NPM Workspaces with two or more @prisma/client dependencies

Question: I have a monorepo setup. It looks something like this:

project

node_modules
packages

my-first-project

prisma

schema.prisma

my-second-project

prisma

schema.prisma

So both projects (my-first-project and my-second-project) have @prisma/client installed and get there dependencies from the upper node_modules folder.
The thing is that whenever i change something in my schema.prisma file (e.g. in my-first-project) and run npx prisma migrate dev --name whatever it generates all the types and stuff and puts it in the upper node_modules folder. this leads to "type not found" errors on the other project (e.g. my-second-project).
Is there a way to tell npm to keep some dependencies in a separate node_modules folder inside each project?
Answer: You could configure a custom output path to specify the location at which PrismaClient should be generated.
Example:
generator client {
  provider = "prisma-client-js"
  output   = "../src/generated/client"
}

And you should be able to import PrismaClient like this:
import { PrismaClient } from './generated/client'

By generating PrismaClient outside of node_modules should solve your issue.
Comment: It is not clear to me from your example where I tell Prisma to build to an alternative location.
Comment: @ThaJay if you mean the `generator client ...` block, that is from the `schema.prisma` file.


Why do my static files serve with dev_appserver.py but not on GAE?

Question: My static files serve great on the development server, but when I deploy my application via appcfg.py my themes don't load.  GAE returns Error: Not Found when I try to access my .css files with the following url.
http://sprucepress.appspot.com/static/default/css/bootstrap-responsive.css

I have download a copy of my source and verified the files are actually on GAE.  I've also verified that everything is working on my local dev_appserver.py.
You can see the current deployed version on GitHub.
My directory structure...

app.yaml
static.py
themes

default

admin

edit.html
index.html
published.html

assets

css
ico
img
js

base.html
listings.html
post.html

simple

default
admin

edit.html
index.html
published.html

assets

css
ico
img
js

base.html
listings.html
post.html

My app.yaml.
application: sprucepress
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:

- url: /admin/.*
  script: admin.app
  login: admin

- url: /static/([^/]+)/(.*)
  static_files: themes/\1/assets/\2
  upload: themes/[^/]+/static/.*

- url: .*
  script: static.app

builtins:
- remote_api: on

libraries:
- name: webapp2
  version: "2.5.1"

- name: jinja2
  version: latest

An example of the HTML not working..
<link href="/static/default/css/bootstrap.css" rel="stylesheet" />

the live site is at http://sprucepress.appspot.com
update 1 - I tried to redeploy, but that did not solve the issue.
update 2 - Here is my appcfg.py output.
john@ogradylan-lap01:~$ appcfg.py update google_projects/sprucepress
09:27 AM Host: appengine.google.com
09:27 AM Application: sprucepress; version: 1
09:27 AM
Starting update of app: sprucepress, version: 1
09:27 AM Getting current resource limits.
Email: <ny email>
Password for <ny email>:
09:27 AM Scanning files on local disk.
09:27 AM Cloning 117 application files.
09:27 AM Cloned 100 files.
09:27 AM Compilation starting.
09:27 AM Compilation completed.
09:27 AM Starting deployment.
09:27 AM Checking if deployment succeeded.
09:27 AM Will check again in 1 seconds.
09:27 AM Checking if deployment succeeded.
09:27 AM Will check again in 2 seconds.
09:27 AM Checking if deployment succeeded.
09:27 AM Will check again in 4 seconds.
09:27 AM Checking if deployment succeeded.
09:27 AM Will check again in 8 seconds.
09:27 AM Checking if deployment succeeded.
09:27 AM Deployment successful.
09:27 AM Checking if updated app version is serving.
09:27 AM Will check again in 1 seconds.
09:27 AM Checking if updated app version is serving.
09:27 AM Will check again in 2 seconds.
09:28 AM Checking if updated app version is serving.
09:28 AM Will check again in 4 seconds.
09:28 AM Checking if updated app version is serving.
09:28 AM Will check again in 8 seconds.
09:28 AM Checking if updated app version is serving.
09:28 AM Completed update of app: sprucepress, version: 1
09:28 AM Uploading index definitions.

update 3
I've downloaded the app to verify the files are actually on the server. Everything appears to   have been uploaded correctly.
appcfg.py download_app -A sprucepress sp3
09:37 AM Host: appengine.google.com
09:37 AM Fetching file list...
Email: <my email>
Password for <my email>:
09:37 AM Fetching files...
09:37 AM [1/117] themes/default/assets/ico/apple-touch-icon-114-precomposed.png
09:37 AM [2/117] themes/default/assets/js/bootstrap-carousel.js
09:37 AM [3/117] themes/default/assets/css/bootstrap.css
09:37 AM [4/117] lib/wtforms/ext/django/templatetags/wtforms.py
09:37 AM [5/117] themes/default/assets/img/glyphicons-halflings.png
09:37 AM [6/117] lib/wtforms/fields/__init__.py
09:37 AM [7/117] themes/default/assets/img/examples/bootstrap-example-fluid.jpg
09:37 AM [8/117] themes/default/assets/css/bootstrap-responsive.css
09:37 AM [9/117] lib/wtforms/ext/i18n/__init__.py
09:37 AM [10/117] themes/default/assets/js/bootstrap-modal.js
09:37 AM [11/117] lib/wtforms/compat.py
09:37 AM [12/117] lib/wtforms/widgets/__init__.py
09:37 AM [13/117] static.py
09:37 AM [14/117] themes/default/assets/js/bootstrap-tooltip.js
09:37 AM [15/117] themes/default/assets/img/grid-baseline-20px.png
09:37 AM [16/117] themes/default/listing.html
09:37 AM [17/117] lib/wtforms/fields/simple.py
09:37 AM [18/117] themes/default/assets/img/bs-docs-masthead-pattern.png
09:37 AM [19/117] themes/default/assets/js/bootstrap-alert.js
09:37 AM [20/117] lib/wtforms/ext/i18n/messages/pl/LC_MESSAGES/wtforms.mo
09:37 AM [21/117] themes/default/assets/img/bs-docs-bootstrap-features.png
09:37 AM [22/117] themes/default/assets/ico/apple-touch-icon-72-precomposed.png
09:37 AM [23/117] app.yaml
09:37 AM [24/117] themes/default/assets/js/jquery.js
09:37 AM [25/117] lib/wtforms/ext/__init__.py
09:37 AM [26/117] lib/wtforms/ext/sqlalchemy/__init__.py
09:37 AM [27/117] lib/wtforms/ext/django/templatetags/__init__.py
09:37 AM [28/117] themes/default/assets/js/bootstrap.min.js
09:37 AM [29/117] lib/aetycoon/app.yaml
09:37 AM [30/117] themes/default/assets/img/examples/bootstrap-example-hero.jpg
09:37 AM [31/117] themes/default/assets/js/bootstrap-button.js
09:38 AM [32/117] favicon.ico
09:38 AM [33/117] lib/wtforms/ext/django/i18n.py
09:38 AM [34/117] lib/wtforms/ext/i18n/form.py
09:38 AM [35/117] themes/default/assets/img/example-sites/jshint.png
09:38 AM [36/117] themes/default/assets/img/responsive-illustrations.png
09:38 AM [37/117] themes/default/assets/ico/favicon.ico
09:38 AM [38/117] themes/default/admin/index.html
09:38 AM [39/117] themes/default/assets/js/google-code-prettify/prettify.js
09:38 AM [40/117] lib/wtforms/validators.py
09:38 AM [41/117] themes/default/assets/css/docs.css
09:38 AM [42/117] themes/default/admin/edit.html
09:38 AM [43/117] lib/wtforms/ext/csrf/form.py
09:38 AM [44/117] lib/wtforms/ext/i18n/messages/pl/LC_MESSAGES/wtforms.po
09:38 AM [45/117] lib/wtforms/ext/django/orm.py
09:38 AM [46/117] admin.py
09:38 AM [47/117] themes/default/assets/ico/apple-touch-icon-144-precomposed.png
09:38 AM [48/117] lib/wtforms/ext/i18n/messages/en/LC_MESSAGES/wtforms.po
09:38 AM [49/117] themes/default/assets/img/examples/bootstrap-example-starter.jpg
09:38 AM [50/117] handlers.py
09:38 AM [51/117] lib/wtforms/ext/i18n/messages/es/LC_MESSAGES/wtforms.po
09:38 AM [52/117] themes/default/assets/js/bootstrap-scrollspy.js
09:38 AM [53/117] themes/default/assets/js/bootstrap-tab.js
09:38 AM [54/117] lib/aetycoon/README
09:38 AM [55/117] lib/wtforms/ext/i18n/messages/fa/LC_MESSAGES/wtforms.mo
09:38 AM [56/117] lib/wtforms/ext/i18n/messages/fa/LC_MESSAGES/wtforms.po
09:38 AM [57/117] themes/default/assets/test.jpg
09:38 AM [58/117] themes/default/assets/js/README.md
09:38 AM [59/117] lib/wtforms/ext/i18n/messages/wtforms.pot
09:38 AM [60/117] lib/wtforms/ext/sqlalchemy/fields.py
09:38 AM [61/117] themes/default/assets/js/google-code-prettify/prettify.css
09:38 AM [62/117] themes/default/admin/published.html
09:38 AM [63/117] lib/wtforms/ext/csrf/fields.py
09:38 AM [64/117] models.py
09:38 AM [65/117] lib/wtforms/ext/i18n/messages/en/LC_MESSAGES/wtforms.mo
09:38 AM [66/117] lib/wtforms/ext/i18n/messages/es/LC_MESSAGES/wtforms.mo
09:38 AM [67/117] themes/default/assets/img/bootstrap-mdo-sfmoma-03.jpg
09:38 AM [68/117] themes/default/assets/ico/apple-touch-icon-57-precomposed.png
09:38 AM [69/117] themes/default/assets/js/bootstrap-popover.js
09:38 AM [70/117] lib/wtforms/ext/dateutil/fields.py
09:38 AM [71/117] lib/wtforms/fields/core.py
09:38 AM [72/117] config.py
09:38 AM [73/117] lib/wtforms/ext/appengine/fields.py
09:38 AM [74/117] themes/default/assets/img/bs-docs-twitter-github.png
09:38 AM [75/117] themes/default/assets/js/bootstrap.js
09:38 AM [76/117] lib/wtforms/ext/i18n/messages/README.txt
09:38 AM [77/117] lib/wtforms/ext/i18n/messages/zh/LC_MESSAGES/wtforms.po
09:38 AM [78/117] themes/default/assets/img/less-logo-large.png
09:38 AM [79/117] themes/default/assets/img/example-sites/soundready.png
09:39 AM [80/117] themes/default/assets/img/example-sites/kippt.png
09:39 AM [81/117] lib/wtforms/widgets/core.py
09:39 AM [82/117] themes/default/base.html
09:39 AM [83/117] lib/wtforms/ext/i18n/messages/it/LC_MESSAGES/wtforms.mo
09:39 AM [84/117] utils.py
09:39 AM [85/117] themes/default/assets/js/bootstrap-affix.js
09:39 AM [86/117] lib/wtforms/ext/csrf/__init__.py
09:39 AM [87/117] index.yaml
09:39 AM [88/117] lib/wtforms/ext/django/fields.py
09:39 AM [89/117] themes/default/assets/js/bootstrap-typeahead.js
09:39 AM [90/117] lib/wtforms/ext/csrf/session.py
09:39 AM [91/117] generators.py
09:39 AM [92/117] lib/wtforms/ext/sqlalchemy/validators.py
09:39 AM [93/117] README.md
09:39 AM [94/117] lib/wtforms/ext/i18n/messages/zh/LC_MESSAGES/wtforms.mo
09:39 AM [95/117] themes/default/assets/js/bootstrap-transition.js
09:39 AM [96/117] themes/default/assets/img/bootstrap-mdo-sfmoma-02.jpg
09:39 AM [97/117] listing.html
09:39 AM [98/117] lib/wtforms/ext/i18n/utils.py
09:39 AM [99/117] themes/default/assets/js/bootstrap-dropdown.js
09:39 AM [100/117] themes/default/assets/js/bootstrap-collapse.js
09:39 AM [101/117] themes/default/assets/js/application.js
09:39 AM [102/117] lib/wtforms/ext/appengine/db.py
09:39 AM [103/117] lib/wtforms/ext/i18n/messages/it/LC_MESSAGES/wtforms.po
09:39 AM [104/117] themes/default/assets/img/example-sites/fleetio.png
09:39 AM [105/117] lib/wtforms/ext/sqlalchemy/orm.py
09:39 AM [106/117] fix_path.py
09:39 AM [107/117] lib/wtforms/form.py
09:39 AM [108/117] themes/default/post.html
09:39 AM [109/117] lib/wtforms/ext/appengine/__init__.py
09:39 AM [110/117] lib/wtforms/__init__.py
09:39 AM [111/117] themes/default/assets/img/bs-docs-responsive-illustrations.png
09:39 AM [112/117] lib/wtforms/ext/django/__init__.py
09:39 AM [113/117] lib/wtforms/ext/dateutil/__init__.py
09:39 AM [114/117] themes/default/assets/img/bootstrap-mdo-sfmoma-01.jpg
09:39 AM [115/117] themes/default/assets/img/glyphicons-halflings-white.png
09:39 AM [116/117] main.py
09:39 AM [117/117] lib/aetycoon/__init__.py

Answer: The upload value should read themes/[^/]+/assets/.*. You dont' have a static folder inside themes.
Comment: Can you post the output of appcfg.py, it usually tells you how many static files is going to upload.
Comment: Thanks for your help. I've added the appcfg output to the original post.
Comment: You were right after all. The first time I tried your fix the updated yaml filed failed to upload. I tried it again and it worked. Thank you so much!


What is causing this white space in flexbox in Chrome and how can I get rid of it?

Question: I am trying to create a simple directional pad and I am running into a problem when trying to use flexbox to separate the left and right buttons. The button components themselves are SVGs. Using display: flex introduces a white space on the top and bottom of the SVGs that I do not want. Strangely, if I make them divs, the problem does not exist. This only happens on Chrome, it works on Firefox.
Here is the problematic code: https://jsfiddle.net/j1etr0ph/
Here is the solution I'd like, but with the SVG: https://jsfiddle.net/j1etr0ph/1/
Even more strange, it seems to work below in Stack Overflow's code sandbox.

#container {
  border: 1px solid black;
  display: flex;
  justify-content: space-between;
}

#directional {
  width: 33.3%
}

  <svg id="directional" viewBox="0 0 30 30">
    <g id="circle">
      <path id="fill" fill="#D1D3D4" d="M15,29.5C7,29.5,0.5,23,0.5,15S7,0.5,15,0.5S29.5,7,29.5,15S23,29.5,15,29.5z"/>
      <path id="outline" fill="#414042" d="M15,1c7.7,0,14,6.3,14,14s-6.3,14-14,14S1,22.7,1,15S7.3,1,15,1 M15,0C6.7,0,0,6.7,0,15
        s6.7,15,15,15s15-6.7,15-15S23.3,0,15,0L15,0z"/>
    </g>
    <polygon id="arrow" fill="#414042" points="6.3,20 15,5 23.7,20  "/>
  </svg>
  <svg id="directional" viewBox="0 0 30 30">
    <g id="circle">
      <path id="fill" fill="#D1D3D4" d="M15,29.5C7,29.5,0.5,23,0.5,15S7,0.5,15,0.5S29.5,7,29.5,15S23,29.5,15,29.5z"/>
      <path id="outline" fill="#414042" d="M15,1c7.7,0,14,6.3,14,14s-6.3,14-14,14S1,22.7,1,15S7.3,1,15,1 M15,0C6.7,0,0,6.7,0,15
        s6.7,15,15,15s15-6.7,15-15S23.3,0,15,0L15,0z"/>
    </g>
    <polygon id="arrow" fill="#414042" points="6.3,20 15,5 23.7,20  "/>
  </svg>

Does anyone know what is causing this and how I can get rid of it?
EDIT: So it seems to not be totally reproducible.
* On Windows, the problem does not exist in Firefox. In Chrome, it ONLY exists on my local site, not the JSFiddle or SO code.
* On Mac, I have not tested Firefox yet. In Chrome, it exists on my local site AND JSFiddle, but not SO.
EDIT: Paul's solution was correct, adding height: 100% to the SVGs solved the problem. Since it only seems to be happening on my local site(still curious as to why), here is the screenshot with and without the height property:
With height: 100%: https://i.stack.imgur.com/gResy.png
Without: https://i.stack.imgur.com/whnxU.png
Comment: I see no whitespace in the jsfiddle you posted. Can you provide a screenshot of the problem? Thanks
Comment: The cause of that most likely lies somewhere else since the issue is yet to be seen.
Comment: Any specific browser ?
Comment: Chrome, sorry! I realized it doesn't happen on Firefox. I've edited the question.
Comment: Very weird. It is not happening on the JSFiddle anymore. I will attach a screenshot.
Answer: Try adding height: 100% to your SVGs.
#directional {
  width: 33.3%;
  height: 100%;
}

https://jsfiddle.net/j1etr0ph/2/
Comment: This was it! Thank you very much, this was driving me crazy. Strangely it only happens on my local site, not the JSFiddle anymore.


Inconsistent behavior from .click()?

Question: When I include jQuery in the console and run this snippet against Google.com, what should happen is that numbered tags appear next to all the anchor elements. Which works fine.
But when you click those tags, it should act as if you clicked the element each tag appears to the left of. Most of them work-- the direct anchors that redirect to a new page, that works fine.
But you'll see there's one, the little square of squares image next to the "Images" anchor, which isn't a direct anchor but rather has a click event on it which shows the other apps in a little pop-up window, and that's where the issue is.
If I give it an id and use .click() directly on it in the console, it works perfectly. But with this code....the .click() is simply not working! I can't seem to determine why.
var n = 1;
$('a').each(function(){
    //create and place numbered tag elements-- works fine
    var id = n;
    var a = $(this).offset();
    $('body').append('' + id + '');
    $('#'+id).css({left: a.left - 25, top: a.top});

    //create click event on each tag-- doesn't quite completely work
    var self = this;
    $('#'+id).click(function(){
        self.click();
    });
    n++;
});

Note, this is only designed to work in Chrome; it's part of an extension. Other browsers do not matter here.
Comment: You may want to note that id values are not supposed to start with a number.
Comment: Notice that if you use setTimeout(function() { self.click(); }, 10); it works. I'm guessing it has something to do with you using click inside click.
Comment: you don't actually need an id here at all, if you create the element directly, add the behavior, and then append it to the DOM.  but hm, weird.
Comment: The id is used for separate functionality not relevant here.
Comment: @jfriend00 - in HTML5 it's fine.
Comment: Have you tried to use a debugger for debugging the code line by line, and watching all variables contents?
Comment: Hello are you getting any error **id="' + id + '"**  should be **id='" + id + "'** means double quote should be inside
Comment: can you provide a fiddle?!
Comment: @user2284570 yes. gained nothing.
Comment: @EranH. make that an answer and the bounty is yours. You're dead on. First tip that worked for me, out of all these answers. Now that you say it, I remember encountering similar behavior once before. Thanks so much.
Comment: JavaScript debugger? did you even deeped in the libraries?
Answer: From EranH's comment under the question, this solution works perfectly. I can't say I understand why, but there you have it.

Notice that if you use setTimeout(function() { self.click(); }, 10);
  it works. I'm guessing it has something to do with you using click
  inside click.
Answer: I don't know exactly why your code didn't work, but this seems to work:
Sorry, was looking at the wrong number box! Doesn't work :(
Ok this seems to affect the problem, but not solve it:
var n = 1;
$('a').each(function(){
    var a = $(this).offset();
    var $num = $('' + n + '');
    $('body').append($num);
    $num.css({left: a.left - 25, top: a.top});
    var that = this;
    $num.on('click' ,function () {
        var e = new MouseEvent('click', {
          'view': window,
          'bubbles': true,
          'cancelable': false
        });
        that.dispatchEvent(e);
    });
    n++;
});

What happens is that browser follows the link (href) the same way as if no other click event were in place. I suspect that the other events get triggered too, but the page get's reloaded in the same moment.
If you set cancelable to true it won't work. So I guess that the event get's canceled somewhere. But why doesn't it show the popup-tooltip box is beyond me...
Comment: That's a very clever insight and I think that's a step in the right direction. I'm thinking how to approach this...
Answer: I think this is due to the binding, the click event is not attached to the dynamically created item. you should use on() (previously live() ) to attache the binding to the element you created:
The following jQuery.On signature:
  $(document).on( eventName, selector, function(){} );

in your case:
//define the span first
createdSpan = "' + n + ''"
//append it here
$('body').append(createdSpan)
//attache/bind the event
$(createdSpan).on( 'click', function(){
    this.trigger( 'click' );
 });

Comment: can you explain the down vote ? i am sure the problem is with your binding !
Comment: Your code does not delegate ; plus it adds html to the body, then creates a new node, binds a click handler to it, and throws it away.
Comment: this is just a snippet to show him that the problem is the binding, I am not writing his code !
Answer: The following code "works" (tested on github's front page - executed from Chromium console) :
// delegate event handling in one place :
$('body').on('click', '.numTag', function(){
    var anchor = $(this).data('link');
    $(anchor).click();
});

// you can use the loop counter to have a number associated with each 'a' tag
$('a').each(function(n){
    //create and place numbered tag elements
    var a = $(this).offset();

    var $numTag = $(''+n+'');
    $numTag.data('link', this);
    $numTag.css({left: a.left - 25, top: a.top});
    $('body').append( $numTag );
});

A simple remark : if you add your tags as children of the 'a' anchors, you don't need to manually handle the click events :
$('a').each(function(n){
    //create and place numbered tag elements
    var a = $(this).offset();

    var $numTag = $(''+n+'');
    $numTag.css({left: a.left - 25, top: a.top});
    $(this).append( $numTag );
});

Answer: Don't know why the click doesn't work on those particular links either. The page probably cancels out the default behaviour to do its own js thingy.
If I try to fire the event manually on the Images link as a test nothing happens either, so this is not a binding issue:
$('.gb_b').eq(2).click()

($('.gb_b').eq(2) is the Images link here on my Belgian google.be page)
Here is a workaround, instead of calling the click event you can do a javascript redirect to the href attribute pulled from the clicked anchor. Don't know if this works in a chrome extension context as I don't have any experience with this.
var n = 1;
$('a').each(function(){
    //create and place numbered tag elements-- works fine
    var id = n;
    var a = $(this).offset();
    $('body').append('' + id + '');
    $('#n'+id).css({left: a.left - 25, top: a.top});

    //create click event on each tag-- doesn't quite completely work
    var self = this;
    $('#n'+id).click(function(){
        window.location = $(self).attr('href');
    });
    n++;
});

Answer: Appending the span within the anchor tag that is being iterated through, rather than the body, worked for me.
var n = 1;
$('a').each(function(){
    var id = n;
    $(this).append('' + id + '');
    n++;
});

Comment: When I tried this, it didn't put up a numbered tag for the "box of boxes" at all. Confused :( . . . . this makes sense in theory.
Comment: Do the numbered boxes append for the rest of the links? Just tested it again and I got a six in the box nested in the App button.
Answer: I would suggest you change to this much simpler code that should work fine.  I'm not sure exactly why your existing code doesn't work, but there could be an issue with either your illegal id values (can't start with a number) or with the .click() DOM method not existing on all types of objects.  In either case, this simpler code avoids both of those issues:
$('a').each(function(index){
    var a = $(this).offset();
    var item = $('' + (index + 1) + '');
    item.css({left: a.left - 25, top: a.top});
    item.appendTo(document.body);
    var self = $(this);
    item.click(function(){
        self.click();
    });
});

Comment: Also, if that were the case, I would expect that it wouldn't work at all for any of them anchors, rather than only not working in the case of this one element.
Comment: @Aerovistae - did you try my code suggestion?  `.click()` for DOM elements is an HTML5 addition and has not been supported on all types of elements in all browsers.  See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.click for some info.  Also, did you try making the id value legal as I suggested?
Comment: @Aerovistae - please try my simpler version of code that avoids a couple pitfalls you have in your original one.
Comment: Without researching the topic of `click()` on DOM elements, I would choose jQuery's implementation over vanilla JS anytime. You never know which browser has it's own cemented reasons for behaving (just a bit) differently. And it is more likely that jQuery guys have taken that into account then not, IMO anyway. Of course, when building for one browser only, the argument is invalid.

Inconsistent behavior from .click()?


How can i make it csv file password protected using javascript

Question: html table data exporting into csv file ,it's happening but i want to make csv file password protected using javascript .is it possible ? or another way to do same thing .Thanks in Advance
Answer: On the surface a CSV file is just a data exchange format, where fields are separated by commas and each record goes on a single line.
Comma Separated Values Standard
This specification itself wouldn't deal with password protection.
But can you do something like zip the csv.  Then that would require a password before uncompressing.
Password Protect a Zip File SO
In that link someone called exec to zip a file with password protection.
I do not know exactly the details of what you are intending to accomplish, but basically you can scramble a CSV all you want and make it unreadable without decryption, but since that isn't part of the standard, anyone getting that file wouldn't know what to do with it.  If you control both the encryption and decryption, then you don't need zip.
You could just use an encryption library Javascript AES Encryption
Comment: I have checked for password protected zip using java script but i did not get any example for password protected zip folder so using https://stuk.github.io/jszip/ js library, I can make zip folder but not able to make it password protected folder .


Removal of Stop Words and Stemming/Lemmatization for BERTopic

Question: For Topic Modelling, I'm trying out the BERTopic: Link
I'm little confused here, I am trying out the BERTopic on my custom Dataset.
Since BERT was trained in such a way that it holds the semantic meaning of the text/document,
Should I be removing the stop words and stem/lemmatize my documents before passing it onto BERTopic?
Because I'm afraid if these stopwords might land into my topics as salient terms which they are not
Suggestions and Advices please!
Answer: No.
BERTopic uses transformers that are based on "real and clean" text, not on text without stopwords, lemmas or tokens. At the end of the calculation stop words have become noise (non-informative) and are all in topic_id = -1.
For the same reason you should not tokenize (done internally) or lemmatize (somewhat subjective) the text. That will mess-up your topics
A disadvantage of not lemmatizing is that the keywords of a topic have a lot of redundancy, like (topn=10) "hotel, hotels", "resort, resorts" etc. It also does not handle bigrams like "New York" or "Barack Obama" elegantly
You can't have it all ;-)
Andreas
PS: You can ofcourse remove HTML tags; they are not in your reference corpus either
Answer: A good way to know if this is needed is to check the examples/tutorials given by the link you provided : Here is Topic Modeling. As you can see, it does not seem to do any preprocess before calling the model.
It then seems that it's not needed or preconised by the authors of the model.
However, removing stopwords can make the whole process faster and they often do not contains salient informations about the topic (by their nature). It is sometimes preconised not to remove them for certains tasks such as Sentiment Analysis as you can read in these links :
Why is removing stopwords not always a good idea ?
DataStack discussion over stopwords
As for Lemmatization or Stemmatization, this link provides you good insights about the subject for a Topic Modeling task saying that it should be implemented for improved results.
In conclusion, the BERTTopic does not need Lemming/stemming nor removing stopwords to work but can be implemented to enhance both processing time and results.
At the end, it always depend on your needs and ressources. Giving a try to both solutions and compare the results you have depending on what you want is always a good way to understand pros and cons about these tools.
Comment: Thanks a lot for the guide. I gave a shot without removing stopwords and I did see few stopwords land up in my results whereas removing stopwords gave better results (almost the same just without stopwords)
Answer: The official FAQ of BERTopic presents a solution for stop word removal:
They can be removed by using scikit-learns CountVectorizer after the embeddings are generated.
This is recommended especially if disturbing stop words are appearing in the resulting topics.
See the example in the BERTopic FAQ.
However, any preprocessing (stop word removal, lemmatization, etc.) should be avoided with BERTopic.


Is Bonferroni correction needed for independent samples T-test on grouped data?

Question: I have conducted three tests (math, Biology, Chinese) on 4 groups of students who are coming from Hong Kong, Pakistan, Philippines, and Singapore respectively.
I have the following dataset with the following columns:
Subject: math, Biology, Chinese
Country: Hong Kong, Pakistan, Philippines, Singapore
Score: values ranging 1-100
I want to test for each subject whether there is a significant difference in scores between the Hong Kong students and the other three group of students from different countries.
I conducted independent samples T-test but my question is do I need a Bonferroni correction here?
Here is some simulated data:
<code>df <- tibble(
Subject = rep(c("math", "Chinese", "Biology"), 40),
Country = rep(c("Phili","Sing", "HK", 'Pak'), 30),
Score=  sample(x=1:100, size = 120, replace = TRUE))
</code>
Comment: Thanks for pointing it out, Henry. I have edited that.
Comment: There is little philosophical justification for multiplicity correction (https://stats.stackexchange.com/questions/120362/whats-wrong-with-bonferroni-adjustments), so my suggestion is that you should only use it for political reasons - e.g. if your study is going to be assessed by people who believe that multiplicity correction is a good idea.
Comment: Some thought here https://stats.stackexchange.com/questions/468620/correction-for-multiple-testing-in-multiple-regression-analysis/468622#468622 will also apply.
Answer: I just need a bit of clarification :

Are you trying to compare (and test) the difference between Hong Kong students with students from each different countries or Hong Kong students with the others students from different countries as a whole ?

And the important thing is what would be your question ? (I work in healthcare so I might not be suited to your topic but I'll try to be as clear as possible)

if you want to have a strong claim (like in a randomized controlled trial testing if treatment A is better than treatment B), with hypothesis testing (H0, H1) that would be the approach of Neyman & Pearson. Here you would need a correction for multiple tests
if it's only observationnal data and you want to see if your result are surprising if it were only the effect of randomness (the smaller the p value, the more surprising), that would be closer to the approach of Fisher, then I wouldn't really need to adjust for multiple tests. You just look at the p values (or confidence intervals)

And my last comment on this is you could use Bonferroni which is the simplest method but you could use others (Holm procedure, Fallback, Hierarchical procedure)
I hope it helps, I can develop if it's not clear


Programa C++ para dia da semana (com exemplo de código)

Question: Sabe-se que o dia da semana de uma data fornecida entre 1° de março de 1700 e 28 de fevereiro de 2100 pode ser determinado através do seguinte método:
n=int(365.25∗g)+int(30.6∗f)−621049+d

ds=round(frac(n/7)∗7)+Δ+1

g={a−1, m≤2
  {a, m>2

f={m+13, m <= 2
  {m+1, m>2

Δ={2,n<36523
  {1,36523≤n<73048
  {0,n≥73048

O dia da semana (ds) é representado por 1 se for domingo, 2 se for segunda-feira, e assim por diante. Faça um programa que leia o dia, mês e ano e forneça o dia da semana correspondente;
sei que devo utilizar modf() para o frac(n/7), para obter a parte fracionária. Até agora não encontrei lógica, pois o dia da semana sempre acaba sendo 01.
#include <iostream>
#include <cmath>
#include <math.h>

using namespace std;

int main(){

    int dia;
    int mes;
    int ano;
    int ds;
    int g;
    int f;
    int delta;
    int n;
    float frac;
    float intpart;

    cin >> dia >> mes >> ano;

    if(mes > 2){
        g = ano;
        f = mes + 1;
    }else if(mes <= 2){
        g = ano - 1;
        f = mes + 13;
    }

    n = int(365.25 * g) + int(30.6 * f) - 621049 + dia;

    cout << n << endl;

    if(n < 36523){
        delta = 2;
    }else if( 36523 <= n and n < 73048){
        delta = 1;
    }else if(n >= 73048){
        delta = 0;
    }

    cout << delta << endl;
    frac = modf(n/7, &intpart);

    ds = round(frac * 7) + delta + 1;

    cout << ds << endl;

    switch (ds){
        case 1:
            cout << "domingo" << endl;
            break;
        case 2:
            cout << "segunda-feira" << endl;
            break;
        case 3:
            cout << "terca-feira" << endl;
            break;
        case 4:
            cout << "quarta-feira"  << endl;
            break;
        case 5:
            cout << "quinta-feira" << endl;
            break;
        case 6:
            cout << "sexta-feira" << endl;
        case 7:
            cout << "sabado" << endl;
    }

    return 0;
}

Comment: Aqui: `frac = modf(n/7, &intpart);` faça ou `frac = modf((float) n / 7, &intpart);` ou `frac = modf(n / 7.0, &intpart);` para forçar a operação em ponto flutuante e não uma operação entre inteiros.
Comment: muitíssimo obrigado
Answer: Você sempre entra no case 1:, pois sua variável frac está retornando 0 para a variável ds.
Isto está acontecendo porque você não fez um casting de int para float dentro da função modf.
Seu código corrigido ficará assim:
frac = modf((float)n/7, &intpart);

Observe que o recomendado para operar números float é a função modff:
modf, modff, modfl

Mas por que sua variável frac estava retornado 0 ?

Porque na divisão entre números inteiros( sua variável n é do tipo int) a parte fracionária é eliminada.
Por isto sua função modf sempre retornava 0 para a sua variável ds, pois não havia parte fracionária!
Comment: faltou forçar o 7.0
Comment: A resposta está errada. Na expressão float(n/7), o programa primeiro realiza uma integer division de n/7 (que provavelmente vai dar 0) e depois constroi um float com o valor 0.
Comment: @v.Santos verdade o correto seria (float)n/7. Já vou corrigir
Comment: cara, valeu... tô inciando em C++... não sabia que deveria forçar a tipagem
Comment: tentei editar a linha e mesmo assim retorna 01, domingo
Comment: Tentou mudar os valores iniciais de dia, mês e ano? Aqui retornou correto
Comment: Boa! Precisando de mais ajuda, abra novas perguntas!
Comment: O correto seria ou (float) n / 7. Ou o bem mais simples n/7.0. Que me parece que foi a solução adotada pelo @Alce de Terno.
Answer: Para resolver o problema deve-se usar do casting para float, evitando int em todo caso
frac = modf(float(n/7.0), &intpart);

tanto float() casting quanto forçar 7.0 como divisor
Comment: float() não é casting. float() funciona como um construtor (embora, a rigor, não seja um construtor). Ele apenas constrói um objeto do tipo float com o número passado como parâmetro. Para realizar um cast, utiliza-se (float) - enfatizo, não float() - e isso apenas por compatibilidade com a linguagem C, pois, a rigor, C++ tem seus próprios operadores de casting.
Answer: costumo usar assim:
uint8_t RTCWeekDayNum(uint32_t nYear, uint8_t nMonth, uint8_t nDay)
{
  uint32_t year = 0, weekday = 0;
  year = 2000 + nYear;

  if(nMonth < 3)
  {
     weekday = (((23 * nMonth)/9) + nDay + 4 + year + ((year-1)/4) - ((year-1)/100) + ((year-1)/400)) % 7;
  }
  else
  {
     weekday = (((23 * nMonth)/9) + nDay + 4 + year + (year/4) - (year/100) + (year/400) - 2 ) % 7;
  }
  return((uint8_t)weekday);
}


How prove $ \int_0^1 f(x)dx-\exp\left(\int_0^1\log(f(x)) dx\right)\le\max_{0\le x,y\le 1}\left(\sqrt{f(x)}-\sqrt{f(y)}\right)^2 $

Question: Consider a continuous function  $f:[0,1]\to\mathbb{R}^{+}$. How show that
$\int_0^1 f(x)dx-\exp\left(\int_0^1 \log(f(x)) dx\right)\le \max_{0\le x,y\le 1}\left(\sqrt{f(x)}-\sqrt{f(y)}\right)^2$?
Comment: possible duplicate of [this question](http://math.stackexchange.com/questions/885622/functional-inequality-with-a-strong-rhs). This link does not have an answer though.
Comment: see leshik's solution with mixing variables [**here**](http://math.stackexchange.com/questions/845355/how-prove-this-stronger-am-gm-inequality-fracn2-16-min-1-le-ij-le-n-le?rq=1)
Answer: It is the continuous version of a well-known result about the difference between the arithmetic and geometric mean: see, for instance, the article of S. H. Tung, or the article of J. M. Aldaz, proving that:

If $0\leq a_1\leq a_2\leq\ldots\leq a_n$ and $X=(a_1,\ldots,a_n)$,
  then: $$ AM(X)-GM(X)\leq n \operatorname{Var}(\sqrt{X}).$$
Comment: Jack san for us who do not have access to jstor contents it will be helpful if you summarized the results of the paper in the answer. Thanks :-)
Comment: @r9m: You're welcome.
Comment: This is AMM problem (2014),I have a nice methods
Comment: @r9m: answer updated :)
Comment: This is nice! +1.
Comment: @math110 the discrete version was Joszef Wildt math competition 2012 problem W-32 :)


Loop through number array to construct object of index nodes in plain javascript

Question: I have an array such as [2,5,3,1] each number represents an index number. How would I be able to construct an object path using these nodes? For example:
[2,5] would create:
myObject.conversations[i].conversations[i]

[2,5,3,1] would create:
myObject.conversations[i].conversations[i].conversations[i].conversations[i]

I can only use basic javascript - es6, es5 etc not allowed. I tried a for loop to construct a string which I could just keep adding to but it didn't work.
Comment: If you cannot use ecmascript, you cannot use Javascript...
Comment: basic is ecma. please add the language version and your try.
Comment: If you can't use ES5 or ES6 you can't use Javascript :) These are JS versions (ES6 = JS 2015)
Comment: ECMA *is* JavaScript, so if you can't use ECMA, this is equivalent to you saying you can't use any JavaScript code. Don't take my word for it, just look it up :)
Comment: Sorry I meant I can't use es6, es5 etc. I'll update answer.
Comment: @AndrewJuniorHoward typeof myObject is ? Object or Array ?
Answer: You could iterate the indices array and use a variable for getting the nested references.
var temp = myObject, // start value
    indices = [2, 5, 3, 1],
    i;

for (i = 0; i < indices.length; i++) {
    temp = temp.conversations[indices[i]];
}

// use temp
console.log(temp);

Comment: Thanks for your answer. I think the only problem I have is that with this ansert the 'myObject' would repeat everytime, and I can only have it at the start if that makes sense.
Comment: i don't get you. do you have an example?
Comment: It won't repeat, it will get to the child conversations array if the indexes are correct
Answer: I would just use .reduce

console.log(
    [2,5,3,1].reduce(function(carry, current) {
        return carry + '.conversations[' + current +']';
    }, 'myObject')
)

And if you want the actual object (not the string path), it's as simple as:
[2,5,3,1].reduce(function(carry, current) {
    return carry.conversations[current];
}, myObject)

Or if you want to only pass in myObject once:
function conversation(myObject) {
    return function(path) {
        return path.reduce(function(carry, current) {
            return carry.conversations[current];
        }, myObject)
    }
}

And then you just do
var convo = conversation(myObject);

convo([2, 3, 5, 1]);

Comment: Thanks for your answer. I think the only problem I have is that with this ansert the 'myObject' would repeat everytime, and I can only have it at the start if that makes sense.
Answer: I hope that can help.
let obj = 'myObject';
[2,5,3,1].forEach(i => {
  obj += `.conversations[${i}]`;
});
eval(obj);


Application of MLE

Question: I was reading about the concept of MLE as to how parameters of a particular assumed distribution are calculated using the MLE approach. But, I wonder what is done next once the value of the parameters with the best possible value is/are calculated. I mean what to do next once the MLE is calculated? How, is it utilized over a new set of points, etc.
For an example say I have a set of data points. Let's denote it by D. By looking at the data and prior experience, I assume Gaussian distribution and try to find out mean and variance. I successfully found those values. Now, the question is how should I use the model data that is available with me?
Any piece of advice would be helpful. If there are post related to this question then, I request you to please provide the link about the same.
Comment: What you might do next after computing some MLE depends on what you're trying to achieve. It might be any number of things.
Comment: MLE is a broad topic, useful for many families of distributions. Do you have a particular example or distribution in mind? You seem to be stuck at "what next?" but give no clue what next toward what end?
Comment: @BruceET Thank you for pointing out the problem in the post. I have updated it. I think this should help you or any other person answer my question with a little ease.
Answer: OK, now we know you're interested in MLEs for normal data. But your goal in
finding these estimates of $\mu$ and $\sigma$ might be. Maybe if I give
a couple of examples, that might help you to refine your question.
Suppose you know that scores on the ABC college entrance exam for this year
are normally distributed with mean $\mu = 350$ and standard deviation $\sigma = 50.$ You have 100 early applications for your college with sample mean $\bar X = 360$ and sample SD $S = 56.$ These sample statistics are based on MLEs.
Estimating average scores. You want to know whether the applicants so
far might be better than the population mean. So you do a one-sample t test
of the  null hypothesis $H_0: \mu = 350$ against $H_a: \mu > 350.$ The
procedure for one-sample t tests is explained in most elementary statistics
texts. Output from Minitab statistical software for such a test on your
data is as follows:
One-Sample T

Test of μ = 350 vs > 350

  N    Mean  StDev  SE Mean  95% Lower Bound     T      P
100  360.00  56.00     5.60           350.70  1.79  0.039

Because the P-value is below 0.05, we say that the sample mean $\bar X = 360$ is significantly larger than the population mean $\mu = 350$ at the 5% level
of significance.
Estimating proportion of qualifying scores. Maybe your college only admits students with ABC scores of 410 or above.
Among the 100 applications at hand, how many have sufficiently high scores?
You may find that there are 15 of them, and estimate that you are on track for 15% of applicants
to qualify. But the fraction of sufficiently high scores among the 100
is not based on MLEs. So this is not the best way to estimate this year's
proportion of qualified students. [We see below that this estimate is to low. Using the number of qualifying scores among the 100 at hand might just as well have given an estimate that is too high.]
Using the MLEs, we ask what proportion of a normal population with mean 360 and SD 56 would have qualifying scores. According to a quick computation in R
statistical software, that turns out to be about 19%. This is a better estimate because the MLEs carry more information about your applications on hand than
does the actual count of qualifying applications.
1-pnorm(409.4, 360, 56)
[1] 0.1888498

Note: it would also be a mistake to look at the proportion of qualifying ABC scores
nationwide because that would be only about 12%.
1 - pnorm(409.5, 350, 50)
[1] 0.1170232

Addendum. A million samples of size $n=100$ were taken from
$\mathsf{Norm}(350, 50).$ The population 88th percentile is 408.75.
For each sample of 100 the 88th percentile was estimated by taking
the 88th sample percentile (sp.88). Also, the 88th population
percentile (pp.88) was found for the distribution estimated using MLEs
$\mathsf{Norm}(\bar X, S).$ The histograms show that the MLE method
is nearly unbiased and has smaller variance than the sample percentile method.

R code for the simulation (but not the histogram) is shown below.
set.seed(920)
mu = 350; sg = 50; n = 100
m = 10^6; sp.88 = pp.88 = numeric(m)
for(i in 1:m) {
  x = rnorm(n,mu,sg)
  sp.88[i] = quantile(x,.88)
  pp.88[i] = qnorm(.88,mean(x),sd(x)) }
mean(sp.88); sd(sp.88)
[1] 407.65
[1] 7.979684  ## larger SD
mean(pp.88); sd(pp.88)
[1] 408.5956  ## closer to 408.75
[1] 6.509124  ## smaller SD

Application of MLE


Tutorials for drawing an ROC curve

Question: Are there tutorials you recommend that teach how to draw an ROC curve?
Thanks.
Comment: The most important thing to learn is WHEN to draw ROC curves. 95% of the examples that I have seen are unnecessary and do not represent the best approach to the problem.
Comment: I think you need to be more precise. Do you want to draw them by hand (don't), or use a specific piece of software (R, SPSS, ...)? What exactly is your problem with drawing them?
Comment: See my [answer](http://stats.stackexchange.com/questions/13636/how-to-draw-an-roc-curve) to your previous question -- I think it is a pretty straightforward description of ROC.
Comment: @Nick Sabbe. Since I'm trying to learn how to plot an `ROC`curve, a tutorial to show you the steps and how it is built would be fine, but I will surely use a software for that. Thanks
Comment: _Programmers' Niche_ in [this document](https://cran.r-project.org/doc/Rnews/Rnews_2004-1.pdf), p.33, would be a great read.
Answer: If you want to learn how to draw ROC curves by hand, wikipedia is a good place to start.
If you just want to calculate a plot a ROC curve, and don't really care to learn how the math works, try the colAUC funcion in the caTools package in R.
I believe most major stats packages can drawn ROC curves as well, and a little googling should help you find the appropriate commands.

Tutorials for drawing an ROC curve


Using sed to replace a pattern between curly braces where line immediately before the opening curly brace has a known word

Question: I would like to change:
inlet
{
    type    patch;
    ...
}
outlet
{
        type  patch;
}

to
inlet
{
    type    wall;
    ...
}
outlet
{
        type  patch;
}

As a first attempt to achieve this, I tried to limit the range between inlet and outlet and replace "patch" with wall.
echo "inlet { patch } outlet" | sed "/^\(inlet [^ ]*\) .* \([^ ]*\)$/s//\1 wall \2/"

which gave output :
inlet { wall outlet

The last curly bracket is missing.
echo "inlet {patch} outlet {patch}"| sed "/inlet/,/outlet/{s/patch/wall/}"

gave output :
inlet {wall} outlet {patch}

However, I need to make sure that the "patch" that is replaced by wall shall have a "type" in the same line. It is this part I need to resolve now.
Comment: `'s/[img:.*]/[img]/g'` ??? This is a random command that have nothing to do here AFAIK
Comment: @GillesQuénot, yes. I started with this command to solve this
Comment: please update the question with your actual code (not a link to some other Q&A) and the (wrong) results generated by your code
Comment: your code is likely to fail in various conditions. eg. nested braces; braces inside comments/regex/strings; with macros/includes/conditionals, etc, (cf. https://doc.cfd.direct/openfoam/user-guide-v11/basic-file-format ). you'd be better off refactoring your configs so that the parts to be changed are macros or includes, for example, so that you don't have to write your own parser for the format
Comment: Do you specifically want to replace the string `patch` but not change any other string if it was in that location, or do you want to change any string that's inside `inlet` at the end of a line that starts with `type`?
Comment: @jhnc Thanks for pointing out that. Right now, this work but as you said, it can fail easily. Includes can improve the stability. Thanks
Comment: @EdMorton My upstream workflow kind of ensure that only patch will appear in that location. So, I can safely replace patch, I guess. But below the line with type, there could be patch, before }, which I do not want to replace.
Answer: Using any POSIX awk, if you want to replace any string in that position:
$ awk '
    /^[[:alpha:]]/ { f = ($1 == "inlet") }
    f && ($1 == "type") { sub(/[^[:space:]]+;$/,""); $0=$0 "wall;" }
    { print }
' file
inlet
{
    type    wall;
    ...
}
outlet
{
        type  patch;
}

or if you only want to replace patch specifically then change the 2nd line of the script to:
f && ($1 == "type") && ($2 == "patch;") { sub(/[^[:space:]]+;$/,""); $0=$0 "wall;" }

and if there could be spaces before or after the last ; on the line:
f && ($1 == "type") && ($2 ~ /^patch;?$/) { sub(/[^[:space:]]+[[:space:]]*;[[:space:]]*$/,""); $0=$0 "wall;" }

Answer: This might work for you (GNU sed):
sed -E '/^inlet$/{n;/^\{$/{:a;N;/^\}$/M!ba;s/^(\s+type\s+)\S+/\1wall;/M}}' file

Search for line containing inlet only.
Print it and fetch the next line.
If that line contains only {, fetch subsequent lines until one containing only }.
Now substitute a line beginning and separated by white space, two words: the first being type and then replace the second word by wall;.
N.B. The use of the M flag in both regexp and the substitution commands, that bound the regexp by line i.e. the anchors respect the ^ and $ anchors, in a multiline string.


Run a custom function on a WordPress page

Question: I have a function in my WordPress theme functions.php file with the following code:
function locations() {
    $locations_list = array();
    query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'post_type' => 'location'));
    while(have_posts()) {
      $locations_list[the_slug()] = the_title();
    }
    wp_reset_query();
    return $locations_list;
}

The idea is that I can run this function anywhere on my site and it will store all my posts in an array.
However, I have no idea how I run this at the public end :'(
Perfect world, I'd like to run this in my footer.php script.
Any help would be greatly appreciated.
Answer:
Perfect world, I'd like to run this in my footer.php script.

Then simply run the function in the footer.php template from your theme.
Also, avoid using query_posts() for custom queries because that function alters the main query. Use the WP_Query class directly instead:
$query = new WP_Query(array(...));
while($query->have_posts()) {
  $query->the_post();
  // $locations...
}

FYI the_title() prints the post title on the screen, so you don't need to assign it to a variable because it returns nothing.
Comment: I'll give it a whirl. Won't be a moment :-)


Marginal likelihood of a Gaussian Process?

Question: I've been studying Gaussian processes (GP), this resource implements GP from scratch and has been very useful in visualizing what's happening. So far all has made sense to me except for the below equation (eq 11 in link), the log marginal likelihood of the GP:
$$ -1/2 [Y^{T} K_y^{-1}Y] -1/2 [log(|K_y|)] - N/2[log(2 \pi)]$$
The author explains that this step is necessary to optimize the hyperparameters of the kernel function. I've used some algebra and found that this is simply the log multivariate gaussian PDF:
$$ \frac{exp(-1/2 Y^{T}K_y^{-1}Y)}{|K_y|^{1/2}(2\pi)^{N/2}} $$
My question is- what has been marginalized out? I gather it's either the old data (training) or the new data (at inference). But I'm not sure which. Intuition and context lead me to believe that we're optimizing kernel hyperparamters for the new data (else why not just accomplish this step during in the prior?)
However, the author defines {$K,K_*, K_{**}$} as $K(old, old)$, $K(old, new)$, and $K(new, new)$. I'm not sure which of the above $K_y$ is supposed to represent, what has been marginalized out, and some intuitions as to why it's been marginalized out. Could anyone comment on the what/why of what's going on here?
Answer: $K_y$ represents $K(old, old)$. You are marginalizing out the Prior over function values, which is explained in the "Prior" section of the blog. By marginalizing out the prior over function values you are able to optimize parameters of kernel function(in the case of RBF kernel it is $l$ and $\sigma_f$) based on the information you acquire from the training data.
I believe this blog is a review of the some chapters of "Gaussian Processes for Machine Learning by Carl Edward Rasmussen and Christopher K. I. Williams". The book explains the concepts clearly.
Comment: I think you are confused because author does not derive the results in functions 4 and 5. Those results deriven from posterior over function values, with the assumption poserior follows a gaussian distrb. Parameters $\{l, \sigma_f \}$ are estimated by MLE because they are required to calculate mean and covariance which are obtained from posterior. "95% confidence interval" can be used in bayesian setting too as long as you are able to estimate distrb, difference is in the estimation of distrb. not the usage of confidence interval. Chapter 2 of the book explains your questions in detail.
Comment: This optimization technique seems akin to MLE. I'm not seeing anything particularly Bayesian in the author's write up, other than the use of words, prior & posterior. In a Bayesian design, would the parameters, {$l, \sigma_f$} be sampled? (Or am I confused?)
Comment: Also, the author uses "95% confidence interval" often, which is from the frequentist paradigm.


use of unassigned variable c#

Question: What is the best way to solve the error use of unassigned variable? The following code contains error:
string[] Names;
Countries.Keys.CopyTo(Names, 0);

Here Countries is of type Dictionary<string, string>. Error comes for the Names array.
Comment: Names are not assigned. try string[] Names = new string[5];
Comment: But what if Keys have count more than 5 ?
Comment: The compiler isn't smart enough..
Comment: @user1574860 He should of course use the size he needs.
Answer: You need to create an empty array to copy the values into:
string[] Names = new string[Countries.Keys.Count];
Countries.Keys.CopyTo(Names,0);

If you can use LINQ, you can do this as
string[] names = Countries.Keys.ToArray();

Answer: Assuming the country set is a dictionary, for example:
string[] names = new string[countries.Count];

Regarding .NET coding conventions, local variables as well as private type members should be titled camel cased, thus use "name" instead of "Name" and "countries" instead of Countries, assuming Countries is not a property.
Answer: it's better to use default construct, if it's possible, on initialization of some variable with some it's intiial value:
For example :
var x = default(int);

in your case, it could be
string[] s = default(string[]);

EDIT
Considering edited question, you have to carry about intializing correctly, as default value for reference-type would return null, which in your specific case, would generate exception.
So just initialize it like:
string[]  s=  new string[Countries.Keys.Count];

Comment: I also challenge you to write a `CopyTo` method with the signature described in the original question where passing a null array can do _anything_ useful.
Comment: it says Countries is a Dictionary in the question
Comment: `new string[Countries.Keys]` also makes no sense.
Comment: [This will throw an ArgumentNullException](http://msdn.microsoft.com/en-us/library/06x742cw.aspx).
Comment: default is kind of unnecessary when not working with generics. 'null' is much more concise then 'default(string[])'.
Comment: @Rawling: **wrong**. It depends on **what** is it *Countries.Keys* and *how* it's implemented.
Comment: @MrDosu: I would call this "coding preference". Someone likes it, someone not.
Comment: My mistake. I meant [this will throw an ArgumentNullException](http://msdn.microsoft.com/en-us/library/91e2z0hz.aspx).
Comment: @Tigran If something just introduces complexity for no gain I wouldn't call it preference. The default keyword was explicitly created to assign default values in generic classes when you don't know if you have a reference or value type in front of you.
Answer: You must initialize the array to overcome this:
string[]  Names =  new string[Countries.Keys.Count];

use of unassigned variable c#


How to return from fullscreen mode in Chrome Mobile

Question: I have problem with returning from full-screen mode in Chrome Mobile.
I found some fullscreen example and added one feature. When browser is in full-screen mode then image border is red.
#root:-webkit-full-screen  > .img-wrap > .img-01
{
    border: 2px solid red;
}

Sample app you can find here:
https://codepen.io/herrmefisto/pen/eraKKg
If you click button then it will open in fullscreen mode and image border will be red. If you push "Esc" button then border will be still red!! On real android device Esc == back button.
I found also that events: webkitfullscreenchange, mozfullscreenchange, fullscreenchange, MSFullscreenChange are not fired when pushing Esc button on keyboard.
There are few libraries (cross browser) like e.q BigScreen (https://brad.is/coding/BigScreen/) but this bug exists also here.
Is anybody know how to make some hack/workaround to make it work?
In desktop Chrome (ver 66) it works fine.
Comment: What Chrome mobile version? Try using [this solution](https://stackoverflow.com/a/25876513/7663972).
Comment: I did it in exactly same way, but it doesn't work.
What Chrome mobile version?  - You can open Chrome on desktop (I have version 66) and push F12 to open developer tools. Then click "Toggle Device Toolbar" to open app in emulator. It works exactly the same as on my Android Device (Samsung Galaxy A5 with Chrome 66.0.3359.158)
Comment: If the problem was solved, please [accept](https://stackoverflow.com/help/someone-answers) the answer that you believe is the best solution to your problem, or you can provide and [accept your own answer](https://stackoverflow.blog/2009/01/06/accept-your-own-answers/).
Answer: Fullscreen is not available in SO snippet, so I made a fork of your version on codepen.io with "exitHandler" method changes. From this:
function exitHandler() {
    if (
       !document.webkitIsFullScreen
       && !document.mozFullScreen
       && !document.msFullscreenElement) {
        console.log("asdasd");
    }
}

to this:
function exitHandler() {
    if (
        document.webkitIsFullScreen === false
        || document.mozFullScreen === false
        || document.msFullscreenElement === false
    ) {
        alert("exit fullscreen");
    }
}

On my Android device (not Samsung Galaxy A5) with Chrome v.66.0.3359.158 in fullscreen mode on Esc key press the alert is displayed, so "webkitfullscreenchange" exit event is fired. The border color of the picture also changes after exiting the fullscreen mode.
But in Google Chrome for Windows v.66.0.3359.181 in device toolbar none of the devices is firing the fullscreen exit event. But if you choose "Responsive", then everything is OK with any screen size. If no one has posted a bug about this, then you should do so.
Comment: Did my answer help to solve the problem, @HerrMefisto?
Answer: Opening, document.documentElement:
document.documentElement.requestFullscreen();

Exiting full screen mode, document object:
document.exitFullscreen();

Manually, you drag the top of the screen to down, and Android shows the android navigation bar.


Getting the node.js monitor-dashboard project to work externally

Question: I'm trying to get the monitor-dashboard project to work but i get a page can't be found error when I try to use a browser externally.
http://lorenwest.github.io/monitor-dashboard/
Internally seems OK, I'm getting a HTTP/1.1 200 OK from http://localhost:4200 with the usual curl command.
I went in to node/node_modules/monitor-dashboard/config/, and changed default.js and external.js and changed all occurrences of allowExternalConnections to true.
I've also got node-monitor loaded in to my node project.
I'm running node server.js first and then npm start monitor-dashboard in another window.
port 4200 is open via iptables -L
Any ideas?
Answer: The setting you're looking for is:
export NODE_ENV=external


Should one examine the cross-correlation plot to rule out performing Granger causality test?

Question: Should one look at cross-correlation plot before performing Granger causality test to avoid type I errors?
If we can't find any dependence between two series from the cross-correlation plot, then should we always not perform a Granger causality test?
Answer: No.
First, if you are really concerned about type I error rate, use a lower significance level in your test. That is why we have the "significance level knob" built into statistical tests!
Second, it seems you consider using the cross-correlation (CCF) plot as a substitute for the Granger-causality test to avoid doing the actual test. This is not a perfect substitute, but they are related, so I get the intuition. However, you would not gain anything this way. If one method (the CCF) shows absence of a certain relationship, the other method (Granger causality test) would tend to do the same – to the extent one can substitute for the other. So if you see absence of certain correlations, you will tend to find absence of Granger causality, and that would not systematically affect your type I error rate.


Is there any exchange in stack overflow to guide writing economic paper?

Question: Maybe it is off-topic. But I am wondering where in stack overflow that I can ask people some suggestions for some sentences or how to write an introduction and literature review for economics and finance papers with good tension.
Thank you in advance. I will close this topic and hope that I can receive the suggestion
Answer: There are several guides available, here are those I know (and appreciate):
McCloskey Deirdre N., Economical Writing, Thirty-five rules for clear and persuasive prose, Third Edition
Neugeboren Robert H., 2005, The Student's Guide to Writing Economics, Routledge
Thomson William, 2011, A Guide for the Young Economist, MIT Press (2nd edition)
McCloskey also wrote an article available on her webpage:
http://www.deirdremccloskey.com/docs/pdf/Article_86.pdf
Answer: The stack exchange format is not really for one on one guidance. The goal is to create a depository of knowledge that is useful for future visitors. For writing in general, there is Writing.


Proof of propensity score theorem - problem with conditional expectation

Question: My question is about the "propensity score theorem", which is quickly presented here : https://en.wikipedia.org/wiki/Propensity_score_matching#Main_theorems
The paper of the authors of the theorem, Rosenbaum and Rubin (1983), is available here :
the central role of the propensity score in observational studies for causal effects (the pdf document is freely available).
My question is about the fifth theorem, that can be found on the fifth page of the pdf file.
The proof is also reproduced here, in its most simple form : https://www.youtube.com/watch?v=YwzkQnpXLDM
At some point we end up with E{P($z = 1 | x$) | $r_1$, $r_0$, P($z = 1 | x$)} and so they conclude that is is equal to P($z = 1 | x$) whereas I would say that it is equal to E{P($z = 1 | x$)} and since E{.} is the expectation over the $x$ (we know that from the beginning of the proof, when the person in the video is invoking the law of iterated expectations), we should end up with the unconditional probability $P(z = 1$).
Where am I mistaken?
Answer: What you have is simply something like $\mathbb E[X|Y,Z,X]$ which is equal to $X$, not $\mathbb E[X]$ because $X$ is given. In other words, given $P(z=1|x)$, your expectation about $P(z=1|x)$ should be the value given.


How to access xcconfig variables from XCUITest code

Question: I need to access an environment variable named ENV that is set in the xcconfig file for my main app target, but from inside my UI test target.
After doing a ton of googling this is what I've tried:

set the main xcconfig as the configuration for the UITest target
add an environment variable ENV=$(ENV) in the test plan configuration
print the environment dictionary like this

print(ProcessInfo.processInfo.environment)

But $(ENV) is not expanding to the real value.
I also tried adding a custom entry in the Info.plist for the UITest target
<key>ENV</key>
<string>$(ENV)</string>

And then accessing it via Bundle.main.infoDictionary but again I just get the string $(ENV). Any idea what I am missing, or is this just impossible because of the way UI tests work in Xcode?
Answer: What you have to do is to either use the app target's xcconfig as the build config for your test target. Or if you need to have specific test target's build config, you include the app's xcconfig into your test target xcconfig.
Then in your test plan settings you define your test plan environment var as ENV=$(ENV)
Basically:
apptarget.xcconfig:
ENV=appenv
testtarget.xcconfig:
#include apptarget.xcconfig
in testPlan environment you define:
ENV=$(ENV)
XCConfig is used during build time. The $(ENV) has to be expanded in build time to the value you want. You will accomplish that by either using the apptarget.xcconfig as the xcconfig of your test arget or including it into your testarget.xcconfig


What can I do to be sure that a background service will not start twice?

Question: The past few days I am working on creating a background service and I noticed that quite a few people say that AlarmManager is the best way to go.
<code>    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    //After after 5 seconds
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 ,
</code>
What I wish to know is how to make sure that if this code is ran twice the service won't start 2 times. Thank you for the help in advance!
Comment: What exactly do you mean by start twice? If a `Service` is already running the second start command will also be sent to the running `Service`. You cannot have two instances of the same `Service` at the same time. However if you want to perform some action only once regardless of how often the `Service` is started you can for example use `SharedPreferences` to save if the task has already been executed or not.
Answer: A service can't be started twice, it will remain running if you try to start it again.
See here: http://developer.android.com/guide/components/services.html#StartingAService
Edit:
However, everytime you start the service, the onStartCommand() method is called.
Answer: This is what I have used, for starting service after 30 seconds from current time,
<code>  Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
  PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);
  AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
  alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
</code>
Try it, and let me know what happen...
EDIT:
In your manifest.xml file
<code>  <service android:enabled="true" android:name=".ServiceClass" />
</code>
Comment: if i restart my device then will this alarm manager will start service again without trying to open my app ? or may i need to start my service using boot_completed reciever


Determining the position of the specific combination with repetition

Question: A $k$-combination with repetitions, or $k$-multicombination, or multisubset of size $k$ from a set $S$ is given by a sequence of $k$ not necessarily distinct elements of $S$ (size $n$), where order is not taken into account. Click here for details. However, there is one restriction that each element can't be more than $n$ times. The number of such combinations is given by (look here for the explanation):
$$\left(\!\!\!\binom{n}{k}\!\!\!\right)-\binom{n}{1}\left(\!\!\!\binom{n}{k-(n+1)}\!\!\!\right)+\binom{n}{2}\left(\!\!\!\binom{n}{k-2(n+1)}\!\!\!\right)-\ldots.$$
My question is following. How can I determining the position of some specific combination? This problem appears on my programming task where I want to save my computer memory.
Example. $n=6$, $k=9$, the number of the combinations with repetitions and no more than $n$ repetitions is
$$\left(\!\!\!\binom{6}{9}\!\!\!\right)-\binom{6}{1}\left(\!\!\!\binom{6}{2}\!\!\!\right)=1876.$$
My specific combination is $\lbrace 1,1,1,1,1,1,2,3,3\rbrace$. I want to add specific number between $1$ and $1876$ for my specific combination.
Comment: Do you mean the size of S to equal the maximum number of matching elements in the combination?  You used $n$ for both.
Answer: Let $f(n,k,m)$ be the number of $k$-multicombinations from an $n$-set, in which no element may appear more than $m$ times.
Suppose we write down, in order, a multicombination of $\{1,2,\ldots,7,8\}$, and add $n-1$ bookmarks for each increment in the digits: $$'1'1'1'1'1|2'2'2|3'3'3'3||5'5'5'5'5||7'7|8'8'8'$$
Give the name $a_i$ to the position (increasing from left to right) of the bookmark after the digit $i$.
Now you want to count the multicombinations which come before it in dictionary order. Suppose such a multicombination has bookmarks $a_1', a_2',\dots$ (The one shown above has $5,3,4,0,5,0,2$.) Then it belongs to one of the following categories:

$a_1<a_1'$
$a_1=a_1'$ but $a_2<a_2'$
$a_1=a_1'$ and $a_2=a_2'$ but $a_3<a_3'$, etc.

These could be counted like this:

$\sum_{i=a_1+1}^m f(n-1,k-i,m)$
$\sum_{i=a_2+1}^m f(n-2,k-a_1-i,m)$
$\sum_{i=a_3+1}^m f(n-3,k-a_1-a_2-i,m)$, etc.

a total of $n-1$ sums, any of which can be empty.
It may be possible to simplify the total by taking advantage of properties of $f$ with fixed $m$, for example, a recurrence relation.
Edit. Let's consider the case $m=3$.
$$\begin{array}{c|cccccccccccccccc}
_n\backslash^k&0&1&2&3&4&5&6&7&8&9&10&11&12&13&14&15\\\hline
1&1&1&1&1\\
2&1&2&3&4&3&2&1\\
3&1&3&6&10&12&12&10&6&3&1\\
4&1&4&10&20&31&40&44&40&31&20&10&4&1\\
5&1&5&15&35&65&101&135&155&155&135&101&65&35&15&5&1\end{array}$$
Obviously if you've been working on this problem you've seen a table like this before. The recurrence is $$f(n,k,m)=\sum_{i=0}^mf(n-1,k-i,m)$$
You will easily find that $f(6,8,3)=546$. Now consider the multicombination $11233566$ with bookmarks $2,1,2,0,1$. How many entries come before it on a sorted list? Applying the method, we sum:
$$\begin{array}{c|cccccccccccccccc}
_n\backslash^k&0&1&2&3&4&5&6&7&8&9&10&11&12&13&14&15\\\hline
1&\boxed{1}&\boxed{1}&1&1\\
2&\boxed{1}&\boxed{2}&\boxed{3}&4&3&2&1\\
3&1&3&\boxed{6}&10&12&12&10&6&3&1\\
4&1&4&10&\boxed{20}&\boxed{31}&40&44&40&31&20&10&4&1\\
5&1&5&15&35&65&\boxed{101}&135&155&155&135&101&65&35&15&5&1\end{array}$$
to get $1+1+1+2+3+6+20+31+101=166$. And if you ask your computer to sort the list of $546$ combinations, you will find that $11233566$ is indeed the $167$th item on the list.
Comment: I can't understand your answer. Can You give an example?
Comment: Say you have 111222333, and the limit for any symbol is five. The strings appearing before it in the list must be the completions of 1111..., 11111..., (moving the first bookmark to the right) then below them the completions of 1112222..., 11122222... (moving the second bookmark to the right).
Comment: Let $n=6$, $m=6$, $k=2$. Then the first sum can't exceed $1+5$, the second sum can't exceed $1+4$, ..., the fifth sum can't exceed $1+1$. From this it can be concluded that total sum can't exceed $20$. However, $f(6,2,6)=21$... I think that the answer is incomplete. Can you enumerate all combinations for this case with $k=2$?
Comment: The list will go 11, 12, 13, 14, 15, 16, 22, 23, 24, 25, 26, 33, 34, 35, 36, 44, 45, 46, 55, 56, 66. There are twenty-one numbers, therefore we would expect that the maximum number of predecessors for any number is 20. Fix $m\ge k$ and then the number of predecessors for "34" must be $f(5,1)+f(5,0)$ (first sum) plus $f(4,1)+f(4,0)$ (second sum) plus $f(3,0)$ which makes $6+5+1=12$, and "34" is indeed 13th in the list.
Comment: I have edited my answer to give a fuller example using a table of results.


Curve not parametrized by arc length

Question: Let $\alpha:I=[t_0,t_1] \to \mathbb{R}^3$, $\alpha=\alpha(t)$ is a regular curve not parametrized by arc length and $\beta: J=[s_0,s_1]\to \mathbb{R}^3$, $\beta=\beta(s)$ a reparametrization by arc, where $s=s(t)$ is calculated from $t_0$. Let $t=t(s)$ be the inverse function and $\frac{d\alpha}{dt}=\alpha',\frac{d^2\alpha}{dt^2}=\alpha''$, etc. I want to prove that
$$\frac{d^2t}{ds^2}=-\frac{\alpha'\cdot \alpha''}{||\alpha'||^4}.$$
We can define $s:[t_0,t_1]\to [s_0,s_1]$ and it's a difeomorphism as
$$s=s(t)=\int_{t_0}^t ||\alpha'(u)||du,$$
that is to say, $s(t)$ measure the arc length. Then, it's easy to see that
$$||\alpha'(t)||^{-1}=\frac{dt}{ds}.$$
I try to develop $\alpha''(t)$, but I don't get anything similar.
$$\alpha(t)=s'(t)^2\boldsymbol{t}'_\beta(s(t))+s''(t)\boldsymbol{t}_\beta(s(t))$$
Can anyone help me?
Answer: I would be tempted to square everything, and write
$$ \left( \frac{dt}{ds}\right)^2 = \frac 1 {\alpha'(t(s)) . \alpha'(t(s))}.$$
This gets rid of the horrible square roots.
Now differentiate both sides, using the product rule and the chain rule:
$$  2 \frac{dt}{ds} \times \frac{d^2 t}{ds^2} = - \frac {2\alpha'(t(s)).\alpha''(t(s)) \times dt/ds}{ (\alpha'(t(s)) . \alpha'(t(s)))^2}.$$
I leave you to finish off...
Comment: The product $\times$ is vectorial product? If the answer is yes, why do you use this product and not the normal product?
Comment: No, $dt/ds$ is a scalar, so $\times $ is just ordinary multiplication. Sorry about the confusion.

Curve not parametrized by arc length


Geofield map : add marker on click listener

Question: I've added a google map which I feed thanks to the Geofield module.
I'd like to add an onClick event to each marker to have a custom behavior.
this is what I've done this far :
<code>  Drupal.behaviors.geofieldGoogleMapInteraction = {
    attach: function (context, settings) {
      if (context !== document) {
        return;
      }

      // React on geofieldMapInit event.
      $(document).on('geofieldMapInit', function (e, mapid) {
        var map = Drupal.geoFieldMapFormatter.map_data[mapid].map;
        var markers = Drupal.geoFieldMapFormatter.map_data[mapid].markers;
        map.addMarkerAddedCallback(function(markerClicked) { // is not a function
          triggerClick(markerClicked);
        });

        function triggerClick(markerClicked) {
          console.log("click !")
        }
        $.each(markers, function (storeId, marker) {
          if(parseInt(storeId) !== 56) return;
          const properties = marker.geojsonProperties;
          $(marker).on('click', function() {
            console.log("click") // not triggered
          });
        })
      });
    }
  };
</code>
I can't manage to trigger the on click of the marker ,I've got nothing in my console. Where am I wrong ?
EDIT : this is the source code of a single marker. I don't see any sign of how the marker id could be retrieved... (I have cluster and single markers at the same time)
Answer: If it help someone, this is what I came up with :
<code>  $(document).on('geofieldMapInit', function (e, mapid) {
    var map = Drupal.geoFieldMapFormatter.map_data[mapid].map;
    var markers = Drupal.geoFieldMapFormatter.map_data[mapid].markers;

    $.each(markers, function (storeId, marker) {
      const properties = marker.geojsonProperties;
      google.maps.event.addListener(marker, 'click', function() {
        console.log('click ' + storeId)
      })
    })
  });
</code>


jQuery: Animate Removal of Style Attribute from Multiple divs

Question: I have ~33 divs that I am setting the position of randomly and animating this places. These divs are originally positioned with the help of flex and then the positions are randomized by setting their positions to relative and changing the left and top values. This happens every click.
On every alternate click, I want to return the divs to their normal position. So far the only solution to this I've found is the .removeAttr('style') method. However, I want to be able to animate their return to original position. Is this possible?
Here is the code:
var position_checker = false;
$(document).click(function() {
 if(position_checker == false) {
  $('.poster05-text').each(function() {
  var position = $(this).offset();

  $(this).css({
    position: 'relative',
  }, position);

  var docHeight = $(document).height(),
    docWidth = $(document).width(),
    divWidth = 500,
    divHeight = 500,
    heightMax = docHeight - divHeight,
    widthMax = docWidth - divWidth;

    var posLeft = Math.floor(Math.random() * widthMax);
    var posTop = Math.floor(Math.random() * heightMax);

    // console.log(docHeight, docWidth);

  $(this).animate({
    position: 'fixed',
    left: posLeft,
    top: posTop
  }, 1000 , 'easeInQuint');
});
  position_checker=true;
}
else if(position_checker==true) {
$('.poster05-text').each(function() {
$(this).removeAttr('style');
});
position_checker=false;
 }
});

Answer: I don't know this a right way to do that or not .. but anyway .. you need to save the previous left and top positions for each div on array
var position_checker = false , T_L_Positions = [];
$(document).click(function() {
 if(position_checker == false) {
  $('.poster05-text').each(function(i) {
  var position = $(this).offset();

  $(this).css({
    position: 'relative',
  }, position);

  T_L_Positions[i] = new Array(position.top ,position.left);

  var docHeight = $(document).height(),
    docWidth = $(document).width(),
    divWidth = 500,
    divHeight = 500,
    heightMax = docHeight - divHeight,
    widthMax = docWidth - divWidth;

    var posLeft = Math.floor(Math.random() * widthMax);
    var posTop = Math.floor(Math.random() * heightMax);

    // console.log(docHeight, docWidth);

  $(this).animate({
    position: 'fixed',
    left: posLeft,
    top: posTop
  }, 1000 , 'easeInQuint');
});
  position_checker=true;
 }
  else if(position_checker==true) {
   $('.poster05-text').each(function(i) {
      $(this).animate({
         position: 'relative',
         left: T_L_Positions[i][1],
         top: T_L_Positions[i][0]
      }, 1000 , 'easeInQuint');
   });
position_checker=false;
 }
});

Note: This Code Not Tested .. but you can try it
maybe you'll need to wrap your code in $(document).ready(function(){ //code here })
Comment: Thanks for the answer. Unfortunately, while it's an intelligent solution, the divs don't return to the same position as they were in the `flex` box. They return the the position with tons of extra space in them.
Comment: Look @ShivamSinha you provide just the js code .. so my code is to give you the idea of how you can get the top , left position and save it on the array then return it back .. if this idea work the rest is on you .. I don't know the purpose of `position : relative` in your code.. you only know .. so you can cut/paste the line of the array before change the css to relative .. and you can keep working with animation styles to reach the effect you're looking for
Answer: If you're looking for a non-JS solution. You should be able to use CSS Transitions to do this.
transition: top 500ms, left 300ms;

That way you can just set and remove the position and let CSS deal with the animation.
For more information check out these examples:

https://www.w3schools.com/css/css3_transitions.asp
https://css-tricks.com/almanac/properties/t/transition/
Comment: Thanks for the answer. Unfortunately since the `top` and `left` values are being added via JS and aren't originally in the CSS, the transition property doesn't work.


How does the Galois group act on $E[m]$?

Question: Let $K$ be a perfect field and $\bar{K}$ its algebraic closure and say the characteristic of $K$ is $0$. Suppose I have an elliptic curve over $K$.
It (the book I am reading) says that the Galois group $G(\bar{K}/K)$ acts on $E[m]$ because: if $[m]P = O$ then
$$
[m](P^{\sigma}) = ([m]P)^{\sigma} = O^{\sigma} = O.
$$
I don't understand why the first equality is true. Any explanation is appreciated. Thank you.
Comment: The map $[m]$ is defined by polynomials with coefficients in $K$.
Comment: If you have your curve in some projective space, then he Galois group acts simply by acting on each coordinate of points.
Comment: The addition of the group is defined in terms of taking tangents and so on, so the action of the Galois group preserves it.
Comment: @LordSharktheUnknown I figured this was the case. Could you possibly explain this in the answer maybe for the simple case $m=2$ or something?
Comment: In any case, the case $m=2$ is the only one you need, because for example $[3]$ is the composition of two instances of $[2]$.
Comment: Alternatively, you can show that addition on $E$ is compatible with the action of $G=\text{Gal}(\overline{K}/K)$ by showing that the isomorphism $P\mapsto (P)-(O)\in Pic^0(E)$ is an isomorphism of $G$-modules, which is a one-liner.
Answer: $m\sigma(p)=\sigma(p)+...+\sigma(p)=\sigma(p+...+p)=\sigma(mp)=\sigma(\mathcal O)=\mathcal O $
we can explain how the Galois group $G(\bar{K},K)$ acts on $E[m]$ by form:
We have
$$ 0\to E(\bar{K})[m]\to  E(\bar{K}) \to E(\bar{K})\to 0 $$
then
$$ 0\to E({K})[m]\to  E({K}) \to  E({K}) \to Hom(G(\bar{K},K),E(\bar{K})[m])\to Hom(G(\bar{K},K),E(\bar{K}))\to ... $$
Comment: Can you explain the exact sequence? By $Hom$ I assume you mean $H^1$?


Passing data up in an onClick function in React

Question: I'm new to React/ES6 and I'm working on my first components. I have a PuzzleContainer component that contains a Puzzle component which displays images. The container component makes an AJAX call to determine what images to display and then passes that data down to the child component. I want to do something in the container component when one of the images is clicked.
Here is my code, I didn't include the componentWillMount() function in the container component, but cards is just an array of strings.
class PuzzleContainer extends React.Component {

    cardClicked(cardsrc) {
        console.log(cardsrc);
    }

    render() {
        return (

                    <Puzzle cards={this.state.cards} cardClicked={this.cardClicked}></Puzzle>

                <Infobar></Infobar>

        );
    }
    }

    class Puzzle extends React.Component {
        render() {
        var cards = this.props.cards;
        var html = cards.map((card) =>

                         this.props.cardClicked(card)}>

        );

        return (

{html}

        );
    }
}

The problem is, whenever I click an image, a Proxy(?) Object gets printed to the console. It seems to be some object from React. However, my understanding was that it should just print the card value that gets passed to the function, which is a string.
Why is an object getting logged instead of a string? How do I make it so the container component can receive the identity of the image that gets clicked?
Comment: [The answers in this SO question may explain things for you](http://stackoverflow.com/q/10218722/2902660)
Comment: the parameter card will have the event object instead of the card src value.
Answer: You use card as both the parameter for the map function as well as the parameter for the onClick function. As a result, the onClick event object is being passed to this.props.cardClicked rather than the string you desire.
Changing your img tag to
 this.props.cardClicked(card)}>

will do what you want.
Answer: The first parameter of an onClick handler is the event object.
onClick={(card) => this.props.cardClicked(card)} When you do this, the event object is assigned the name card and you are actually passing the event object to this.props.cardClicked instead of the card variable that you are looping through in map.
Do this instead:

Btw,  is self-closing and you can combine the opening and closing tag into one.


How to print all the unique combinations of a list?

Question: list_a = [1, 2, 3]

I want to print all the unique combinations from the list like this
[ [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3] ]

Note: Without using any module
Comment: This post may be useful -> https://stackoverflow.com/a/60907108/11433654
Answer: You need a variant of the powerset recipe from itertools:
from itertools import combinations, chain
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))

list_a = [1, 2, 3]

out = list(map(list, powerset(list_a)))

output: [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
If you don't want to use itertools you can quite easily reimplement combinations and chain using list comprehensions or functions.


How to set a coming soon page on drupal?

Question: All request must be redirected to the coming soon page, is there any module can do it or a solution, I'm using the zen base theme.
Thank you for your help :)
Comment: just create your own custom page www.example.com/comingsoon
Comment: Why would you even use Drupal for that? Just create an index.html with your coming soon message, and develop your soon-to-come website somewhere else.
Answer: You can put the site on maintaince mode and can use the message as coming soon.
Comment: This is a pretty good solution!  Just don't forget to change it back to a maintenance page once you've finished your build :)
Answer: Another way, mentioned by VM in this support request 5 years ago is:

[...] creating a page-front.tpl.php file for you theme which only gets called on the front page.

And use that tpl for the coming soon period.
I personally used the maintenance mode (see answer by arpitr in this page). But I don't know how to display a block in the maintenance mode. For instance a block with a mailing list subscription form (which is a must in a coming soon page). The front.tpl.php way instead is more customizable, I think. I'll check it out. (see updates in edit3)
Edit: I'll check out also mcd module which integrates with simplenews subscription block (this way it's possible to use the maintenance option).
Edit2: Also, with 3rd party service mailchimp one can embed her subscriptio form in the plain html of the maintenance page (see updates in edit3). Another way to go and use the maintenance page option.
Edit3: I've tried to insert an iframe (embedding mailchimp subscription form or google subscription form) in the maintenance page message, with no success. So, if one needs to deal with iframe embedding, one has to use the tpl.php option. The good news (for me) is that there is a more specific maintenance-page.tpl.php to configure for this.
Answer: Have you tried the Maintenance Countdown module? It puts your site in a maintenance mode and provides a nice counter for the time the site will be available again.
Answer: Check ComingSoon: A Distro for Collecting Pre-Launch Sign Ups. I think this could help you.

"Coming Soon" is a distribution for creating a launch site for an upcoming project, idea or business. In it's most basic sense, it's a Drupal clone of LaunchRock.com. It provides a simple signup / registration form on the homepage and unique share pages for new users. So that before the site, app or business itself actual launches, you can start to get new members.
Answer: you can create a panel with one column and put a block in it with all data you need
so you wil have a new page with a unique url then choose this page from configuration - site information in Default 404 (not found) page or put its link to all your incoming page
Comment: Thank u :), but like I say for all incoming requests not just 404 requests
Comment: ok you can set all your menu item to this page


Declined 'No Longer Needed' Comment Flags

Question: I flagged two comments on a question I came across, nearly 3 months ago now, and they were declined.
I've only just been back to notice this.
The specific comments are this and this one.
I flagged these as 'No longer required' which seems pretty reasonable to me. The first asks for clarification and the second one confirms the clarification. I also checked the revision history for the post which shows that the OP did update their question with the requested information.
These comments now serve no purpose that I can see (nor did they when I flagged them 7 days after they were posted and 7 days after the information was added).
Was there a reason that they are still required?
Answer: They got dismissed mostly because of this: Flagging comments
There are a lot of flagged comments that should not be deleted because that would disrupt the ideas discussed in the comments.
I guess your comments got dismissed because they were in a large pool of flagged comments and were overlooked.
I deleted them now.
As a side note...
Comments like that are not really needed, but they don't cause too much noise in the website.
my opinion is that comments should be flagged if they are rude or abusive or have nothing to do with the post.
Comment: Thanks for the answer. To clarify, I shouldn't be flagging comments which would fall under the 'No Longer Needed' category on Magento? The [flagging privilege page](https://magento.stackexchange.com/help/privileges/flag-posts) has a link to [the flagging guide](https://meta.stackexchange.com/questions/17364/how-does-comment-voting-and-flagging-work/17365#17365) which is what I followed. I don't visit this site very often so I didn't know the local customs. Apologies if this caused extra work! :)
Comment: Yes you should flag them. What I'm trying to say is that "no needed" is a bit relative and you should think twice before the comments are actually not needed and check if removing them does not disrupt the conversation flow. And no need to apologize. I encourage asking questions :)
Comment: Ah, I follow you now, thanks. In this case specifically the flags were good but generally, always check the context isn't ruined. Sorry, I misunderstood that this was a local site policy that I wasn't aware of.


Geometric interpretation of adding dependence on a otherwise constant in a vector field.

Question: So if i have
$$ \vec{u} = \Omega r \vec{e_{\theta}}$$
Now if i take the curl
$$\omega = 2\Omega\vec{e_z}$$
This is what we expect, we have a "rotating flow".
Who's curl would be pointing in the z direction.
Now when I make $\Omega = \Omega(z)$
I get
$$\omega = -\frac{\partial \Omega}{\partial z}r\vec{e_r}  + 2\Omega\vec{e_z}$$
I can understand that if we were to fix our r and move up the z axis we are no longer going to have the same "angular velocity". For some reason I can't quite string a sentence together to interpret this extra term, geometrically speaking.
Answer: To visualize it, you can take a look at a point, say $\theta = 0$ and $ r= constant $
So this is a view from x+ direction towards the origin.
The velocity distribution along the z axis is not even if $\Omega (z)$ is not constant. This will produce a non-zero component of swirl in x direction or in r direction. This is the extra term in your post.
Comment: what is swirl? Sorry, I have never heard that term before :)


Get email with raw headers and attachments in Spring Integration

Question: My question based on the topik enter link description here
I also use my own implementation of DefaultMailHeaderMapper and I set embedded-parts-as-bytes = true.
But I have a problem - I can't get email message attachments.
I get message, but I can't get attachments, because, as I can see from log, attachments don't have boundaries (for example I attach .gitignore file to mail) and, as a result, MimeMessage parser doesn't see attachments:
A15 FETCH 291 (BODY.PEEK[HEADER])
* 291 FETCH (BODY[HEADER] {860}
Content-Type: multipart/mixed; boundary="=-Kj0VeCHE3Jjjhv1T0WeN"
MIME-Version: 1.0
Message-Id: <firstname.lastname@example.com>
X-Mailer: mail.ukr.net 5.0
To: Pasha <email@example.com>
From: =?UTF-8?b?0J/QsNCy0LXQuw==?= <firstname.lastname@example.com>
Date: Sat, 04 Aug 2018 18:43:37 +0300
Received: from [10.10.80.11] (helo=frv197.fwdcdn.com) by frv34.fwdcdn.com; Sat, 04 Aug
2018 18:43:37 +0300
Received: from firstname.lastname@example.com by frv34.fwdcdn.com;    Sat, 04 Aug 2018 18:43:37 +0300
Received: from [10.10.10.34] (helo=frv34.fwdcdn.com)
by frv197.fwdcdn.com with smtp ID 1flyiP-000B5t-US
for firstname.lastname@example.com; Sat, 04 Aug 2018 18:43:37 +0300
Subject: test3
Return-path: <email@example.com>
)
A15 OK FETCH completed
A16 FETCH 291 (BODY.PEEK[1.MIME])
* 291 FETCH (BODY[1.MIME] {74}
Content-Type: multipart/alternative; boundary="=-Dw7rk3OclJQtNyghQ2Sv"
)
A16 OK FETCH completed
A17 FETCH 291 (BODY.PEEK[1]<0.16384>)
* 291 FETCH (BODY[1]<0> {374}
--=-Dw7rk3OclJQtNyghQ2Sv
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: binary
Content-Length: 2
--=-Dw7rk3OclJQtNyghQ2Sv
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: base64
PGh0bWw+PGJvZHk+PHNwYW4gY2xhc3M9InhmbV84MjI2NTc1MSI+PGRpdj48YnIvPjwvZGl2Pjwv
c3Bhbj48L2JvZHk+PC9odG1sPg0K
--=-Dw7rk3OclJQtNyghQ2Sv--
)
A17 OK FETCH completed
A18 FETCH 291 (BODY.PEEK[2.MIME])
* 291 FETCH (BODY[2.MIME] {168}
Content-Type: application/octet-stream; name=".gitignore"
Content-Transfer-Encoding: base64
Content-Id: <asor_1533397403953NSzHs>
Content-Disposition: attachment
)
A18 OK FETCH completed
A19 FETCH 291 (BODY.PEEK[2]<0.172>)
* 291 FETCH (BODY[2]<0> {172}
Ly5pZGVhLw0KLy5zZXR0aW5ncy8NCi9iaW4vDQovdGFyZ2V0Lw0KLmNsYXNzcGF0aA0KLnByb2pl
Y3QNCi5naXRpZ25vcmUNCi9zcmMvbWFpbi9yZXNvdXJjZXMvZW1haWwucHJvcGVydGllcyANCi9u
YnByb2plY3Qv
)
A19 OK FETCH completed
A20 EXAMINE Download
* FLAGS (\Answered \Flagged \Deleted \Seen \Draft $Forwarded)
* 291 EXISTS
* 0 RECENT
* OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft $Forwarded)]
* OK [UIDVALIDITY 1073741835]
A20 OK [READ-ONLY] SELECT completed
A21 CLOSE
A21 OK close completed

For example, below I show code without using headerMapper:
    * 291 FETCH (BODY[]<0> {1730}
Return-path: <email@example.com>
Received: from [10.10.80.11] (helo=frv197.fwdcdn.com) by frv34.fwdcdn.com; Sat, 04
Aug 2018 18:43:37 +0300
Received: from [10.10.10.34] (helo=frv34.fwdcdn.com)
by frv197.fwdcdn.com with smtp ID 1flyiP-000B5t-US
for firstname.lastname@example.com; Sat, 04 Aug 2018 18:43:37 +0300
Date: Sat, 04 Aug 2018 18:43:37 +0300
From: =?UTF-8?b?0J/QsNCy0LXQuw==?= <firstname.lastname@example.com>
Subject: test3
To: Pasha <firstname.lastname@example.com>
X-Mailer: mail.ukr.net 5.0
Message-Id: <firstname.lastname@example.com>
Received: from email@example.com by frv34.fwdcdn.com;
Sat, 04 Aug 2018 18:43:37 +0300
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=-Kj0VeCHE3Jjjhv1T0WeN"
--=-Kj0VeCHE3Jjjhv1T0WeN
Content-Type: multipart/alternative; boundary="=-Dw7rk3OclJQtNyghQ2Sv"
--=-Dw7rk3OclJQtNyghQ2Sv
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: binary
Content-Length: 2
--=-Dw7rk3OclJQtNyghQ2Sv
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: base64
PGh0bWw+PGJvZHk+PHNwYW4gY2xhc3M9InhmbV84MjI2NTc1MSI+PGRpdj48YnIvPjwvZGl2Pjwv
c3Bhbj48L2JvZHk+PC9odG1sPg0K
--=-Dw7rk3OclJQtNyghQ2Sv--
--=-Kj0VeCHE3Jjjhv1T0WeN
Content-Type: application/octet-stream; name=".gitignore"
Content-Transfer-Encoding: base64
Content-Id: <asor_1533397403953NSzHs>
Content-Disposition: attachment
Ly5pZGVhLw0KLy5zZXR0aW5ncy8NCi9iaW4vDQovdGFyZ2V0Lw0KLmNsYXNzcGF0aA0KLnByb2pl
Y3QNCi5naXRpZ25vcmUNCi9zcmMvbWFpbi9yZXNvdXJjZXMvZW1haWwucHJvcGVydGllcyANCi9u
YnByb2plY3Qv
--=-Kj0VeCHE3Jjjhv1T0WeN--

Is it a bug of Spring Integration, or I have to add some configuration? I'm using Spring Integration 4.3.17 and I also had tried this on the 5.0.5 version.
Answer: See JIRA for more info: https://jira.spring.io/browse/INT-4299.
Starting with version 5.2 we have introduce autoCloseFolder which you can configure on the MailReceiver to false. That allows together with disabled headerMapper you are going to have a full raw MimeMessage in the payload of produced message. So, you are good to parse attachments downstream whatever it is necessary.
Then you would need to close Folder from the IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE if you need.


Is there any difference between forget gates and remember gates?

Question: In this youtube tutorial by nervada the following diagrams can be seen:

The remember gate in Gated Recurrent Units (GRUs) in the diagram to the right seems to have an analogous function to the forget gate in LSTM (left diagram): filter out how much of the previous state will be kept or discarded.
Is there a more mathematical or technical difference between them?
Answer: Yes, the output of both the LSTM's forget gate and the GRU's remember gate are vectors with dimension equal to the LSTM's cell memory and GRU's hidden state, respectively, and pointwise values between 0 and 1.
They act by multiplying pointwise by the previous LSTM cell memory or the previous GRU hidden state, respectively. (Note, unlike the LSTM, the GRU does not maintain a cell memory separate from its hidden state.) Forget/remember gate values closer to 1 ensure that the previous cell memory/hidden state is retained, while values close to 0 wipe out the previous cell memory/hidden state.
Concretely (see notation definitions below), the GRU's remember gate is defined as $r_t = \sigma(W_r[h_{t-1},x_t])$, and the "remember-gated" hidden state is $h_{t-1}* r_t$.
Similarly, the LSTM's forget gate is defined as $f_t = \sigma(W_f[h_{t-1}, x_t] + b_f)$ and the "forget-gated" cell memory is $C_{t-1}* f_t$.
That is, mathematically they are pretty much the same thing, except for the bias term and the fact that the forget gate is pointwise-multiplied by the LSTM's previous cell memory, while the GRU's remember gate is pointwise-multiplied directly by its previous hidden state.
But after this initial step, what the LSTM does with its forget-gated cell memory vs. what the GRU does with its remember-gated hidden state is quite different.
Check out Chris Olah's blog post for a great explanation for the inner workings of an LSTM, featuring some particularly elegant and intuitive diagrams.
Notation

$x_t \in \mathbf{R}^x$ is the current input,
$h_{t-1} \in \mathbf{R}^h$ is the previous hidden state,
$C_{t-1} \in \mathbf{R}^c$ is the LSTM's cell memory,
$W_r$ is a weight matrix for the remember gate with dimension $h \times (x + h)$,
$W_f$ is a weight matrix for the forget gate with dimension $c \times (x + h)$,
$b_f \in \mathbf{R}^c$ is a bias vector for the forget gate,
$\sigma(\cdot)$ is the sigmoid function,
$[\cdot, \cdot]$ is vector concatenation, and
$*$ is pointwise multiplication.
Answer: The remember gate from GRU is rather similar to the output gate of the lstm. The role of the forget gate in the LSTM is represented by $(1 - z)$, where $z$ is the update gate from GRU.
For the mathematical details, I refer to my answer on a somewhat similar question.