Architecture for multi-page angular application

Question: We have to design a angular multi-page application. And the pages look something like this:

I planned to design the page in such a way that each section of the page will have a particular angular controller associated to it and a template will be defined which will be added via the ng-include directive. So basically the page 1 (route ==> '/') will have a 4 different sections which will have 4 different controllers.
Now ofcourse this works fine on a single page, but I am unsure how to define the routes here.
1) Should I have nested controllers, so for page 1 we have a page1Controller and all the other controllers will be under this. Will this be a good design?
or
2) Should I have one controller per page which will make the routing easy and have directives defined for each sections of the page?
Comment: I would use 2 states (for the two pages), with different views (for sections), each view will be a directive.
Comment: Although is not usually recommended, you can use the ngController directive instead of defining the page controller on Routing. I would go that way.
Comment: @MayK : Thanks, By 2 states you mean, both the pages will have just one controller each, right?
Comment: @ItaloAyres: Can you please provide some more details on your approach
Comment: @Mugambo just something like [this](http://jsfiddle.net/qoa5xs4s/)
Answer: I think I would recommend just using multiple named views. Each named view can have its own controller:
$stateProvider
  .state('home', {
    url: '/',
    views: {
      '': {
        templateUrl: 'templates/app.tpl.html',
      },
      'section1': {
        controller: 'Section1Controller as vm',
        templateUrl: 'templates/section1.tpl.html'
      },
      'section2': {
        controller: 'Section2Controller as vm',
        templateUrl: 'templates/section2.tpl.html'
      },
      'section3': {
        controller: 'Section3Controller as vm',
        templateUrl: 'templates/section3.tpl.html'
      },
      'section4': {
        controller: 'Section4Controller as vm',
        templateUrl: 'templates/section4.tpl.html'
      }
    }
  })
  .state('page2', {
    url: '/page2',
    views: {
      '': {
        templateUrl: 'templates/page2.tpl.html',
      },
      'section1': {
        controller: 'Section1Controller as vm',
        templateUrl: 'templates/section1.tpl.html'
      },
      'section2': {
        controller: 'Section2Controller as vm',
        templateUrl: 'templates/section2.tpl.html'
      },
      'section3': {
        controller: 'Section3Controller as vm',
        templateUrl: 'templates/section3.tpl.html'
      }
    }
  })

Then, when you lay out the views, they look something like this:

Comment: But for this I would have to use the `angular-ui` library. Any chance this can be done natively?
Comment: Worth mentioning this uses UI-Router instead of angular-route
Comment: @Mugambo I find it using angular-ui a better option than default lib. If you are willing to change it.
Comment: @ItaloAyres: Thanks. This seems to be much better options. I will give it a try. Thanks Mike
Comment: @Mugambo, specifically it uses the UI Router. I am unsure how this would be done with `ngRoute`, but I would never recommend using `ngRoute`.
Comment: @MikePerrenoud: I just modified the exiting plunkr but I am not able to get it working with the templateUrl in the state (http://plnkr.co/edit/hE6prAL45AhgV6TQ1RHD?p=preview . ). Request your help on this
Comment: Used the absolute naming convention which solved the issue. http://plnkr.co/edit/BZfQU5SaXCnH3skCXfUj?p=preview
Comment: @Anamadeya, great job because that's actually the changes I was just making!
Answer: I would use directives to allow multiple controllers, to re-use code between page1 and page 2, and to prepare for the migration to Angular 2.
Your page would look like:
<section1></section1>
<section2></section2>
<section3></section3>
<section4></section4>

And you will have to write a directive per section:
module.directive('section1', function() {
  return {
    scope: {},
    bindToController: {
    },
    controller: function() { },
    controllerAs: 'vm',
    template: `

This is section1

    `
  }
});

Here is an article to approximate module in Angular 1.x
If you are interested in using TypeScript, here is an tutorial that includes two pages with 2 shared sections using directives as explained above. Look at the section close to the end called 'Sample pages with shared directives.' The tutorial includes a github repository.
In that tutorial, page1 looks like
h1 page1
page1-section1
page1-section2

And, the second page shared the same sections:
h1 page2
page2-section2
page2-section1

The controllers between page1 and page2 are very similar and creates the section tags using the same/shared directives (DigiSection1.Section1Directive):
angular
.module('digiangularjs.page1', [])
.controller('agendaController', Page1Controller)
.directive("page1Section1", [() => new DigiSection1.Section1Directive()])
.directive("page1Section2", [() => new DigiSection2.Section2Directive()])
;

And for the second page, we use the same directives, but
angular
.module('digiangularjs.page2', [])
.controller('page2Controller', Page2Controller)
.directive("page2Section1", [() => new DigiSection1.Section1Directive()])
.directive("page2Section2", [() => new DigiSection2.Section2Directive()])
;

Answer: Going off Mike's answer I would define your route-level templates as single components that are high level layout containers.
.state('page1', {
  url: '/page1',
  template: '<page1></page1>'
})
.state('page2', {
  url: '/page2',
  template: '<page2></page2>
});

Then in your <page> components (which just dictate layout of nested directives/components) you could do:
.component('page1', {
  template: [
    '<section1></section1>',
    '<section2></section2>',
    '<section3></section3>'
  ].join('')
});

Also I realize you wrote "multi page applicaton" which would suggest you don't plan on using a router at all. If that is the case your backend will have to take care of the dynamic layout generation, which is a totally different question.


Unable to access directory created under Network Share in Windows 2012

Question: Gettting below error in accessing folder created under Network Share:- "Windows cannot access \Network_Share\XYZ."
"You do not have permission to access \Network_Share\XYZ. Contact your
network administrator to request access."
Whereas, able to access network share(\Network_Share) from any machine. Only XYZ folder is not accessible.
Kindly suggest please.......
Answer: Looks like you don't have permission access XYZ folder. To check this
Right click on the XYZ folder and go to Properties>Security tab and check whether your ID is having permission to access the folder (You can use "Effective Permission" under the Advance option in Security Tab)
Also check permission in Share tab too.


Commerce: What field to join line_item in order to get product price in custom query?

Question: I'm starting with line 'commerce_line_item' as a base table, and I want to get prices for each of the line item products attached to a Drupal Commerce Order, rather than just the order total. I need a listing of each product sold with prices, and neither views nor Entity Field Query offer enough options for me (I'm creating a master order statistics spreadsheet with phpexcel).
The only promising field I have in the 'commerce_line_item' table is an 'order_id', which I can't find a way to relate back to 'commerce_product' and a 'line_item_label', which does not join on the field 'commerce_product.sku'.
So what would I join on to get pricing information?
I asked a similar question here, but this has me slightly more baffled.
Here's my code below for the query.
  $query = db_select('commerce_line_item', 'i');
  $query->fields('i', array('line_item_label', 'line_item_id', 'quantity', 'data'));
  $query->condition('i.type', 'product', '=');
  $query->leftjoin('commerce_product', 'cp', 'cp.sku = i.line_item_label');
  $query->leftjoin('field_data_commerce_price', 'fcp', 'fcp.entity_id = cp.product_id');
  $query->fields('fcp', array('commerce_price_amount'));
  $query->leftjoin('commerce_order', 'o', 'o.order_id = i.order_id');

snip->
Thanks for your help!
Answer: As you can see in the graph from the question you're linking, there's a field that relates the line item with the products, that's not a database field but a Drupal field. This means that there will be a database table for the field data and revisions and you don't want to deal with that in a db_query, you should be using Entity Field Query instead that will know the database tables and fields to use in each case.
I'm guessing you want to get products from the line items you already have, or the order.
I'd get the line items with EntityFieldQuery:
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'commerce_line_item')
  ->propertyCondition('order_id', <-your-order-id->)
  ->execute();

Now you've got the line items there, wrap them and get the product price:
if (!empty($result['commerce_line_item'])) {
  foreach ($result['commerce_line_item'] as $id => $value) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $id);
    $product_wrapper = $line_item_wrapper->commerce_product;
    $price = commerce_price_wrapper_value($product_wrapper, 'commerce_price', TRUE);
  }
}

Also, all this data is exposed to views, so you can create a view instead.
Comment: Friend, thank you for answering the question. I am with you on wanting to use Entity Field Query or views. Can't use views because, I have to hand query results to phpexcel to build a complex spreadsheet. As for EntityFieldQuery, I looked at it yesterday and didn't think it was powerful enough. Maybe I'm wrong, I will look again and look at your code here. The thing is, I'd like to join arbitrary tables as well as those known to entity. Can EntityFieldQuery do that? I didn't think it could when I looked.
Comment: Alright, I just thought of what should be obvious. If I use EntityFieldQuery, I can just do a db_select query later with the results. No need for a monster query. I am persuaded that after 8 joins a query should be drug out back and shot. I'll convert the query next week when I'm back on the project.
Answer: This was totally the wrong way to go about this as pcambra points out.
Instead, I built a view based on the object Commerce Line Item with relationships to Commerce Order and through Commerce Order to Address Profile and then used views_get_view_result() to get an array of the results which I then handed to the function phpexcel_export() with a little bit of processing.


Bach's Bourree BWV 996 timing issue

Question: I'm currently learning Bach's Bourree, although I'm into second part of it, I have troubles getting the timing correct. Usually it follows a 3 bar flow (except few places, where it really speeds up), but then when I listened to the performances by John Williams and Goran Sollscher, they do slow it up and speed it wherever necessary. Is it possible to learn these via online tutorials or does these minor issues can be corrected only by a teacher at hand sitting beside or any other way ?
Answer: I assume you mean rubato. It's more a feel thing that can't be taught without sounding artificial. It's something you must develop from listening to others using it and feeling the music. There are certain common things such as slowing down near a cadence and speeding up on a climax... usually called accelerando's and ritardando's.
The idea of rubato is basically to make the music sing. A singer never sings perfectly in time and the melody is here and there but the singer, if singing with accompaniment, must be in strict time(assuming the accompaniment is) in some average sense(else he will get out of time). A piano piece is similar. You have the melody, the singer, and the chords(the accompaniment). The chords keep strict time and the melody should weave in and out(but like it is being sung). It is very subtle though and can be very bad if not done with taste/musicality.
This isn't to say you have to strictly do this but I believe Chopin taught it that way and he was suppose to have been the master of rubato. Maybe the way to think about it is that if you play it too perfect in time it will sound robotic(like "midi"). But it should be natural so it doesn't feel jerky. It's also going to depend on the context. Some melodic notes are going to naturally want to fall on the beat and some are going to be ok slightly after and some slightly before to make them work best. The same notes may change the way they work in a different song in the same key.
All this stuff can't really be taught and this is what makes some people better than others. They have some innate understanding or just the way they practiced that make them play the way they do. There are some people with poor time but sound better than some with perfect time(many more factors are involved than time in making something sound good).
In any case I think you should be able to play it in perfect time before you start trying to play around with it. When you learn to make a connection with the music you'll naturally start adding these timing inflections to express the feeling you are expressing. If you try to force it then it will sound unnatural and unmusical.
Comment: There's a definite distinction between 'can't be taught' and 'can't be learned'! I can teach a student to play exactly on time all the time, but I can't teach good rhythm and 'feel'. That's something they have to learn on their own.
Comment: "All this stuff can't really be taught and this is what makes some people better than others..." That's quite an unfair assumption. Yes, it's difficult if you're trying to do it on your own, but if your teacher knows how to do it, then they can teach it. A teacher might say "I'm going to play this phrase like this, you listen, then repeat after me."
Answer: I agree with AbstractDissonance, that this cannot be completely taught. However, this book does a good job of describing it and how to approach it.
Learning the Classic Guitar Part 3 Book/CD Set by Aaron Shearer
It also has a great section on how to prepare for a performance. It makes a few references to Part 1 and 2, but if you are already learning Bach you probably have the knowledge you need to skip 1 and 2.

Bach's Bourree BWV 996 timing issue


Spring when is HTTPSession created if all controllers are singleton

Question: I am learning Spring 3 and trying to understand when is HTTPSession created and what is the lifecycle. All my controllers are singleton (which is by default) and I have configured a HttpSessionListener. I observed that sessionCreated is never getting invoked.
But when I make my LoginController as Session scoped controller then the sessionCreated gets invoked. I want to know how is the HttpSession managed by spring controllers. Also, another question is lets say first request from borowser comes to LoinController and creates the HttpSession - then does the subsequent requests from that browser to different controller(which is singleton) would be using the same HTTPSession or woule it be stateless? Can someone please help.
Answer: Controllers are singleton and stateless. The dispatcher servlet invokes the desired controller method and passes the session to it. The session is obtained by the dispatcher servlet by calling request.getSession(). Since it is s normal servlet, the container "gives" it the request and response that any servlet obtains on each request.
That said, a servlet is also singleton (it has one instance per context). And multiple threads (= requests) are invoking its methods.
And a final note - session-scoped beans are rarely needed. In my experience you can have a whole application without any session-scoped beans.
Comment: @integral_dev the difference is that the session-scoped controllers can have state - i.e. you can assign values to their fields and they will be unique for each user session..
Comment: Yes, by default controllers are singleton but they can configured to be session scoped by using the annotaion. If I have a mix of session scoped and singleton controllers then do they share the same HTTPSession for all requests from same browser?
Answer: A session associates a number of HTTP requests, so once it's created for a user the servlet engine maintains it either using cookies or URL rewriting.
Comment: Thanks for your response. Yes, session associates multiple requests - but even if its forwarded to singleton controllers? Also, how is the lifecyle of that session maintained by servelet engine.


The number of ways of selecting 6 shoes from 8 pairs of shoes so that exactly 2 pairs of shoes are formed

Question: The number of ways of selecting  6 shoes from 8 pairs of shoes so that exactly 2 pairs  of shoes are formed?
My try:

Let us first choose $2$ pairs from $8$ pairs. It can be done in $_{8}C_2$ ways.
Suppose I have chosen pair $(1,2)$ and $(3,4)$. We have to chose other 2 shoes such that one is not a pair of another.
For example if I choose 5 I shouldn't choose it's pair ie 6.  It can be chosen in $_{12}C_1 \cdot _{10}C_1$ ways. So total no. of ways = $_8C_2\cdot _{12}C_1\cdot_{10}C_1=3360$ ways.
Am I correct. Please clarify.
Answer: No you are not correct in your final steps. Here is how you could proceed instead: first choose two complete pairs out of $8$ (as you did), for $\binom82=28$ choices. Then choose two pairs from the remaining $6$ for which you will (later) make two incomplete pairs, for $\binom62=15$ choices. Finally from each of those two incomplete pairs, choose one shoe, for $2^2=4$ choices. Every final outcome can be obtained in exactly one way (this is where it differs from your method) and one gets $28\times15\times4=1680$ possibilities.
You found twice that. That is because you found each solution in two different ways, for the $2!=2$ different orders in which you can choose the two unpaired shoes.
Comment: Sir one doubt at last you are doing 2^2 , but shouldnt it be just 1*1 as such shoes are like xx ,yy in the incomplete ones we just have one way of choosing a incomplete one from them isnt just xy isnt?
Comment: @Buraian check this out
Comment: @ProblemDestroyer I don't quite understand what you want to say, things like $xx$, $xy$ have no meaning intrinsically so you need to explain what you mean to say by this. What is important here is that each shoe is distinguished (it both belongs to a specific pair and within the pair it is either the left or the right shoe), is a choice is really that of a subset, of size $6$, of the set of $16$ shoes (though not all choices are allowed). That means for each pair from which $1$ shoe is taken, we must know which one it is, and that gives $2$ distinct possibilities for each such pair (cont'ed..)
Comment: ... Maybe you think a choice is determined by just telling for every pair whether $0$, $1$ or $2$ of the shoes are chosen, but that is not the case (if it were socks, where we often cannot tell left from right, that might be a plausible interpretation but the question should still make this clear; for shoes it is excluded). If that had been the problem, it would amount to counting the distinct permutations of the sequence $[2,2,1,1,0,0,0,0]$, which is $420$, but each of these gives $\binom22^2\binom21^2\binom20^4=4$ actual solutions.
Answer: When unsure, try with a smaller instance of the problem.
Let's count the ways of choosing 2 shoes from 2 pairs so that they are not in the same pair. Your method would say start with 0 full pairs out of 2 and then multiply by $_4C_1$ and $_2C_1$:
$$\binom{2}{0} \binom{4}{1} \binom{2}{1} = 8$$
But we can count directly: out of $ABab$, the choices fulfilling our conditions are $Aa$, $Ab$, $Ba$, $Bb$. That's not 8 so the formula is not correct.
At the same time it shows what should have been done differently and why: divide your result by 2 to reflect that the last 2 shoes that must not be from the same pair can be picked in any order ($aA = Aa$).
Answer: As you said you can choose $2$ pairs out of $8$ pairs in ${8\choose2}=28$ ways. When these $2$ pairs have been chosen there are $6$ complete pairs left, and you have to choose another $2$ shoes out of these such that no additional pair is formed. This is possible in ${12\choose2}-6=60$ ways. The total number of admisible choices therefore is $28\cdot60=1680$.


Datatables Module not Sorting all Columns

Question: I am using the DataTables module (https://www.drupal.org/project/datatables). The sorting option does not work for all columns, and I am not sure why. I'd like the ability to have all columns sortable as this is just in the DOM, shouldn't that be a possibility?

For example:

Columns that do sort: Content Text, Terms, Dates...
Columns that do not sort: View Conditional (if this then that results)

Here is 2 of the table columns html output:
Title

There is a checkbox in the views datatable settings next the "TITLE" column above...
There is not checkbox enabling sorting on the column below (views conditional):
BLM

EDIT:
This might be due to the sType (https://datatables.net/development/sorting)
In the DataTables module, changing line 298 from FALSE to TRUE allows all sorting... I am sure there is a reason not to allow this, but not sure why. Investigating sType more to apply another elseif on string or whatever type is being produced by the views conditional...
Line 298:
if (empty($options['info'][$field]['sortable']) || !$fields[$field]->click_sortable()) {
        $column_options['bSortable'] = TRUE; //changed from FALSE
      }

Line 301:  //checks what sType the data is:
else {
        // Attempt to autodetect the type of field in order to handle sorting
        // correctly.
        if (drupal_strlen($fields[$field]->last_render) != drupal_strlen(strip_tags($fields[$field]->last_render))) {
          $column_options['sType'] = 'html';
        }
        elseif (is_numeric($fields[$field]->last_render)) {
          $column_options['sType'] = 'numeric';
        }
        elseif ($fields[$field] instanceof views_handler_field_date) {
          $column_options['sType'] = 'date';
        }
        $column_options['bSortable'] = TRUE;

STRING is not one of the options in here. Though the documentation says it could be: http://legacy.datatables.net/usage/columns#sType
I attempted to add it like so real quick with no results:
elseif (drupal_strlen($fields[$field]->last_render) != drupal_strlen(strip_tags($fields[$field]->last_render))) {
      $column_options['sType'] = 'string';
    }

Comment: Can you clarify your question a bit please, to explain what you mean by "all" columns. E.g. by adding a sample of what works and what does not work.
Comment: Please don't post answers inside questions. If you found a way, great! By all means, share it. But share it where it belongs, as an answer.
Comment: @molot, still looking for an answer. This hacks the module, I'd like to know how to address this properly.
Answer: I used a hook_views_data_alter() to add 'click sortable' to the field that didn't have that option.
/**
 * Implements hook_views_data_alter().
 */
function utagta_helper_views_data_alter(&$data) {
  // Allow the views fields to be sortable.
  $data['views']['view']['field']['click sortable'] = TRUE;
}

Answer: If I am reading your question right, you are wanting to sort a Views Conditional field on the database level.  The issue is, the value that would be sorted by is only available after the database work is done and the view starts processing the conditions.  Therefore, the database sorting does not work even if you force the ui to allow it.
What you can do is use a hook_views_pre_render to alter the ordering of the results, effectively sorting it yourself.  I have done this when I was making a site usage report and the client wanted multiple layers of aggregation with filters.  If you have the ajax setting on No, and force the ui to permit sorting on the fields, then you can listen for the sort in the url and use the pre_render to perform it.
Other options are treat this like a rewritten field, and do one of these: sort-view-on-a-rewritten
Comment: Ah, then it is out of my realm of knowledge.  Sorry.
Comment: Sorry, not in the database, using data tables module. It is dom manipulation


Jeditable inserts 'Click to edit' after saving?

Question: My code is:
<code>$(document).ready(function() {
            $('.post_title').editable('editposttitle.php', {
                cancel    : 'Cancel',
                        submit    : 'OK',
                indicator : 'Saving...',
            });
        });
</code>
When saving text the text'Click to edit' is inserted into my element? instead of the saved text?
Any ideas?
Thanks!
Answer: Sorry, found where I was going wrong!
I didn't echo the new value in my php.
Comment: For clarification: Jeditable sets the contents of the jEditable element to whatever content your server returns. If your server returns no content then it sets the contents to "Click to edit"
Answer: <code><?php echo $_REQUEST["value"]; ?>
</code>
Answer: For me the fix was not opening the file up locally as a file, but accessing it through a webserver.  Not sure why this was the case, but as soon as I put the example file on a webserver it started working.


How to extend Views Plugin ViewsSelection.php to have $form_state

Question: I need to add in the current $form_state into the ViewsSelection. I have copied the file /core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php to /modules/custom/fsed_entry/fsed_project_entity_reference_options/src/Plugin/EntityReferenceSelection/ProjectsSelection.php where I have the file overriding views' implementation. However, I can't seem to figure out how to get $form_state into my variables so that I can use a value from another form element. I have been trying to experiment with FormCache but I have not been successful. Any ideas on best approach here?
For background, I need the $form_state because the field that is being rendered (and this plugin is used on) here was ajaxed in and I want to pass in a value that I can add onto the handler_settings -> view -> arguments that this plugin uses.
Answer: There is no form state, at least not with autocomplete. And since the same code is designed to work with autocomplete and other widgets, it can't rely on form state anywhere.
If you have autocomplete you can possibly pass in the settings in the entity_autocomplete form element which should be passed to your plugin. Not sure about other widgets, you might need your own widget to be able to do that.
Comment: Thanks so much for answering Berdir. I am actually using the select list widget but it works of some of the same stuff as autocomplete so your comments certainly make sense. Do you think that using `FormCache` might allow me to retrieve the cached form state from the current user? I mean we have `$current_user` and we also can add in the `FormCacheInterface` I am just not sure if I would be chasing unicorns if I try it.
Comment: Reading your comment again I am kind of understanding what you are describing now. I could definitely add that data onto the element before it is sent. I might have to change to autocomplete or create a new select widget that is more similar to the autocomplete perhaps.


Redirecting specific traffic to amazon AWS

Question: My server has recieved sudden increase in the (read) web traffic, requesting many map image tiles, and apache cannot handle it.
Apache cannot even handle the redirections! The average load I get in my CentOS machine is more then 200..
Is there some software out there that can redirect SOME of the traffic, such as only the traffic from specific directory (such as http://example.com/maptiles/abc.png) to a different address (sucha as http://s3.amazonaws.com/mytiles/abc.png) ?
can this be done by HAProxy?
Comment: Use Load Balancing, man..
Answer: You could do that, but before you go to that extreme, consider improving the performance of your existing service, including (perhaps) putting in a caching reverse proxy such as Varnish.  By the time you get to the point where your only option is proxying some traffic out to S3, you're probably going to be dead in the water anyway.
What you might want to consider doing instead is putting some content on a separate subdomain (such as maptiles.example.com), pointing that to S3, and changing the links to those assets in your site code to reference that subdomain.  That'll take a fair chunk of load off your machine.
Comment: You really needed to be thinking of this before you got busy -- or you should have sought the advice of experts to manage your infrastructure in advance, so you could effectively manage these sorts of peak periods.
Comment: Thanks a lot. I think cacheing is not an option, since most of the data is static, but I'll check it. The sub domain idea is great, but the problem is that the traffic also comes from an iOS app that cannot be changed easly. I'll do that in the app and submit it to Apple. The problem is that the site is dead now, and this is the most important time of the year (holidays).
Answer: If you think your server reached its limit, you can use haproxy as load balancer and direct all traffic to it. Then, it will redirect the requests to the configured backends. Some of the great features of haproxy include:

Health-check of backend servers.
Very flexible ACLs can be built to redirect traffic.
Stable and can handle many many concurrent connections.
Answer: I'd say you should install - better if you can do it on a dedicated instance, but would also work on the same - an instance of NGINX (a simple event webserver/beautiful load balancer solution) in front of your apache web server.
You could add a Varnish cache (to NGINX, if you have enough RAM available) to manage those static request internally, without involving your apache setup. This is a very simple setup that would allow you to grow horizontally (adding more server with Apache and doing the redirect to them from NGINX).
You should also understand where your bottleneck are located. Load of 200+ could be related to high CPU (maybe you have MySQL running locally and you are missing indexes?), or to disk I/O (look at iowait% from iostat GNU/Linux command) which could be related to those static files requests.
Understanding the bottleneck should be the first step then offload everything you can.


A problem related to coefficient of $\int{(t-a)^n}dt$

Question: Let's make some antiderivative of $(t-a)^n$.
When $n=1$, we get $\frac{1}{2}t^2-at$ for the antiderivative (ignoring some constant). Now when we put $t=a$, we get $-\frac{1}{2}a^2$ and $-\frac{1}{2}$ is the coefficient.
When $n=3$, we get $\frac{1}{4}t^4-at^3+\frac{3}{2}a^2t^2-a^4t$ for the antiderivative and we get $-\frac{1}{4}$ for the coefficient by putting $t=a$.
When $n=5$, in the same manner, we get $-\frac{1}{6}$ for the coefficient.
The case when exponent $n$ is even, it is straightforward to know that the coefficient always comes out as $\frac{1}{n+1}$. However I'm stuck with finding a proof for when $n$ is odd.
Any help would be grateful, thanks.
Edit: I've already gotten a great answer however my original purpose of posing this question was to approach this question in regard of the pattern of binomial coefficients. If there is someone who knows some proofs that looks somewhat more 'discrete', I would be grateful to know any of them. Thanks.
Edit: My question can be substituted as follows.
Let's make an array of coefficients of $(a-b)^n$ as Pascal's Triangle.
Then we can see the following.
\begin{array}{c}
+1 \\
+1 \quad -1 \\
+1 \quad -2 \quad +1 \\
+1 \quad -3 \quad +3 \quad -1 \\
+1 \quad -4 \quad +6 \quad -4 \quad +1 \\
+1 \quad -5 \quad +10 \quad -10 \quad +5 \quad -1 \\
+1 \quad -6 \quad +15 \quad -20 \quad +15 \quad -6 \quad +1 \\
+1 \quad -7 \quad +21 \quad -35 \quad +35 \quad -21 \quad +7 \quad -1 \\
\end{array}
Now, let's multiply each coefficient by $\frac{1}{n+1}$, $\frac{1}{n}$, $\frac{1}{n-1}$, $\frac{1}{n-2}$ $\cdots$, $\frac{1}{1}$ as the following.
\begin{array}{c}
\frac{+1}{1} \\
\frac{+1}{2} \quad \frac{-1}{1} \\
\frac{+1}{3} \quad \frac{-2}{2} \quad \frac{1}{1} \\
\frac{+1}{4} \quad \frac{-3}{3} \quad \frac{+3}{2} \quad \frac{-1}{1} \\
\frac{+1}{5} \quad \frac{-4}{4} \quad \frac{+6}{3} \quad \frac{-4}{2} \quad \frac{1}{1} \\
\frac{+1}{6} \quad \frac{-5}{5} \quad \frac{+10}{4} \quad \frac{-10}{3} \quad \frac{+5}{2} \quad \frac{-1}{1} \\
\frac{+1}{7} \quad \frac{-6}{6} \quad \frac{+15}{5} \quad \frac{-20}{4} \quad \frac{+15}{3} \quad \frac{-6}{2} \quad \frac{1}{1} \\
\frac{+1}{8} \quad \frac{-7}{7} \quad \frac{+21}{6} \quad \frac{-35}{5} \quad \frac{+35}{4} \quad \frac{-21}{3} \quad \frac{+7}{2} \quad \frac{-1}{1} \\
\end{array}
When $n$ is even, then it is straightforward that the sum of each floor equals to $\frac{1}{n+1}$.
However, when $n$ is odd, the numbers get quite messed up. So I'm stuck with deducing some 'discrete' proof that it equals to $-\frac{1}{n+1}$.
If someone knows some other approach than using the fundamental theorem of calculus it would be grateful if I could know them. Thanks.
Answer: Setting the constant equal to $0$ and taking $t=a$ means you are computing :
$$I_n = \int_0^a (t-a)^n\text dt$$
A change of variable $x = t-a$ tells us that :
$$I_n = \int_0^a(-x)^n\text dx$$
And we can compute :
$$I_n = \frac{(-1)^n a^{n+1}}{n+1}$$
In particular when $n$ is odd, you have :
$$I_n = -\frac{a^{n+1}}{n+1}$$
Another proof
\begin{align}
I_n &= \int_0^a (t-a)^n \text dt \\
&= \sum_{k=0}^n {n \choose k}\int_0^a t^{k} (-a)^{n-k}\text dt \\
&= a^{n+1}\sum_{k=0}^n {n\choose k} \frac{(-1)^{n-k}}{k+1} \\
\end{align}
Then, we use  :
$$\frac{1}{k+1}{n\choose k} = \frac{1}{n+1}{n+1\choose k+1}$$
Therefore :
\begin{align}
I_n &= \frac{a^{n+1}}{n+1} \sum_{k=0}^{n} {n+1 \choose k+1} (-1)^{n-k} \\
&=\frac{a^{n+1}}{n+1} \sum_{k=1}^{n+1} {n+1 \choose k} (-1)^{n+1-k}\\
&= \frac{a^{n+1}}{n+1}\left( \sum_{k=0}^{n+1} {n+1 \choose k} (-1)^{n+1-k} - (-1)^{n+1} \right) \\
&= \frac{a^{n+1}}{n+1}\left(- (-1)^{n+1} \right) \\
&= \frac{(-1)^n a^{n+1}}{n+1}
\end{align}
Comment: Thank you for your clear answer. Actually I was approaching this question in terms of the pattern of binomial coefficient. Do you know any kind of proof that looks more discrete(something like that deals with the pattern of binomial coefficient) other than using the fundamental theorem of calculus?
Comment: $I_n=\frac{(-1)^na^{n+1}}{n+1}$
Comment: Oh, I think your additional combinatorial method answers my curiosity. I will definitely check and practice with your method by myself. Thank you for spending your time on my question.


How to insert a HTML Page inside HTML File without conflicting styles of each other

Question: I have an HTML stored in database. I want to add that HTML page inside a HTML. the page has inline styling cdn of bootstrap etc. If I just add it inside a div element it affects the styling of the page that's it added to.
How can I insert the html page in the html without conflicting styles of each other?
Comment: `iframe` is your friend => https://www.w3schools.com/html/html_iframe.asp
Comment: Use iframe as solution check this answer maybe give a idea how to solve https://stackoverflow.com/questions/53987873/how-to-embed-a-scoped-html-css-in-a-document
Answer: Use this code for your HTML and CSS:
HTML:

CSS:
.iframe-container{
    position: relative;
    width: 100%;
    padding-bottom: 56.25%;
    height: 0;
}
.iframe-container iframe{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
}

The JS is pretty interesting, Using the contentWindow property you can set it without needing to write to any file,
var iframe = document.getElementById("my-Iframe");
iframe.contentWindow.document = x; //x stands for the code that you want to
put

Further Readings: https://www.w3schools.com/jsref/prop_frame_contentwindow.asp


Is it a Fermat polynomial?

Question: A Fermat polynomial is a polynomial which can be written as the sum of squares of two polynomials with integer coefficients. Let $f(x)$ be a Fermat polynomial such that $f(0)=1000$. Prove that $f(x)+2x$ is not a Fermat polynomial.
Comment: So then $f(x)=[a(x)]^2+[b(x)]^2$ for polynomials $a,b \in \mathbb{Z}[x]$?
Comment: Yep. That's right.
Answer: Let $f(x) =  [p(x)]^2 + [q(x)]^2$.  We have $p(0)^2 + q(0)^2 = f(0) = 1000 \equiv 0\pmod{4}$, so $p(0)$ and $q(0)$ must both be even.
Consider the coefficient $c_1$ of $x$ in $f(x)$.  It must be $c_1 = 2ap(0) + 2bq(0)$, where $a$ and $b$ are integers (the coefficients of $x$ in $p(x)$ and $q(x)$, respectively).  Since $p(0)$ and $q(0)$ are even, it follows that $c_1$ is divisible by $4$.
Then the coefficient of $x$ in $g(x) = f(x)+2x$ is $c_1+2$ and is not divisible by $4$.  But $g(0) = f(0)$, and so if $g(x)$ were a Fermat polynomial, then the same argument would show that the coefficient of $x$ in $g(x)$ would be divisible by $4$.  Hence $g(x)$ is not a Fermat polynomial.
Answer: $1000$ can be expressed as a sum of two squares in two different ways: either $1000 = 10^2 + 30^2$ or $1000 = 18^2 + 26^2$. Thus if  $f(x)$ is a Fermat polynomial with $f(0) = 1000$ and $f(x) = [a(x)]^2 + [b(x)]^2$, then $a(0)^2 + b(0)^2 = 1000$ so that (wlog) either $a(0) = 10$ and $b(0) = 30$, or $a(0) = 18$ and $b(0) = 26$.
Writing $a(x) = xp(x) + 10$ and $b(x) = xq(x) + 30$ for $p,q \in \mathbb Z[x]$ yields $$f(x) = a(x)^2 + b(x)^2 = x^2 (p(x)^2 + q(x)^2) + 80x(p(x) + q(x)) + 1000,$$ and writing $a(x) = xp(x) + 18$ and $b(x) = xq(x) + 26$ for $p,q \in \mathbf Z[x]$ yields $$f(x) = a(x)^2 + b(x)^2 = x^2 (p(x)^2 + q(x)^2) + 88x (p(x) + q(x)) + 1000.$$
In both cases we have that $\displaystyle \left.\frac{f(x) - 1000}{x}\right|_{x = 0}$ is a multiple of $8$.
$f(x)$ and $f(x) + 2x$ can't both have this property.

Is it a Fermat polynomial?


Help with Cross-Domain file for ActionScript 3 Socket

Question: Here is My ActionScript Code:
  var S:Socket=new Socket("127.0.0.1",2222);

Here is My CrossDomain.XML File (Located at http://127.0.0.1/crossdomain.xml)
  <?xml version="1.0"?>
  <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
  <cross-domain-policy>
  <allow-access-from domain="*" to-ports="2222"/>
  </cross-domain-policy>

Here is The Error I Am Getting
  Ignoring policy file at xmlsocket://127.0.0.1:2222 due to incorrect syntax.

Having never used one before, I don't understand what's wrong with the syntax of my CrossDomain file.
Please Help.
Answer: Socket policy files work a little differently than HTTP policy files; in particular, they aren't served via HTTP, or at port 80.
Instead, Flash Player checks for a policy file server (port 843 by default), or if necessary, on the socket you're opening (for you, port 2222).
A policy file server is a socket which responds to a <policy-file-request/> with a valid policy file.  What's happening with your message is likely that it's sending its request and getting something other than a policy file back, hence invalid syntax from port 2222.
There are a lot of resources out there, and a number of questions here on SO.  Here's one tutorial from Adobe.
Comment: This was definitely the answer to my question!  Once I programmed my socket to return a my crossdomain.xml file OVER THE SOCKET when it got a "" message, suddenly all Flex's complaints about it vanished.  Thank you!


Importing Python packages with same name

Question: I have two packages installed with the same name, one globally and one locally (a development version). My PYTHONPATH has to local directory in it. Now, when importing in Python, I want to choose which package I take. Is there any way to do this?
Comment: Consider using a virtualenv instead of trying to perform hacks like this on the python code level.
Answer: The easiest way is giving the local package a different name and then using import foo_dev as foo instead of just import foo
Comment: Rename the folder where the package is located.
Comment: I now that this is really a beginner's question, but how can I gave the package a different name?
Comment: @ThiefMaster Simplest solution is often best. Good call. +1 to answer and comment.


mongoDB get the latest date for an array

Question: I like to get the latest enter and exit timestamp for a given user and for a given location. The collection is like this
{ "ActivityList" : [
{ "type" : "exit",
      "timestamp" : Date( 1348862537170 ),
      "user" : { "$ref" : "userProfile",
        "$id" : ObjectId( "4fdeaeeede26fd298262bb80" ) } },
    { "type" : "entry",
      "timestamp" : Date( 1348862546966 ),
      "user" : { "$ref" : "userProfile",
        "$id" : ObjectId( "4fdeaeeede26fd298262bb80" ) } },
       { "type" : "entry",
      "timestamp" : Date( 1348870744386 ),
      "user" : { "$ref" : "userProfile",
        "$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
    { "type" : "exit",
      "timestamp" : Date( 1348878233785 ),
      "user" : { "$ref" : "userProfile",
        "$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } } ],
  "Location" : { "$ref" : "loc",
    "$id" : ObjectId( "4fd410f0e7e994b59054b824" ) },
  "_id" : ObjectId( "4fe8f3c6e7e9ebe3697ee836" ) }

I tried something like this but does not work
db.collection.group(
{
    keyf: function(doc) {
        return {
            location    :doc.Location._id,
             userid     : doc.ActivityList.user._id,
             actiontype : doc. ActivityList.type
        };
    },
    reduce: function(obj,prev) {
        if (prev.maxdate < obj. ActivityList.timestamp) {
            prev.maxdate = obj. ActivityList.timestamp;
        }
    },
    initial: {maxdate:0}
});

Thanks for your help.
Answer: A simple $group won't work for your data structure and finding/filtering the maximum values within an array.  You would have to iterate the array to find the maximum values, which would be more efficiently done by retrieving the document and iterating in your application code.
A possible server query approach in MongoDB 2.2 would be to use the new Aggregation Framework:
db.activity.aggregate(

    // Find matching location documents first (can take advantage of index)
    { $match : {
        Location: {
            "$ref" : "loc",
            "$id" : ObjectId("4fd410f0e7e994b59054b824")
        }
    }},

    // Unwind the ActivityList arrays as a document stream
    { $unwind : "$ActivityList" },

    // Filter activities to the user reference of interest
    { $match : {
       'ActivityList.user': {
            "$ref" : "userProfile",
            "$id" : ObjectId("4fdeaeeede26fd298262bb80")
        }
    }},

    // Group the stream by activity types, and get the timestamp for the latest of each
    { $group : {
        _id : "$ActivityList.type",
        latest: { $max: '$ActivityList.timestamp' }
    }}
)

Sample result:
{
    "result" : [
        {
            "_id" : "entry",
            "latest" : ISODate("2012-09-28T20:02:26.966Z")
        },
        {
            "_id" : "exit",
            "latest" : ISODate("2012-09-28T20:02:17.170Z")
        }
    ],
    "ok" : 1
}

Comment: Thanks a lot. works with no problem. Looks like I need to some effort in learning the aggregate function in Mongo 2.2. Thanks Again.


Who is this football player?

Question: My brother pointed out that this football player strongly resembles me, but he doesn't know who it is.  Who is my doppelganger? It looks like the player in the rear (third person back, on the right) is wearing a Baltimore Ravens helmet.  Of course, they could be the opposing team.
Comment: This question is off-topic because it is a photo-finder question, a type of source/research request. Meta discussion in regards to photo-finder questions can be found [here](http://meta.sports.stackexchange.com/questions/476/is-photo-finder-type-questions-on-topic).
Answer: That would be Bruce Gradkowski. He is Ben Roethlisberger's backup QB for the Pittsburgh Steelers.

Who is this football player?


Bass buzz how do I fix it?

Question: I'm quite new to playing the bass guitar and I'm hearing a lot of buzz. I mainly play with my thumb. Could that be contributing to it? I do play somewhat hard and I'm trying to calm down with it, but is there anything else that might help?
By the way, I have a Schecter Stiletto Extreme 4.
Comment: @DavidBowling - 'play' closer to the frets ought to be 'press' closer. Play to beginners translates as pluck. You're correct, of course!
Comment: If it is fret-buzz that you are experiencing, you may need to play closer to the frets. It takes less pressure and is generally easier to fret notes when your fingers are closer to the fret you are playing.
Comment: https://music.stackexchange.com/questions/1053/string-buzz-on-bass-guitar and https://music.stackexchange.com/questions/30333/bass-guitar-fret-buzz-should-i-care might be useful.
Comment: Where is the buzz coming from? What sort of buzz? When does it happen? Impossible to answer this question without knowing these things.
Answer: Seems like the action may be a bit low for your style of playing. When the strings are close to the fingerboard, they will rattle against it when played hard, as the vibrations are large, causing them to touch the other frets between where you press and the bridge. It may only be a couple of those fretwires - test by playing every note on the neck, ascending and descending, to ascertain if it's worse on particular frets. The neck may not have enough relief in it.
Another cause is not pressing hard enough, or close enough to the fretwire. Pressing on the fret close to the bridge direction makes a better angle for a cleaner sound.
A slight possibility is that the strings are too loose for the open notes - for example if it's downtuned a fair bit, you may need to up the string gauge to regain the tension needed for that particular scale length.
Answer: Assuming there's not a problem with your setup as described by Tim, Try listening through headphones... you're ears are very close to the instrument but what folks will hear is coming from your amplifier. If you listen via headphones you'll put yourself more in the position your audience will be in.
Your buzz won't be as bad as it sounds to you.
I also wouldn't focus(obsess) on it, you'll adjust your technique naturally over time and it will go away. For example, when I was learning drums I bought a toe stop for my kick pedal because my foot would slip off. After about 2-3 months I never got close to that toe-stop because my foot was just naturally keeping the right place on the pedal.

Bass buzz how do I fix it?


Dynamic sql syntax issues for date time variable

Question: For this code, when I introduce the 2 date variables the code errors with an error.
The Error is
Msg 137, Level 15, State 1, Line 8
Must declare the scalar variable "@STARTDATE".
Msg 137, Level 15, State 1, Line 9
Must declare the scalar variable "@ENDDATE".

Any idea how to get round this as my brain is now officially dead ?
DECLARE
    @Query1  AS NVARCHAR(MAX),
    @Startdate DATETIME,
    @Enddate DATETIME

SET @STARTDATE = '10-JAN-2012'
SET @ENDDATE = '11-JAN-2012'

SET @Query1 = '

;WITH CTE AS
(
    select COALESCE( PT.[description] , ''Grand Total'') AS [Transaction Type],
           Sum (AI.PRICE_INC_VAT) AS [AMOUNT (ú) CREDIT],
           P.[DESCRIPTION] AS [PRODUCT TYPE]

From  [dbo].[T1] C
join [dbo].[T2] S on S.[Customer_ID]=C.[Customer_ID]
join [dbo].[T3] SO on SO.[SITE_ID]=S.[SITE_ID]
join [dbo].[T4] OI on OI.[ORDER_ID]=SO.[SITE_ORDER_ID]
left join [dbo].[T5] P on P.[PRODUCT_ID]=OI.[PRODUCT_ID]
JOIN [dbo].[T6] AI ON  AI.ORDER_ITEM_ID = OI.ORDER_ITEM_ID
JOIN [T7] JBAI ON JBAI.ACTION_ITEM_ID = AI.ACTION_ITEM_ID
JOIN T8 JB ON JB.JOB_BATCH_ID = JBAI.JOB_BATCH_ID
JOIN [T9] PA on PA.PAYMENT_ID=JB.PAYMENT_ID
LEFT JOIN [T10] CU ON JB.CUSTOMER_USER_ID = CU.CUSTOMER_USER_ID
JOIN [T11] PT ON PT.PAYMENT_TYPE_ID=PA.PAYMENT_TYPE_ID
LEFT JOIN [T12] ON SU.SYS_USER_ID=JB.SYS_USER_ID

where P.[PRODUCT_CATEGORY_ID]= ''PADS''
    and C.COMPANY_ID= ''19992''
    and PA.DATE_RECEIVED BETWEEN @Startdate AND @Enddate

group by PT.DESCRIPTION, P.DESCRIPTION
)'

Answer: Your parameters are out of scope with your sql query. You need to pass the parameters into the sql string. You will notice that you also have to cast the parameter as a varchar so it can be concatenated to the string:
DECLARE
    @Query1  AS NVARCHAR(MAX),
    @Startdate DATETIME,
    @Enddate DATETIME

SET @STARTDATE = '10-JAN-2012'
SET @ENDDATE = '11-JAN-2012'

SET @Query1 = '

;WITH CTE AS
(
    select COALESCE( PT.[description] , ''Grand Total'') AS [Transaction Type],
           Sum (AI.PRICE_INC_VAT) AS [AMOUNT (ú) CREDIT],
           P.[DESCRIPTION] AS [PRODUCT TYPE]

From  [dbo].[T1] C
join [dbo].[T2] S on S.[Customer_ID]=C.[Customer_ID]
join [dbo].[T3] SO on SO.[SITE_ID]=S.[SITE_ID]
join [dbo].[T4] OI on OI.[ORDER_ID]=SO.[SITE_ORDER_ID]
left join [dbo].[T5] P on P.[PRODUCT_ID]=OI.[PRODUCT_ID]
JOIN [dbo].[T6] AI ON  AI.ORDER_ITEM_ID = OI.ORDER_ITEM_ID
JOIN [T7] JBAI ON JBAI.ACTION_ITEM_ID = AI.ACTION_ITEM_ID
JOIN T8 JB ON JB.JOB_BATCH_ID = JBAI.JOB_BATCH_ID
JOIN [T9] PA on PA.PAYMENT_ID=JB.PAYMENT_ID
LEFT JOIN [T10] CU ON JB.CUSTOMER_USER_ID = CU.CUSTOMER_USER_ID
JOIN [T11] PT ON PT.PAYMENT_TYPE_ID=PA.PAYMENT_TYPE_ID
LEFT JOIN [T12] ON SU.SYS_USER_ID=JB.SYS_USER_ID

where P.[PRODUCT_CATEGORY_ID]= ''PADS''
    and C.COMPANY_ID= ''19992''
    and PA.DATE_RECEIVED BETWEEN '+ convert(varchar(10), @Startdate, 120)
    + ' AND '+ convert(varchar(10), @Enddate, 120) +'

group by PT.DESCRIPTION, P.DESCRIPTION
)'

I am not sure why you are using dynamic SQL for this procedure though. This can be easily performed without the use of dynamic SQL:
;WITH CTE AS
(
    select COALESCE( PT.[description] , 'Grand Total') AS [Transaction Type],
           Sum (AI.PRICE_INC_VAT) AS [AMOUNT (ú) CREDIT],
           P.[DESCRIPTION] AS [PRODUCT TYPE]

From  [dbo].[T1] C
join [dbo].[T2] S on S.[Customer_ID]=C.[Customer_ID]
join [dbo].[T3] SO on SO.[SITE_ID]=S.[SITE_ID]
join [dbo].[T4] OI on OI.[ORDER_ID]=SO.[SITE_ORDER_ID]
left join [dbo].[T5] P on P.[PRODUCT_ID]=OI.[PRODUCT_ID]
JOIN [dbo].[T6] AI ON  AI.ORDER_ITEM_ID = OI.ORDER_ITEM_ID
JOIN [T7] JBAI ON JBAI.ACTION_ITEM_ID = AI.ACTION_ITEM_ID
JOIN T8 JB ON JB.JOB_BATCH_ID = JBAI.JOB_BATCH_ID
JOIN [T9] PA on PA.PAYMENT_ID=JB.PAYMENT_ID
LEFT JOIN [T10] CU ON JB.CUSTOMER_USER_ID = CU.CUSTOMER_USER_ID
JOIN [T11] PT ON PT.PAYMENT_TYPE_ID=PA.PAYMENT_TYPE_ID
LEFT JOIN [T12] ON SU.SYS_USER_ID=JB.SYS_USER_ID

where P.[PRODUCT_CATEGORY_ID]= 'PADS'
    and C.COMPANY_ID= '19992'
    and PA.DATE_RECEIVED BETWEEN @Startdate AND @Enddate

group by PT.DESCRIPTION, P.DESCRIPTION
)

Comment: I would add that what was asked so far doesn't seem to have any real need for dynamic SQL at all -- a stored procedure with \@Stardate and \@Enddate arguments would do fine.
Comment: Better yet, use sp_executesql so that you aren't concatenating strings.
Comment: @RossPresser I was updating my answer to include that note when you commented.
Answer: If this really needs dynamic SQL, you should do the following:
-- USE UNAMBIGUOUS FORMATS PLEASE!

SET @STARTDATE = '20120110';
SET @ENDDATE = '20120111';

SET @Query1 = ';WITH CTE AS
...
    and PA.DATE_RECEIVED BETWEEN @STARTDATE AND @ENDDATE
    group by PT.DESCRIPTION, P.DESCRIPTION
)';

EXEC sp_executesql
  @Query1,
  N'@STARTDATE DATETIME, @ENDDATE DATETIME',
  @STARTDATE, @ENDDATE;

However unless I'm missing something there is no need for dynamic SQL here.


How to get the image from the url and store in the custom path?

Question: if(empty($nodevalue->field_beachesimages)){
    $imageurl=array(explode(",",$nodevalue->field_beach_migrateurlhidden[$nodevalue->language]['0']['value']));
    foreach ($imageurl as $imagechange) {
        $countimagurl=count($imagechange);
        if($countimagurl>10)
            $imgdata=9;
        else
            $imgdata=$countimagurl;
        for($i=0;$i<$imgdata;$i++){
           $image =$imagechange[$i];
           $file = system_retrieve_file($image,'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);
           echo "
";print_r($file);echo "
"; exit;
           file_save($file);
           file_usage_add($file, 'iks_beaches', 'beaches', $file->fid);
        }
    }
}

Comment: what is the problem in the above code? Are u getting any errors? Pls mention
Comment: i use the above code but no folder creation takes place :(
Comment: You can use drupal_mkdir() to create new folder in the code above Link : https://api.drupal.org/api/drupal/includes!file.inc/function/drupal_mkdir/7
Answer: Hope this will help you.
In Drupal 7 , system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

You need to create a folder beachesmigration inside sites\default\files.
By using system_retrieve_file it will be store your images inside beachesmigration folder with the filename you no need to specify the filename manually.

 $image = 'http://wordpress.ikitesurf.com/wp-content/uploads/2012/09/2032239599_fdce5e0ab0_z.jpg';
//I have used picture folder to store images using image field settings
 $file = system_retrieve_file($image, 'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);

Source
Answer: Try this :
function savefile($filepath, $uid = 1) {
  global $base_url;
  if (filesize($filepath) == 0 ) {
    return array();
 }
  $file = (object) array(
    'uid' => $uid,
    'uri' => $filepath,
    'filemime' => file_get_mimetype($filepath),
    'status' => 1,
  );
  if(file_exists($filepath)) {
    $file = file_copy($file, 'public://');   //Change path here
    return $file;
  } else {
    return array();
  }
}

$file = savefile("http://wordpress.ikitesurf.com/wp-content/uploads/2012/09/2032239599_fdce5e0ab0_z.jpg");

Comment: Hello. Yuor answer does not mention `$pathval` or `beachesmigration`, so how it is supposed to help?


Predict the price of single part after running the ML algorithm

Question: I am working on a problem to predict the price of a mechanical part. I collected all the necessary data and variables.($1200 \times 25$)
I have build multiple models using $log$ transformations of the response variable and two of the predictors. I have fairly good accuracy: 89%. Testing and validation of the model are done. There is no multicollinearity. $R^2$, F statistics, P value and adjusted $R^2 - $  everything is perfect. I have predicted the values on the test set. (250 parts values). Predictions are spot on.

Model is -
<code>test <- lm (log(price) ~ log(SurfaceArea) + log(Quantity) + density + Complexity +
            Y + X + PricePerKg, data = Training)
</code>
Now, I want to know how can I predict the price of just one part from the coefficients from my model. Is there any way to predict the price of just one part on the basis of the results?
I want to predict the price of one part if I have the values for: SurfaceArea, quantity, density, complexity Y, X, [PricePerKg].
I hope my problem is clear now.
Comment: I assume that PricePerKg is given, too, which is why I added it in brackets at the end
Comment: `help("predict.lm")`
Comment: I think, help("predict.lm"), will predict for a whole test set not an individual part.
Comment: You think wrong. You can pass new data to `predict` and it will then only predict for this data.
Comment: Yes, you can use $predict$ with $newdata= [a~data~ frame ~that~ only~ has~ one~ row]$, which is the predictors you mean to predict with. But they you will be getting the log(price) rather than price. Hopefully you won't have any problem converting it to price.
Answer: If we assume your model parameters are given by $w_{parname}$, the predicted price of one part $\hat{price}$ is given by
$$
\begin{aligned}
\hat{price} &= exp(w_0) \times \frac{SurfaceArea^{w_{SurfaceArea}}}{ Quantity^{|w_{Quantity}|}} \times \\
&\times exp \bigg( w_{density} density + w_{machinability} machinability + \\
& + w_{Complexity} Complexity + w_Y Y + w_z Z + \\
& + w_{PricePerKg} PricePerKg \bigg), \\
& given ~ w_{quality}<0
\end{aligned}
$$
where the data

SurfaceArea, quantity, density, machinability, complexity Y, Z, [PricePerKg]

are provided.

The R solution, as indicated above

v2_data = data.frame(Price=c(...), Y=c(...), X=c(...), Price_Per_kg=c(...), Surface_area=c(...),  Complexity=c(...), density=c(...), Order_Qty=c(...))
ModelY <- lm(log(Price) ~Y + X + Price_Pr_kg + log(Surface_area) + Complexity + density + log(Order_Qty),data=v2_data)
newdata=data.frame(Price=c(1000), Y=c(12), X=c(-3), Price_Per_kg=c(42), Surface_area=c(3.14),  Complexity=c(8), density=c(1.04), Order_Qty=c(144))
logPrice_preds<-predict.lm(ModelY,newdata,type="terms")
Price_preds <- exp(logPrice_preds)
Comment: Thank you so much sir, Just a clarification. First part of the formula you just told me Is it Price = (SurfaceArea^B1 * Quantity^B2) * exp(B3*density + B4*machinability + B5*Complexity + B6*Y + B7*Z + B8*Price Per density) What about the intercept ? And the coefficient for quantity is negative.
Comment: The intercept $w_0$ turns into $exp(w_0)$ and it multiplies this whole expression. The coefficient for quantity may be negative. There is nothing wrong with that.
Comment: I am sorry sir, But Price_preds gives => Y = 2.1044,   X = 0.977, PPKG = 0.9856, log(SA) = 3.909, Complexity = 1.58, density= 0.94, log(quantity) = 0.866, attr("constant") = 6.32, when I input values- 609,61, 29, 841450,5,1.08, 12 in same order into newdata to predict the price. Didn't get the Price, just got these above mentioned values only. Am I missing anything here.


How can others run my docker image from my local network?

Question: I've successfully created (using ubuntu VB) a docker image
What would be the best approach to let others from my local network run that image using ssh? I've been searching for quite some time and couldn't find anything that'd help.
I believe I have to map to a port somehow using the dockerfile and forward that port from my VM to my actual OS, but I don't know exactly how to do it or if it that's how is supposed to be done.
Any tips at all would be great help
TL;DR: Created a docker image using an ubuntu VB and I want others from my local network to be able to use it using ssh
Comment: Ideally you should be using a docker management tool (like swarm/kubernetes) etc to manage you containers, but if you just want to start you container and expose it to others, you can simply start your container by running this command docker run -d -p 4022:22 your_docker_image ( supposing the sshd service inside the container is running on port 22 and you want to expose it on port 4022 )
Comment: I've tried that and the container ends within seconds of the execution, which is to be expected considering the app just prints something. I tried to use docker start [container_id] --attach but to no avail.  Could you elaborate your answer please?
Comment: Can you paste your docker file here ?
Comment: FROM python:3; ADD my_script.py / ; EXPOSE 9300; CMD ['python", "./my_script.py" ]
Comment: Can you also provide me your script.py. your docker container will exit if the  main process finishes and this seems to be a case with your script.
Comment: it does, it's a simple print. I've used tail /dev/null so the container doesn't close itself.
Comment: So, is it workiworking fine now after you added tail /dev/null?
Comment: The container doesn't stop anymore but I still couldn't make it work. As in doing localhost:9300 won't work and the port is not seen on the windows (host of VM)
Comment: That won't work for obvious reasons. Are you running a linux machine as a vm on virtualbox and your host OS is windows ?
Answer: Ok, made it work, here is how I did it:

Run the image
Use docker port [containerID] 80, to see the port of the running computer
Port forward that port from VirtualBox
settings
Set inbound / outbound rules for that specific port from windows firewall settings


Incorrect interaction coefficients in summary of a GLM in R

Question: I wrote a model to look at the effect of species + treatment on swimming speed in copepods. I had a bunch of videos and pulled the average swimming speed from each video. Here's a barplot of the data.
<code>> model <- lm(log(Avg_Speed) ~ Species + Treatment + Species:Treatment,
+               data = total)
> summary(model)

Call:
lm(formula = log(Avg_Speed) ~ Species + Treatment + Species:Treatment,
    data = total)

Residuals:
     Min       1Q   Median       3Q      Max
-1.70807 -0.29267 -0.06822  0.26581  1.77693

Coefficients:
                               Estimate Std. Error t value Pr(>|t|)
(Intercept)                      1.1753     0.1050  11.192  < 2e-16 ***
SpeciesAcartia                  -0.5187     0.1560  -3.324  0.00107 **
SpeciesParvo                    -1.6376     0.1560 -10.494  < 2e-16 ***
SpeciesOithona                  -2.1682     0.1560 -13.894  < 2e-16 ***
TreatmentFicoll                 -0.3131     0.1512  -2.071  0.03978 *
SpeciesAcartia:TreatmentFicoll  -0.2102     0.2430  -0.865  0.38803
SpeciesParvo:TreatmentFicoll     0.3127     0.2213   1.413  0.15943
SpeciesOithona:TreatmentFicoll   0.5356     0.2213   2.420  0.01650 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.5655 on 184 degrees of freedom
Multiple R-squared:  0.6696,    Adjusted R-squared:  0.6571
F-statistic: 53.28 on 7 and 184 DF,  p-value: < 2.2e-16
</code>
Calanus Control is the intercept in the model. Now, this looks ok except for when you actually look at what R is saying about the groups - there's a significant effect of treatment for Oithona but not Acartia? Huh? Take a look at the barplot. There's no way that's accurate. So I calculated the means by hand (I can share the data over Google Drive if you want):
<code>> mean(log(subset(total, subset = Species == "Parvo" & Treatment == "Control")[,3]))
[1] -0.4623169
> mean(log(subset(total, subset = Species == "Parvo" & Treatment == "Ficoll")[,3]))
[1] -0.4627922
> mean(log(subset(total, subset = Species == "Oithona" & Treatment == "Control")[,3]))
[1] -0.9929218
> mean(log(subset(total, subset = Species == "Oithona" & Treatment == "Ficoll")[,3]))
[1] -0.7704915
> mean(log(subset(total, subset = Species == "Acartia" & Treatment == "Control")[,3]))
[1] 0.6565436
> mean(log(subset(total, subset = Species == "Acartia" & Treatment == "Ficoll")[,3]))
[1] 0.1331612
> mean(log(subset(total, subset = Species == "Calanus" & Treatment == "Control")[,3]))
[1] 1.175278
> mean(log(subset(total, subset = Species == "Calanus" & Treatment == "Ficoll")[,3]))
[1] 0.862128
</code>
Note that these means haven't been backtransformed so they're actually log(swimming speed). This is so they can be directly compared to the model output. By comparing the group means calculated by hand, you can see that the interaction coefficients are way off. I checked the difference between various group means and it seems like R is comparing random/incorrect groups to get these coefficients. For example, the SpeciesParvo:TreatmentFicoll coefficient is actually the difference between the Oithona Ficoll group and the Parvocalanus Control group (or Parvocalanus Ficoll, they have the same mean). So... what gives? Any help is much appreciated!
Comment: The interaction coefficient estimates (and associated standard errors) are still conditional on the reference levels used, even if it's a reference level for the interaction.  So while the model output appears to say there's no evidence for a treatment effect for Acartia, what it's actually saying is there's no evidence of a difference between the Acartia treatment effect and the Calanus treatment effect.
Answer: Here's an example of how I would use the coefficient estimates to arrive at the group means:
Picking on Parvo/Ficoll, the mean should be [intercept] + [Parvo] + [Ficoll] + [Parvo:Ficoll].  And, in fact,
<code>> 1.1753-1.6376-0.3131+0.3127
[1] -0.4627
</code>
Comment: THANK YOU it turns out my reference for interaction coefficients was worded in a very misleading way and implied that Parvo/Ficoll should be calculated as intercept+parvo+interaction (ignoring ficoll)


Why Does Default user defined destructors in C++ increases execution time?

Question: In my project we had, 1 user defined default destructor, which was written to follow some coding standard requirements of the project.
The Class of this destructor was instantiated more than 200 times, which had increased the overall response time, when this mentioned destructor was removed, I observed improvement in response time by 28 msec.
Can anyone explain why this timing difference, though those were default destructors only but defined by users, which anyways will be called by the compiler.
With the usage of "user defined default destructor" I meant a destructor which is empty :
~Classname(){ };
Doing nothing, but is added to fulfill project's standards.
Just to add more clarity, this destructor doesn't fall in following categories:
1.Destructors declared as 'virtual'.
2.The destructors of static and singleton classes.
3.The destructors of the classes whose objects created using the
'new' keyword.
4.The destructors of the classes whose objects deleted using the
'delete' keyword.
Comment: Can you show us the code for this destructor?
Comment: And be a bit more specific. "user defined default destructor" is an oxymoron.
Comment: [Related](http://connect.microsoft.com/VisualStudio/feedback/details/560640/empty-c-destructors-prevent-optimization). I believe that to be an issue of the compiler, but I have heard this before of different compilers... even though I fail to see why the compiler would not be able to generate exactly the same code.
Comment: I would suspect that the destructor was declared virtual.
Comment: the destructor is empty :
~Classname(){
};
and the destructor is not virtual.
Comment: here the default means there was nothing to do just to have process in place. that resulted into increase in execution time.
Comment: @Arti: You should add sample code to the question so that it is self-contained (i.e. readers are not forced to read into the comments to understand exactly what you mean)
Comment: @DavidRodríguez-dribeas, is this increase in response time due to, compiler overriding its default destructors, with the user defined empty destructors?
Comment: @Arti: No, override implies virtual functions and inheritance. In that case (the Visual Studio bug report) the issue is related to exception. The compiler is able to optimize more on the assumption that the compiler generated destructor will not throw, but it is not realizing that the equivalent user defined destructor has exactly the same properties.
Comment: @Arti: There are several other details that would be useful to know. Does the class have a base class? A virtual base class? Does the base class have a virtual dtor? Does the class have member variables that have destructors? Is your destructor defined inline?
Comment: @dave, This itself is a base class, which is derived by no. of classes.
It does not have any virtual destructor.
It does not have member variables, that have destructors.
No the destructor is not defined inline.
Comment: If the destructor is (explicitly or implicitly) inline, then this is a bug in your compiler's optimizer. Try another compiler.
Comment: *This itself is a base class, which is derived by no. of classes. It does not have any virtual destructor.*  — This *is* a potential problem.
Comment: @n.m. I am sorry for the above mentioned comment, it is getting instantiated many times not derived.
Comment: Ok so no problem here. But why not inline?
Comment: @n.m. even I have observed timing improvement(though less) after removing inline empty destructors as well..
Answer: I've encountered several places where compilers don't recognize empty destructors correctly

MSVC cannot inline functions if they return objects that have user defined destructors, even if that destructor is empty.
Type traits like is_trivial, is_pod etc. don't work the way you would want with empty destructors, on any compilers that I've tested. That may change how some algorithms or containers are implemented for specific types.
User defined destructors may change the exception handling code because the compiler has to create code for unwinding the stack. Again, if I remember correctly MSVC doesn't recognize empty destructors correctly for this purpose either.
Every allocation you do with new T[] has to allocate extra space for item count if T has non-trivial destructor. Also, that can change the alignment of the memory block which can really hurt performance. Neither MSVC or g++ optimize this correctly for empty destructors.


If $\forall x,y \in B$ if $(x,y) \in S$ and if $x+y$ is even then $x=y$ then each class of $S$ has at most $2$ elements

Question:
Set $B = \{1,2,3,4,5\}$, $S$ - equivalence relation. It is given that for all $x,y \in B$ if $(x,y)\in S$ and if $x+y$ is an even number then $x = y$. In such case is it true that:

the number of elements in each equivalence class of $S$ is at most $2$
any relation $S$ would have an equivalence class made up of just one even number.

As far as I understand $S$ could be only of such form:
$$
S = \begin{pmatrix}1&2&3&4&5\\1&2&3&4&5 \end{pmatrix}
$$
because all pairs of $(x,y), x \neq y$ which are both odd numbers can't be in $S$ as well as all pairs $(x,y), x \neq y$ which are both even numbers for example:
$$
\begin{pmatrix}1\\3 \end{pmatrix}, \begin{pmatrix}2\\4 \end{pmatrix}
$$
because their sum will be even but $x \neq y$.
In addition $(x,y), x\neq y$ where one of them is odd and one is even also can't be in $S$ because then the relation will not be transitive and hence will not be an equivalence relation.
In such case I think the statement 1 is false because all equivalence classes are exactly of size $1$ and statement 2 is true because we have for example the equivalence class $\{2\}$ which is one even number.
I'm not sure about my logic because the question is quite tricky.
Answer: The answer to the first part is that if an equivalence class has three elements in it then two are odd or two are even, and the pair of common parity gives a counterexample to the condition.
For the second part, any equivalence class of size $2$ must consist of an odd number and an even number. Can you create a set of equivalence classes without an even singleton set?
I've left you some work to do, because only by working this through for yourself will you really get to understand. But you should appreciate that specifying an equivalence relation as a set of pairs is itself equivalent to expressing it by specifying the associated equivalence classes.
Answer: Your are right about the fact that you cannot have $(x,y)$ with both even or both odd and different, but there is a flaw in the second part of your argument. If you add to the identity relation also a single couple of pairs $(x,y)$ and $(y,x)$ with $x$ odd and $y$ even, everything is still fine: why should transitivity be broken? You can add even more, as long as you do not have $(x,y)$ and $(x',y)$ with $x$ and $x'$ even and different (or the same for $y$), because then you would brake transitivity. 1. follows from this, 2. requires a bit more but is also not far.
Comment: Yes, you are right, I think it should say one **odd** number, because there are more odd than even numbers
Comment: You're right transitivity is not necessarily broken if we carefully add certain pairs. I got the first part, so for the second I have this example: $\begin{pmatrix}1&2&3&4&5&1&2&5&4\\1&2&3&4&5&2&1&4&5\end{pmatrix}$. This would lead the following classes: $\{\{1,2\},\{3\}, \{4,5\}\}$ so the second part is false.
Answer: Assume that $S$ has an equivalence class with $2$ even numbers, namely $2$ and $4$. Then, $(x,y)\in S$ and $x+y=6$ which is even, but this contradicts $x=y$. Hence, two even numbers cannot be in the same equivalence class.
Now, assume that there exists an equivalence class with two odd numbers $x\neq y$. Then $x+y=\text{even},$ but again $x=y$ is not satisfied. Hence, if $x\neq y$ and $x,y$ odd, then they cannot be in the same equivalence class.
So, you have that any equivalence class in $S$ contains at most one even and at most one odd number. Since, there are five elements in $B$, this leaves you with a class that necessarily has one element. But I do not see why this has to be an even number. So, I agree with the first statement but disagree with the second statement (the even numnber part).


How to support es modules and commonjs modules at the same time

Question: Some packages we install from npm support both commonjs and es modules,
These packages can be imported as follows:
import express from 'express'
// or
const express = require('express')

I have created a package which I already published to npm using es modules.
and I since my another project which I'm working on is built with commonjs, I realized that I can not require it using the following syntax:
const stackPlayer = require('stack-player')

How can I support the two module systems in my package stack-player so that everyone around the world can use it?

Is there another method other than converting all of my project to es modules (which would be too complex since the project is 1 year old and is big enough to refuse the idea). ?
Comment: @MostafaFakhraei, I want to develop my package in es6 modules, and I want anyone to install it, and `require()` it or `import` it. Of course, it worked with you because it's written in commonjs, I want to re-write it using es6 modules.
Comment: *P.S: Your package works with both `import` and `require`. I've tested it.*
Comment: That is something else and it is a different thing. I mean I've installed your package, and I've tested and it was fine. So if you want to use *ESM* syntaxes, that would be a different thing. You bring up an example from Express, and Express doesn't use ESM syntaxes in their current code.
Comment: @DanielKaplan no harm no foul. I took a closer look at the post topic and realized what was going on. Anyhow, I've posted an answer that you might find helpful. Happy new year. BTW, I miss the "gourmet ghetto" and all the other fabulous food in your area.
Comment: Have you looked at the [source of express](https://github.com/expressjs/express/blob/442fd467992992558806da8da07e945838712587/lib/express.js#L28) how they did it? You can just use `exports = module.exports = require('./stack-player');`
Comment: @Christopher, it did not work, https://stackblitz.com/edit/node-yy2prn?file=index.js
Comment: @MostafaFakhraei, no, here's a screenshot: https://i.ibb.co/6D5xwjH/Untitled.png this screenshot is from the sandbox I pasted above
Comment: There's literally thousands of examples on GitHub.
Comment: @morganney  Which of those thousands are good examples and which are bad examples? Which ones use deprecated techniques? In these thousands of examples with thousands of lines, which lines are the ones relevant to the question? How important is it that I use their tools? I could go on, but all of these questions are rhetorical. The point I'm making is, these examples are 99% noise when it comes to answering the question of the OP.
Comment: @DanielKaplan you @ me a year later ¯\_(ツ)_/¯? I don't remember what we were talking about. However, differentiating signal from noise is what distinguishes experience and/or good insight.
Comment: @morganney Since there was no @ in your reply, I thought you were replying to the question. I took it to mean, "Instead of asking, you should find one of the 'literally thousands of examples on GitHub.'" If I misinterpreted your comment, I apologize. But if my interpretation was correct, I wanted to say that this is a good question for SO, IMHO.
Answer: There are two main scenarios:
1. Your package is written using CommonJS (CJS) module loading
This means your package uses require() to load dependencies. For this kind of package no special work is needed to support loading the package in both ES and CJS modules. ES modules are able to load CJS modules via the import statement, with the minor caveat that only default-import syntax is supported. And CJS modules are able to load other CJS modules via the require() function. So both ES modules and CJS modules are able to load CJS modules.
2. Your package is written using ES module loading
This means your package uses import to load dependencies. But don't be fooled - sometimes, especially when using TypeScript, you may be writing import in your code, but it's getting compiled to require() behind the scenes.
Unfortunately, CommonJS modules do not support loading ES modules except (in Node.js) by using the import() function (which is a bit painful and not a great solution).
In order to support CommonJS in this case, your best bet is to transpile your package into a CommonJS module, and ship both CommonJS and ESM versions of your package.
I do this in a number of my own packages mostly by using Rollup, which makes it relatively easy.
The basic concept is this:

Write your package as an ES module.
Install rollup: npm i -D rollup
Run npx rollup index.js --file index.cjs --format cjs to convert your code into a CJS module.
Export both from your package.json:

{
  "name": "my-package",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "exports": {
    "import": "./index.js",
    "require": "./index.cjs"
  }
}

This way, the CJS module loader knows to load your index.cjs file, while the ESM loader knows to load your index.js file, and both are happy.
Comment: Yes @DanielKaplan when you use `require` and when you use `import` you're running very different code that loads modules in different ways. The CJS module loader will prefer using the `require` field in the module's `package.json`, while the ES module loader will prefer using the `import` field. Keep in mind however the caveat regarding TypeScript, where it's common to write `import` in your TS code, but you have TS configured to compile that to `require` instead. In that case, even though you're writing `import`, `require` is being used and the CJS module loader is being invoked.
Comment: `the CJS module loader knows to load your index.cjs file, while the ESM loader knows to load your index.js file, and both are happy.`  So you are saying if `import` the dependency, some behind the scenes magic is choosing one file instead of the other, and if I use a `require`, different magic picks the cjs file?
Answer: require() Usage
require() can, by default, only be used in CommonJS Modules. The built in method to import ECMAScript modules into CommonJS is using import(pathToFile).then(module => { }).
Support for require()
If you want to support require() for your package, you must provide a CommonJS module.
Here's a functioning example that demonstrates when and how to utilize require() or import(). There are some small differences how import() of a CommonJS module works compared to a ECMAScript Module. Especially that only the default property on the module object is available, when import() is used on a CommonJS file that exported something with module.exports.
index.js which imports different module types (from the demo above):(In case the stackblitz demo will be deleted:)
// executed as CommonJS module
console.time('');
import('./lib/example.cjs').then(({ default: example }) => {
  console.timeLog('', 'import cjs', example() == 'Foo'); // true
});
import('./lib/index.mjs').then(({ example }) => {
  console.timeLog('', 'import mjs', example() == 'Foo'); // true
});
try {
  const example = require('./lib/example.cjs');
  console.timeLog('', 'require cjs', example() == 'Foo'); // true
} catch (e) {
  console.timeLog('', 'require cjs', '\n' + e.message);
}
try {
  const example = require('./lib/index.mjs');
  console.timeLog('', 'require mjs', example() == 'Foo');
} catch (e) {
  console.timeLog('', 'require mjs', '\n' + e.message); // Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/lib/index.mjs not supported.
}

lib/example.cjs
module.exports = function example() {
  return 'Foo';
};

lib/index.mjs
import example from './example.cjs';
export { example };
export default example;

Conditional Export for Packages
A conditional export can be supplied for packages to support require(), for example in a case where the CommonJS require() is no longer supported by your package. Refer to this link for more information.

The "exports" field allows defining the entry points of a package when imported by name loaded either via a node_modules lookup or a self-reference to its own name. It is supported in Node.js 12+ as an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules.

package.json (example from the nodejs docs)
{
  "exports": {
    "import": "./index-import.js",
    "require": "./index-require.cjs"
  },
  "type": "module"
}

If so, you have to provide two scripts: one for the CommonJS ("require": "filename") and one for the ECMAScript module ("import": "filename").
While index-require.js must provide the script via exports = ... or module.exports = ..., index-import.js must provide the script with export default.
Keyword Usage
You can only use specific keywords depending on the files module type.
CommonJS Modules

module.exports is used to define the values that a module exports and makes available for other modules to require. It can be set to any value, including an object, function, or a simple data type like a string or number.
exports, module

If you use them inside an ECMAScript module you'll get an undefined Error.

require()

require() inside ECMAScript modules is possible, but you have to use a workaround as mentioned in this answer or take a look at the docs for module.createRequire(fileName):
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');

If you call require() from within a CommonJS on an ECMAScript module, it throws a not supported Error:
Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/script.mjs not supported.

With a more detailed error message depending on the situation:

Instead change the require of script.mjs in /path/to/app.js to a dynamic
import() which is available in all CommonJS modules.

Or:

/path/to/script.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename /path/to/script.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /path/to/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

ECMAScript Moduls (ESM)

export default is used to export a single value as the default export of a module. This allows for a more concise way to import values, as the import statement can omit the curly braces when importing the default export.
Named exports, on the other hand, allow multiple values to be exported from a module. Named exports use the export keyword followed by an identifier and a value. (export const foo = "bar")
import ... from ...

It can handle CommonJS files and interprets them as if you would've used require().
Example based on express:
import express, { Route, Router } from 'express'; // EJS
// is similar to:
var express = require("express"), { Route, Router } = express; // CJS

Both CommonJS and ECMAScript modules support the import() function, but the returned object can have more properties on ESM files.
Summary:
CJS modules don't need to be converted to ESM, as they can be imported into ESM using the import ... from ... syntax without any modifications to the CJS module. However, it's advisable to write new modules using ECMAScript Module syntax, as it is the standard for both web and server-side applications and enables seamless use of the same code on both sides the browser/client-side and node/server-side.

Specifications

Additionally, I find this article on CommonJS vs. ES modules in Node.js from logrocket.com to be very informative. It delves into the pros and cons of ECMAScript compared to CommonJS in more depth.
Links:

MDN: import()
NodeJS.org: Difference between ECMAScript modules and CommonJS modules
Answer: When I'm publishing an npm package with TypeScript, for either node.js or the browser, I use @knighted/duel (I am also the author if that matters to you).
It is as easy as creating a tsconfig.json and package.json with a defined type and then defining an npm run script to create a dual build.
tsconfig.json
{
  "compilerOptions": {
    "declaration": true,
    "module": "NodeNext",
    "outDir": "dist"
  },
  "include": ["src"]
}

package.json (type of module or commonjs is ok)
  "type": "module",
  "scripts": {
    "build": "duel"
  }

npm run build

Now update the exports in package.json to match the build output in dist before you publish.
Comment: [It](https://github.com/knightedcodemonkey/duel) delegates [it](https://nodejs.org/api/packages.html#dual-package-hazard) to the user, i.e. ignores it completely. It exists, and you should know about it. Worry less, produce more.
Comment: How does `duel` solve the dual package hazard?


Teclado numérico no IOS

Question: Estou começando a programar e tenho umas perguntas de noob :) queria saber como que faço em uma UITextField subir automáticamente o teclado numérico?
Ja tentei usar o keyboardType mas não sei exatamente como aplicar as propriedades
Obrigada
Answer: Não entendi muito bem a duvida, mas não seria só alterar diretamente no storyboard?
Caso queira uma forma de alterar durante o programa:
<code>[textField setKeyboardType:UIKeyboardTypeNumberPad];</code>
Espero ter entendido e ajudado! rs
Answer: Dá uma olhada nesse vídeo, sei que está inglês mas é só seguir os passos que ele mostra que vai deve fazer o que você precisa.
https://www.youtube.com/watch?v=FNCVmkv_vdI
Valeu
Comment: se você puder descrever a solução apresentada no vídeo, vai ajudar qualquer outra pessoas no futuro que venha nesta mesma pergutna (e só saiba falar portugues)

Teclado numérico no IOS


PHP SHELL EXEC WITH EXCLUDE

Question: This is my current PHP script and it works well except that it backs up everything where in i would like to exclude the image dir.
<?php
function backup()
 {
  shell_exec("tar -cvf backup`date +%Y%m%d`.tar.gz /home/USERNAME/public_html/WEBSITE.com.au* ");
}

backup();
?>

THIS IS WHAT I TRYING TO DO..
<?php
 function backup()
 {
  shell_exec("tar --exclude /home/USERNAME/public_html/WEBSITE.com.au/images/* -cvf backup`date +%Y%m%d`.tar.gz /home/USERNAME/public_html/WEBSITE.com.au/");
 }

 backup();
 ?>

I am unable to get the exclude function to work. Any ideas how to achieve this?
Answer: I suspect you just want to remove the * from the end of that path, since it's expanding into multiple arguments and only the first one follows --exclude.  You also need to drop the trailing slash, because...  I don't know.  tar is picky.
That said, doing this from PHP seems like a really bad idea.  Anyone who discovers this endpoint could pretty easily ramp up your CPU usage by hitting it a few times, or even corrupt your backups by hitting it in parallel.
Comment: thank i tryed
but it still backed up the whole thing
Comment: as for the php file it's not with in the public html folder.. this should be fine
Comment: err, how are you running it then?
Comment: edited answer; you need to drop the trailing slash too
Comment: Turns out you where right first time.. i run it as a cron job ...  oscommerce has a catalog folder and i forgot to add it... oppps sorry you where right all a long ... thankyou for your help ..
Comment: err.  if you run it as a cron job then why not just put it in a shell script?  there's no reason to involve php here.

PHP SHELL EXEC WITH EXCLUDE


É possível utilizar variáveis para definir o tamanho de uma View?

Question: Sou iniciante no desenvolvimento e aplicativos e na aplicação em que estou trabalhando preciso que o usuário me dê um valor (distância em metros) e a partir deste valor eu ajustarei o tamanho da imagem a ser exibida pelo aplicativo.
Estou desenvolvendo em Java com o Android Studio.
Pensei em fazer isso utilizando variáveis que seriam usadas para definir meu valores de altura e largura, por exemplo:
android:layout_width= variavel_w
android:layout_height= variavel_h

porém não se é possível utilizar variáveis nesses campos, ou se haveria alguma outra forma de ajustar o tamanho da minha imagem conforme alguma entrada.
Ficarei muito grato com qualquer ajuda!
Answer: É possível, mas não no xml.
Tem de usar o objecto Java que representa essa ImageView e o seu objecto LayoutParams.
Obtenha o objecto da sua ImageView:
final ImageView aSuaImageView = findViewById(R.id.aSuaImageView);

Obtenha o seu objecto LayoutParams:
//Substitua LinearLayout. por RelativeLayout. se for o caso
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) aSuaImageView.getLayoutParams();

Atribua os valores pretendidos para width e height
layoutParams.width = 100; // Pode usar uma variável
layoutParams.height = 100; // Pode usar uma variável

A atribua o LayoutParams alterado à ImageView:
aSuaImageView.setLayoutParams(layoutParams);

Nota:
Quando se especifica valores programaticamente no LayoutParams, os atributos width e height esperam que esses valores sejam pixeis.
Para que haja consistência das dimensões entre os vários tipos de tela, tem de considerar as dimensões em dp e convertê-las para pixeis antes de as atribuir aos atributos.
Veja nesta resposta como fazer a conversão.


Effect of non-normal distribution on repeated measures 2 way ANOVA

Question: Part of a piece of university work requires me to talk about the effects of non-normal distribution on ANOVA. I'm fairly certain that having non-normal distributions in data increases your chances of a type 1 error. I'm just really struggling to find a paper which actually specifies this.
Comment: What is your question, exactly? I see nothing but statements up there. :P
Answer: It depends on the type of non-normality. In general, ANOVA is conservative with skewed data. As far as references, there was an article by Donaldson in the late 1960's and I am sure there are more recent ones. You can investigate it yourself if you have a browser that lets you run unsigned applets here: http://onlinestatbook.com/2/tests_of_means/robust_sim.html. The video demo on that page show some information on this.
There is also this article: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.921.8875&rep=rep1&type=pdf


A basic combinatorics/probability question

Question: Suppose you have a set $A = \{1, 2, 3, 4, 5, 6, 7\}$.
You do a sampling with replacement over A (uniformly at random), and get a multiset/bag $B$ of size $5$. For instance, B could be $\{2, 3, 4, 5, 6\}$ or $\{2, 2, 3, 3, 4\}$.
Then what is the probability that there are at least $3$ distinct elements in $B$?
More generally, if you have $A = \{1, 2, 3, ..., n\}$, you do a sampling with replacement over $A$ and get a multiset/bag $B$ of size $k$, what is the probability that there are at least m distinct elements in B? (assuming $n > k > m$).
Comment: For the specific question, it shouldn't be hard to calculate the probability of exactly one element in $B$, or of exactly two distinct elements in $B$; from those numbers, you can get the probability of at least 3 distinct elements in $B$.
Comment: This is essentially a "balls and bins" problem - we take $k$ balls and toss them independently and uniformly into $n$ bins, and you are asking for the probability that at least $m$ bins contain a ball.
Answer: It is easier to do the calculation that there are exactly $m$ bins with at least one ball.  $k$ does not need to be less than $n$.
You have a recurrence with $P(n,k,m)=\frac{n-m+1}{n}P(n,k-1,m-1)+\frac{m}{n}P(n,k-1,m)$ starting at $P(n,0,0)=1$.
So for your example with $n=7$ you get something like this, with each column summing to $1$.
<code>n=7     k:  0       1       2       3       4       5       6       7       8
m:
0       1.000   0.000   0.000   0.000   0.000   0.000   0.000   0.000   0.000
1       0.000   1.000   0.143   0.020   0.003   0.000   0.000   0.000   0.000
2       0.000   0.000   0.857   0.367   0.122   0.037   0.011   0.003   0.001
3       0.000   0.000   0.000   0.612   0.525   0.312   0.161   0.077   0.035
4       0.000   0.000   0.000   0.000   0.350   0.500   0.464   0.357   0.248
5       0.000   0.000   0.000   0.000   0.000   0.150   0.321   0.428   0.459
6       0.000   0.000   0.000   0.000   0.000   0.000   0.043   0.129   0.233
7       0.000   0.000   0.000   0.000   0.000   0.000   0.000   0.006   0.024
</code>
So for $k=5$ you just sum the suitable figures in the relevant column to give an answer of about $0.962099\ldots$