text:
Q: Are their names the same: a local-tracking branch, the corresponding remote-tracking branch, and the corresponding remote branch being tracked?
*

*Are the names of a remote-tracking branch and the corresponding
remote branch being tracked necessarily the same?
If they can have different names, how does git fetch match the two
branches then? (a typical refspec to git fetch is +refs/heads/*:refs/remotes/remote/*)

*If I am correct, given a remote-tracking branch, we can create a
local-tracking branch that associates with it but has a different
branch name. (by the -b option in git checkout)
Further if the names of the remote-tracking branch and the
corresponding remote branch being tracked are the same,  how does
git push match the local-tracking branch and the remote branch? (a typical refspec to git push is +refs/heads/*:refs/heads/*)

A:
Are the names of a remote-tracking branch and the corresponding remote branch being tracked necessarily the same?

No.  However, making them not-match results in a lot of pain (and I haven't tested it on the push side).

If they can have different names, how does git fetch match the two branches then? (a typical refspec to git fetch is +refs/heads/*:refs/remotes/remote/*)

You may have multiple fetch = lines, so you could, for instance, do this:
[remote "strange"]
    fetch = +refs/heads/master:refs/remotes/strange/surprise
    fetch = +refs/heads/other:refs/remotes/strange/surprise2

Note, however, that you can no longer use refs/heads/* on the left of any additional fetch refspecs, since that will match master and other and (presumably) map them to names other than surprise and surprise2, and git fetch aborts with an error message in this case.  This effectively forces you to list every refs/heads name that you wish to copy from the given remote (strange, in this case).
(As I said, I haven't tested this with push and I don't know if push obeys the same mapping rules as fetch.  There were some recent changes, around git 2.5 or so, to handle "triangular" work-flows better, where you fetch from localmirror and push to centralserver for instance.  One of those changes was to add the same kind of name-mapping for the push remote.  Presumably, before this new code went in, doing this kind of pushing brought even more pain, possibly even without a triangular work-flow; and presumably now it works better....)
We might call this "silly renaming tricks", and my advice would be: don't use them. :-)  I think they'll work correctly with most commands, and fail with others, though I can't point to any specific failure examples (just vague memories of how I used to do things).

If I am correct, given a remote-tracking branch, we can create a local-tracking branch that associates with it but has a different branch name. (by the -b option in git checkout)

Yes; and this works fine for all kinds of local work.  Again, I'd avoid the phrase "local-tracking branch", and just say "local branch with an upstream" as this is the direction git documentation has moved since about 1.7 (see below).

Remember that "the upstream of local branch $branch" is produced by:

*

*obtaining the remote name from git config --get branch.$branch.remote, and

*mapping branch-name from git config --get branch.$branch.merge through the fetch = refspecs for that remote.

Thus, suppose we've created two local branches test1 and test2 and have the following:
$ git config --get branch.test1.remote
origin
$ git config --get branch.test1.merge
refs/heads/test
$ git config --get branch.test2.remote
origin
$ git config --get branch.test2.merge
refs/heads/test

Both test1 and test2 refer to refs/heads/test, which is the name of a branch on the other git repository that will be located via the name origin: this is why we need to run these through the fetch = map(s) for origin.
In the absence of silly renaming tricks, the "mapped through" part leaves the branch-name part (everything after refs/heads) unchanged, and just replaces the middle bits, so that refs/heads/test becomes refs/remotes/origin/test.  That's really easy to make assumptions about.  I believe some lazy script-writers (including myself in the past) may have used this bit of shell script code:
fullbranch=$(git rev-parse --symbolic-full-name $branch) || exit 1
remote=$(git config --get branch.$branch.remote)
rmtbranch=refs/remotes/$remote/$branch

which not only assumes the lack of silly renaming tricks, it even assumes that if we're on branch test1, the upstream must be origin/test1, not origin/test.  Slightly less lazy script writers (including myself in the past) then had to fix their scripts, e.g.:
fullbranch=$(git rev-parse --symbolic-full-name $branch) || exit 1
remote=$(git config --get branch.$branch.remote)
theirname=$(git config --get branch.$branch.merge)
rmtbranch=refs/remotes/$remote/${theirname#refs/heads/}

which now assumes that refs/heads/test on the origin maps to refs/remotes/origin/test in the local repository.
Adding silly renaming tricks means that we can't find the actual upstream name easily at all, but various commands (e.g., git merge, git rebase) automatically find the correct upstream.  To make it easier for scripting, git version 1.7.0 grew the @{upstream} notation: you can now simply write $branch@{upstream}.  The git parser looks up the upstream for you, and the above (broken) script fragment can be rewritten as:
rmtbranch=$(git rev-parse --symbolic-full-name $branch@{upstream}) || exit 1

This is all fine and good for fetch, but what about push?  Well, if you're pushing to the same remote that you're fetching from, you just do the same thing.  But you can, for any number of reasons,1 split them up: fetch from repository F and push to repository P.  In this case, we might need different mappings for F and P.
Git 2.5 introduced @{push}, as noted by VonC in some earlier SO thread I can't find offhand, and in this github blog posting.  The new @{push} notation simply switches from using the fetch upstream to using the push upstream, i.e., using the P mapping instead of the F mapping.
There's still one good question, and it's your last one here:

Further if the names of the remote-tracking branch and the corresponding remote branch being tracked are the same, how does git push match the local-tracking branch and the remote branch? (a typical refspec to git push is +refs/heads/*:refs/heads/*)

My answer for git 2.5, with the new push stuff, is: I don't really know for sure, but your "typical refspec" is no longer the default (since git 2.0).  When you run git push with no refspec arguments, git looks up your push.default setting (along with a bunch more optional settings but push.default is effectively2 required).  It has five possible values, and only one of them—not the default—amounts to refs/heads/*:refs/heads/*.
One of those settings is upstream, and that setting runs the current branch's merge setting through the map functions (presumably, in git 2.5 and later, through the new separate push map if present, else through the fetch map).

1One reason is to use a pull-request repository, as in the linked github blog post.  Another is to fetch from a local mirror (as at a large corporate setup with local mirrors for various branch offices), but push to a single central server (the corporate-designated "master" site that all the local mirrors actually mirror).
2If you fail to set push.default, git spits out a lot of annoying text.  The best way to shut it up is to set push.default, so that means you're "required" (in some sense anyway) to set it.  And, since git 2.0, the default setting, if you haven't set it, is simple, which forbids silly renaming tricks.

A: refspec
As you said its the refspec which lies inside your .git/config file.
The git config file contains the information about the refspec

Note
In order to see what you described do this:
// Checkout master
git checkout master

// rename the master branch to a new name
git branch -m <old name> <new name>

// View the .git/config file and you will see the the new branch is still
// pointing (tracking) to the master branch, just like you described

Using the refspec you can control to which branch pull/push will refer.
Seting tracking branch
git branch -u <upstream>/<branch name>

matching
Git v2.0 Release Notes
Backward compatibility notes
When git push [$there] does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there).  In Git 2.0, the default is now the "simple" semantics,
which pushes:

*

*only the current branch to the branch with the same name, and only
when the current branch is set to integrate with that remote
branch, if you are pushing to the same remote as you fetch from; or

*only the current branch to the branch with the same name, if you
are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable push.default to change this.
If you are an old-timer who wants to keep using the
matching semantics, you can set the variable to "matching", for
example.  Read the documentation for other possibilities.

A: The answer from @codeWizard is the full and complete answer, but the plain english answer (based on your comment questions on his answer) is:
1 is really two questions. The answer to the first is: No, they don't have to have the same name. The answer to the second is: fetch doesn't actually map the local and remote branches. All fetch does (using your example--the defaults) is ask remote for it's list of refs/heads/*, and the associated blobs, and stores the refs in refs/remotes/* rooted using the remote name.
2 The mapping of the local branch to the remote branch is controlled by either using explicit pull and fetch calls, or setting everything up in .git/config. In git/config The pull behavior is controlled by $branch.merge, but push is controlled by push.default: which by default will push to the same branch name on the remote as the local. If you set this to upstream then it'll use the $branch.merge as the push target.
Walkthrough:
mkdir t1 && cd t1
git init
touch file
git add file
git commit -a -m "remote"
cd ..

git clone t1 t2
cd t2
git branch -a # you should see 'master' and 'origin/master'
git branch -m master local
git pull # Should say "Already up-to-date"
git branch -a # you should now see 'local' and 'origin/master'
git push # damn! It pushed 'local' to 'origin/local'!
git push origin :local # delete 'origin/local'
git config push.default upstream # tell git to use 'local.merge' as the push target
git push # Now it should say "Everything up-to-date"

And after all this your t1 config should look like this:
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true

And t2 should look like this:
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = /nas/src/t/t1
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "local"]
    remote = origin
    merge = refs/heads/master
[push]
    default = upstream

A: I know it's an old question, but clear-cut answer is right from man page of git-config (enter git help config or man git-config). Examples on how to use below information is right after the quotation:

push.default
Defines the action git push should take if no refspec is explicitly
  given. Different values are well-suited for specific workflows; for
  instance, in a purely central
workflow (i.e. the fetch source is equal to the push destination),
  upstream is probably what you want. Possible values are:
·   nothing - do not push anything (error out) unless a refspec is
  explicitly given. This is primarily meant for people who want to avoid
  mistakes by always being
explicit.
·   current - push the current branch to update a branch with the same
  name on the receiving end. Works in both central and non-central
  workflows.
·   upstream - push the current branch back to the branch whose
  changes are usually integrated into the current branch (which is
  called @{upstream}). This mode only
makes sense if you are pushing to the same repository you would
  normally pull from (i.e. central workflow).
·   simple - in centralized workflow, work like upstream with an added
  safety to refuse to push if the upstream branch's name is different
  from the local one.
When pushing to a remote that is different from the remote you
  normally pull from, work as current. This is the safest option and is
  suited for beginners.
This mode has become the default in Git 2.0.
·   matching - push all branches having the same name on both ends.
  This makes the repository you are pushing to remember the set of
  branches that will be pushed out
(e.g. if you always push maint and master there and no other branches,
  the repository you push to will have these two branches, and your
  local maint and master
will be pushed there).
To use this mode effectively, you have to make sure all the branches
  you would push out are ready to be pushed out before running git push,
  as the whole point of
this mode is to allow you to push all of the branches in one go. If
  you usually finish work on only one branch and push out the result,
  while other branches are
unfinished, this mode is not for you. Also this mode is not suitable
  for pushing into a shared central repository, as other people may add
  new branches there, or
update the tip of existing branches outside your control.
This used to be the default, but not since Git 2.0 (simple is the new
  default).

So, to set git to whichever configuration that suits you, enter:
git config push.default nothing

replace nothing with your preferred configuration. If you want it to be global (all repos on your local machine), add the global option:
git config --global push.default nothing

To answer your questions:

*

*No

*Yes


text:
Q: JavaScript to Replace One QuickTime movie with Another I am very new to javascript so bear with me:
I am trying to replace one quicktime movie with another one, so far i have used this code from apple and it works great
you can see my efforts here: http://www.centurysunstudios.co.uk/test/
please look at the source code (i tried to past the code here but would not let me for some reason; said i could only post one url as a new user? )
the problem is that the replace method apple use works in every browser (on osx and windows) apart from IE. In IE the movies do not replace and i get this message;
Error: document.movie is null or not an object
Apple seem to not have a solution and my javascript is limited
Any help would be greatly appriciated
Thanks

A: Try this:

L(o2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run python script located on computer with aws s3 folder object as input parameter in an ec2 instance I am trying to run a python script that takes a folder of pdfs as an input, and outputs an excel file in the current directory. In terminal I would enter the line below and an excel file would appear in the current directory.
$python3 script.py folder
I was wondering how to run this script with a folder located in an aws s3 bucket as the input without having to download the folder because it is pretty big. I believe you have to use an ec2 instance but am unclear about the whole process, especially how to have the s3 folder object be the input parameter for the python script.

A: You can use AWS SDK (Boto3) in Python to list content of S3 bucket, get each object and perform operations on it.
Here's how you normally do it:

*

*Get access to s3 client handler:
Get Boto3 S3 Client

*List S3 Bucket Objects:
List S3 Bucket Objects

*Iterate the list and get object:
Get Each Object

*Perform whatever operations you're looking for on each object.
Moreover, you can use generators with python to make the application memory optimized while iterating over list.
Note: If you're using EC2, it's a best practice to attached the IAM role with permissions to the specific bucket you're trying to list.
Thanks!

A: You would use the AWS SDK for Python (Boto3) to list the contents of an S3 location and stream the contents of each S3 object. The parameter you would pass to the script would be an S3 url like s3://my-bucket/my-folder. You would have to replace all the local file system I/O calls in the script with Boto3 S3 API calls. There would be no requirement to run the script on an EC2 instance, although it would generally have a faster connection to S3 than your local computer would.


text:
Q: Less strong synonym for "disastrous" I want to say that a particular effect may have negative consequences. I have used the word disastrous:

May have disastrous consequences.

However, it is too strong. I need another word. Any suggestion?

A: For negative consequences without sounding too strong, I'd like to suggest undesirable, i.e. undesirable consequences.
From Google,

undesirable
  adjective: undesirable
  1. not wanted or desirable because harmful, objectionable, or unpleasant.

Other similar words: unpleasant, unwelcome, unwanted

A: You could call them unfortunate consequences.


text:
Q: LWC: Chained property not refreshing I chained two wires to get a sales rep's name, but the name does not refresh.
This Lightning Web Component displays account information.
Account has a User lookup field called Sales_Representative__c.
I found Salesforce would not let me import Sales_Representative__r.Name or Sales_Representative__c.Name, so I created a separate chained @wire to look it up.
The problem is that the sales rep's name does not refresh when the name is changed in another window.
Question1: How come this doesn't refresh? Tested in Chrome and Safari.
Question 2: What is the best way to imperatively look up the user's name for example within the accountWire function?
When the sales rep is changed, the salesrepid also does not change, so the first wire is not refreshing.
EDIT:
As @akiradev pointed out, the import does work after all so I do not need a second wire.
However, the Sales Representative field in the LWC still does not automatically update onscreen when I change the Sales Representative from the account's record page in another window.
Changes made to the Javascript (not shown below):
+ import ACCOUNT_SALESREPNAME_FIELD from '@salesforce/schema/Account.Sales_Representative__r.Name';

  @wire(getRecord, {
        fields: [
            ...
+           ACCOUNT_SALESREPNAME_FIELD
        ]
    }) wiredAccount({ error, data }) {
        if (error) {...}
        else if (data) {
            ...
+           this.salesrepresentative = getFieldValue(data, ACCOUNT_SALESREPNAME_FIELD);
            ...
        }
        else {} // wiredAccount

... and commented out the @wire to get the USER_NAME_FIELD

Javascript:
import {LightningElement, api, wire, track} from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
import ACCOUNT_SALESREPRESENTATIVE_FIELD from '@salesforce/schema/Account.Sales_Representative__c';
import USER_NAME_FIELD from '@salesforce/schema/User.Name';

export default class myClass extends LightningElement {
    @api c__recordId; // Get from parent Aura lightning component which is an URL button
    @api recordid;
    @api acctname = '-';
    @api salesrepresentative = '-';
    @api message = '';
    @api salesrepid;

    @wire(getRecord, {
        recordId: '$c__recordId',
        fields: [
            ACCOUNT_NAME_FIELD,
            ACCOUNT_SALESREPRESENTATIVE_FIELD,
        ]
    }) wiredAccount({ error, data }) {
        if (error) {
            this.error = error;
            console.log(error);
        }
        else if (data) {
            this.data = data;
            this.acctname = data.fields.Name.value;
            this.salesrepid = getFieldValue(data, ACCOUNT_SALESREPRESENTATIVE_FIELD);
        }
        else {
            console.log('wiredAccount: Both data and error were undefined');
        }
    } // wiredAccount

    // Get sales representative user name. When salesrepid updates, this is triggered
    @wire(getRecord, {
        recordId: '$salesrepid',
        fields: [
            USER_NAME_FIELD,
        ]
    }) wiredUser({ error, data }) {
        if (error) {
            console.log('wiredUser error: ' + error);
        }
        else if (data) {
            this.salesrepresentative = getFieldValue(data, USER_NAME_FIELD);
        }
        else {
            console.log('wiredUser: Both data and error were undefined');
        }
    };

}

HTML (removed other LWC panels)
<template>

<lightning-card title="WIRED Institution Summary" icon-name="standard:account">

                Institution Name

{acctname}

                Sales Representative

{salesrepresentative} ({salesrepid})

</lightning-card>

</template>

A: There are two parts to this problem:

*

*Refreshing wired data in the LWC module

*Triggering the refresh from an external action/event

Part 1: Refreshing wired data in the LWC module
The data retrieved by a wired service in LWC will not update automatically unless one or more of its arguments change. If arguments are unchanged during the lifecycle of the module, a wired property can be refreshed with the latest data by calling refreshApex() on it.
// ... other imports
import { refreshApex } from '@salesforce/apex';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

// Wired account property
@wire(getRecord, {
    recordId: '$c__recordId',
    fields: [
        ACCOUNT_NAME_FIELD,
        ACCOUNT_SALESREPRESENTATIVE_FIELD
    ]
}) account;

// Getters for the account field values
get accountSalesRep() {
    return getFieldValue(this.account.data, ACCOUNT_SALESREPRESENTATIVE_FIELD);
}

// A method to call to refresh the wired account
// Call this to fetch the data again
handleRefresh() {
    refreshApex(this.account);
}

Part 2: Triggering the refresh from an external event
As you mentioned in a comment that you are updating a record in a separate window to the one the LWC module exists, the module will need to listen and react to an event.
You can use empApi and Change Data Capture to publish events and subscribe to those events inside your module. Subscribe to the event and call handleRefresh() in the callback.
Side note: This might be overkill - Look at how your users interacts with the system to see if it is necessary to keep data synchronised between windows. If the scope is reduced to keeping data synchronised within a record page, you can use something like Lightning Data Service (Record Change) in your parent aura component which in turn calls @api handleRefresh() in the nested LWC module to keep the account data fresh.


text:
Q: Under which conditions is $\int_\Gamma f=0$
Let $\Gamma$ be a contour. $V\subseteq \mathbb C$ and $f:V\rightarrow
 \mathbb C$.
What are the conditions on:

*

*$\Gamma$

*$f$

*Open $U\subseteq V$

  such that $\int_\Gamma f=0$

This seems like an open mapping theorem which states that open sets get mapped to open sets.
I thought:
Let $f$ be holomorphic everywhere, let $\Gamma$ be a closed loop. $U$ to be anything. Is this correct?

A: Look for the Cauchy integral theorem and you will get your answer

A: Integral around contours are computed with the residue formula. So the sum of the residues inside the contour must be zero. Take the Laurent development at each singular point in the contour and compute it's residue.


text:
Q: display "null" when transfer value of "str1" to other class public class ServerResponce extends ListActivity {
    private ArrayList<listobj> tobj = new ArrayList<listobj>();
    **static String str1;**
     PickUpLocation pickup=new PickUpLocation();
  String pickuplocid=  pickup.locationid;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new MyTask().execute();

}

  private class MyTask extends AsyncTask<Void, Void, Void>
  {
          private ProgressDialog progressDialog;
          protected void onPreExecute() {
                  progressDialog = ProgressDialog.show(ServerResponce.this,
                                    "", "Loading. Please wait...", true);
          }
          @Override
          protected Void doInBackground(Void... arg0) {
                  try {

                URL  tURL=  new URL("http://qrrency.com/mobile/j2me/cab/CabBooking.php?userid=1&from=home&to=office&datetime=&cabservicetype=1&cabtype=1&cabfeatures=AC&locationid="+pickuplocid+"");

                  BufferedReader inn = new BufferedReader(new InputStreamReader(tURL.openStream()));
                    int p=0;

                    StringBuffer buffer1=new StringBuffer();

                    while ((p=inn.read())!=-1)
                    {
                            buffer1.append((char)p);
                            str1=str1+(char)p;

                    } Log.i("Line----saurabh trivedi-ddddd----", str1);

                   inn.close();

I make object of class and transfer the str1 value to other class ServerResponce
servresp=new ServerResponce();
String serv= servresp.str1;
Log.i("tag",serv);

serv is showing "null" why??

A: When your String is static then you dont need to create Objetc of that class.
For reference in 2nd Activity you could use.
ServerResponse.str1;

in your second Activity

A: ListActivity is not a class that's meant to be instantiated by you, it's a framework thing that should be handled by Android itself.
onCreate() is not getting called when you instantiate the class, that's Android's job, when an activity is started via an intent. So MyTask is not created nor executed.
Moreover, even if you executed MyTask in the constructor, it wouldn't work either, because with:
ServerResponce servresp=new ServerResponce();
String serv= servresp.str1;
Log.i("tag",serv);

you're just starting the task (which will take some time to be executed!) and immediately querying the result string. You have to use the onPostExecute() callback to be sure that you have a value.
(aren't you going a bit too fast?)


text:
Q: Poisson process probabilities and o notation. I am struggling with understanding a certain result. I study poisson processes, and a solution to an exercise I am doing does not make sense to me.
Let $N_1(t)$ be a Poisson($\lambda$) process and $N_2(t)$ a Poisson(3$\lambda$) process that are independent. Then
$$P(N_1(h)=1,N_2(h)=0)=(\lambda h+o(h))(1-3\lambda h+o(h))=\lambda h+o(h)$$
What I don't understand is the last equality. How to we derive that?
Thank you.

A: Expand: when $h\to 0$,
$$\begin{align}
(\lambda h+o(h))(1-3\lambda h+o(h))
&= \lambda h+o(h)-3\lambda^2h^2+o(h^2)+o(h^2) \\
&= \lambda h+o(h)
\end{align}$$
since $h^2=o(h)$.


text:
Q: How change the color of selected Textview I have lots of textview in screen. I want to change color of textview whenever user click it and color should be remained same until user click other textview.
For this i am used this slector but it isn't working like that.
    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false" android:state_selected="false" android:color="#000"/>
    <item android:state_selected="true" android:color="#12fdfd"/>
</selector>

How should i do it? any help

A: Your TextView need to implemented Checkable interface. Try to use Known Indirect Subclasses of Checkable eg. CheckedTextView or implement your own TextView.

A: Replace the TextView by CheckedTextView then your selector must be as following
   <?xml version="1.0" encoding="utf-8"?>
   <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item  android:state_checked="true"   android:color="#12fdfd"/>
     <item  android:color="#000"/>
  </selector>

use the setChecked(boolean bln) function for your CheckedTextView
 mCTxtView.setChecked(true);

You can use it as checkbox ui by setting drawable for checkedTextView
android:drawableLeft="@drawable/radio_drawable"

radio_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/radio_checked"  android:state_checked="true"/>
  <item android:drawable="@drawable/radio_unchecked" />
</selector>


text:
Q: How to control the count of resource in a ASP.net application? I am working on a ASP.net application, which basically use huge excel document to do some  calculations and finally extract the output from excel to the page. The normal excel document size could be more than 15 MB. So i am forced to put a limit  at the application that it should serve only 5 users at one point of time (To keep the memory usage under control so that other web applications run on same server will not get affected). Hence all other users has to wait in a queue to get served. The Excel used for calculation is Cached in the server and when a new request come, the application will clone the cached excel and use that for calculation.
Once the calculation is done, the used excel is disposed. (I can't reuse the excel used for other's calculation)
So my question is "How can we put a limit to the excel usage ?". This limit should be application wide (not session wide).

A: You can create a application level shared variable (either using static variable or using Application State) to keep the count of calculation in progress. Don't forget about the locking while modifying the shared state - I will personally prefer the static variable with Interlocked methods for providing thread-safety.
On the different note, I would actually design the solution differently. Because excel based calculation is resource heavy, I will move that part in different process (probably a windows service). Will probably host WCF in this process to accept calculation requests (note request submital can be done in many ways - putting a request file at some folder or inserting row into database table etc). Any kind of throttling will be put into this process. The ASP.NET application will pass the request to this service and update user about the results asynchronously.

A: If I am trying to limit access to a resource, then I usually implement the object pool pattern. This question is a great reference for it.


text:
Q: How to get the selected UIElement(Image) in a Grid instantiated at Runtime? My Grid has 2 rows and 2 columns (Total: 4 cells) created at design time. I added 4 Image controls to each cell (some Loop here: Row, Column Definition etc... Set Grid.SetRow(imageControl, gridRowCell);
                        Grid.SetColumn(imageControl, gridColumnCell);) at runtime.
Just for testing purposes, I would like to know if there is something I could use to return the specific selected UIElement in my case the Image when selected?
Summary:

*

*Each cell in the Grid has only 1 Image control instantiated at runtime.

Purpose:
My purpose here is to empty the Source of that child image when selected because soon I'll be replacing that empty image with a new one.
Please suggest me also in what event of Grid to place your suggested code. Grid doesn't have a Click or SelectionChanged event.
The reason I use Grid and dynamically add RowDefinition; ColumnDefinition because ListBox I think can't apply different item properties (i.e  displaying images with different sizes) within a bounded collection display but Grid can do RowSpan and ColumnSpan which can stretch to Rows or Columns spanned.
e.g. The user selects a layout format (4  cols & 3 rows; 5 cols & 3 rows etc...) which makes it harder to create at design time.
In short:
All I want is to display the Image collection items in different sizes and hopefully can still be done using Binding

A: If you want selection you should use a ListBox.
e.g.

*

*Create a class for your images which has a property signature like this:
Link : string
X : int
Y : int

*Set up a ListBox with bindings and an ItemsPanel that is a Grid:
<ListBox ItemsSource="{Binding ImageCollection}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Grid.Column" Value="{Binding X}"/>
            <Setter Property="Grid.Row" Value="{Binding Y}"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
            </Grid>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding Link}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

You now can select the images and the ListBox.SelectedItem can be casted to your class and the Link can be changed.
You can also wrap the image in the DataTemplate in a Button if you want it clickable.

A: There is no selection of items in a Grid so if you want to get the selected item there are three ways:

*

*Replace the Grid by a ListBox and use the SelectedItem(s) property

*Put the Images in clickable/selectable controls such as buttons so you can use the click event or monitor the IsChecked property.

*Use the MouseDown/Up events of the Image control.


text:
Q: Dlls missing for Win Server 2k8 core I am planning to port an application(rather make it run) on win 2k8 core. But it seems that a lot of dlls are missing on core. I understand that this is a stripped down version of Windows server, but then how is one supposed to develop applications or rather make existing applications run seamlessly on server core.
While running my app(works fine on rest of the platforms including Win 7), I've found that the following dlls are missing
oledlg.dll
msjetoledb40.dll
dhcpsapi.dll
dsauth.dll
just to name a few. I'm sure i might come across some more.
For now, of what I could think of, the only quick way to fix this is to ship the dlls with my app. Which I guess not everyone would agree with. It's not the best solution and comes with redistro licensing hassles.
Any thoughts?
Thanks.
Samrat Patil.

A: The main point of the default "core only" install of Windows Server 2008 is that is includes almost nothing - it is a bare system into which you install the few services and components that you need and nothing else (like the Debian base install and similar, if you are more familiar with Linux). Those DLLs are likely not "missing" - they are just part of components that you have not installed on the machine yet.
You should find out which components and services provide the libraries and other facilities your app requites and list them as pre-install dependencies for your application.
You should not ship system or 3rd party DLLs yourself as you suggest (unless the libraries come with relevant instructions, or a redistributable install set or mergable MSI) as you risk significant library versioning issues on the destination system. Also, you won't need just those DLLs that are referenced directly - those libraries will probably depend upon other that are also not present and may require other things (such as a mountain of registry settings perhaps) to be present in order for them to work correctly - getting all that together yourself would not be a pleasant job.
Edit: You might find more help finding which components your project is depending upon (that the Core install is lacking by default) over on StackOverflow, as it is probably more a developer question than an admin one.

A: Also note that while developing for Server Core there are guidelines to follow to make it work. You can't base your work on the standard .Net framework. See microsoft.com for more info on the subject (there are developer guidelines on MSDN).


text:
Q: How to get a download option of dynamic table in Angular using Django Database ( each time we will have different tables in Database) I have tables in Django Data Base with name TBL_Result_1_1, TBL_Result_1_2 etc.
Image of All tables in Django Backend
I am creating a dashboard in angular frontend, our model will generate tables in Django database with different tables name, each time we run the model . I want to get all tables in dashboard with a download option so a user can download all these tables with click of button. Problem is these tables are not static we will have different number of tables each time and different number of parameters. I know how to get a static table in frontend but not sure with dynamic table with dynamic parameters. Their has to be specific way to this solution.
Problem i don't want to add model in model.py each time
I have used models.py for static tables in django, but these tables are dynamic. Will not able to add models.py each time for each table.

A: You need to use a function in your views.py to get the table dynamically. After that give this table name to a URL that you created before for the download link. This function will run the download URL.
visit here to see download url
If you would ask your question more specific stack overflow could help you more.


text:
Q: prerender express-handlebars templates to include them in other templates this might not be a question, but an answer I found by myself that I want to share.
I had a dashboard app working with express-handlebars and wanted to put the code of each module in other templates to include them dynamically.
I found a solution by recursively rendering a list of modules while emptying a list of module paths and rendering the html to save into the data object there all templates get their data from.
app.get('/dashboard', function(req, res) {
    var mainTemplate = 'dashboard';

    var modules = [
        {
            name : 'FIVE_MONTH_OVERVIEW',
            path : 'modules/fivemonth'
        },
        {
            name : 'LAST_CHANGES',
            path : 'modules/lastchanges'
        }
    ];

    var data = {};

    recursiveRender(res, req, modules, data, mainTemplate);
});

And the function (req is currently unused, but might be used to read GET/POST parameters and cookies):
function recursiveRender(res, req, list, data, final, lastHtml){
    list = list || [];
    data = data || {};
    if(list.length === 0){
        if(final){
            res.render(final, data);
        }
        else if(lastHtml){
            res.send(lastHtml);
        }
        else{
            res.status(409).send('Conflict.');
        }
    }
    else{
        var item = list[0];
        list.splice(0, 1);
        data.modules = data.modules || {};
        data.modules[item.name] = item;
        res.render(item.path, data, function(err, html){
            data.modules[item.name].html = html;
            recursiveRender(res, req, list, data, final, html);
        });
    }
}

It might be used to render static html directly:
 recursiveRender(res, null, null, null, null, "<html>...</html>");

Or render a single template with data:
 recursiveRender(res, null, null, data, "dashboard");

or
 recursiveRender(res, null, [{name: "templatename", path: "templatename"}], data);

If anyone says 'that is possible much easier.' - tell me, i'd love to know! :)


text:
Q: In which cases is it acceptable to put imports not on the top in Python? I need to support  Python code, which was written by another person and it contains imports, that are placed not at the top of the module. And I'm a bit afraid to break something, as project is quite complex.
So when it can be good to use imports not on the top of the file?

A: If you have a python program that has different paths, and only one of the paths use a specific module, you can import the module in that specific path. So you won't be importing many module you won't use.


text:
Q: java.lang.ClassCastException: cannot assign instance of java.util.HashMap I am running SparkNLP dependency_typed_conllu class. I got error below. Previously code was working. Any clue on which direction go?
dependency_typed_conllu download started this may take some time.
Approximate size to download 2.4 MB
[ / ]
An error occurred while calling z:com.johnsnowlabs.nlp.pretrained.PythonResourceDownloader.downloadModel.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 17.0 failed 1 times, most recent failure: Lost task 2.0 in stage 17.0 (TID 55, DESKTOP-CI8T2HB, executor driver): java.lang.ClassCastException: cannot assign instance of java.util.HashMap to field com.johnsnowlabs.nlp.annotators.parser.typdep.util.Dictionary.map of type gnu.trove.map.hash.TObjectIntHashMap in instance of com.johnsnowlabs.nlp.annotators.parser.typdep.util.Dictionary
    at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2287)

at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassCastException: cannot assign instance of java.util.HashMap to field com.johnsnowlabs.nlp.annotators.parser.typdep.util.Dictionary.map of type gnu.trove.map.hash.TObjectIntHashMap in instance of com.johnsnowlabs.nlp.annotators.parser.typdep.util.Dictionary


text:
Q: getting error while trying to get "Grade" for StudentId=1 I have below entities and database context class,
public class Grade
{
    public int Id { get; set; }
    public string GradeName { get; set; }

    public virtual ICollection<Student> Students { get; set; } = new HashSet<Student>();
}

public class Student
{
    public int Id { get; set; }
    public string StudentName { get; set; }
}

public class SchoolContext : DbContext
{
    public DbSet<Grade> Grades { get; set; }
    public DbSet<Student> Students { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=SchoolDB;Trusted_Connection=True;");
    }
}

Getting below error while executing below code, whats need to be done here. Thanks!
I'm looking for solution without adding Grade property in Student class

System.InvalidOperationException: 'The Include property lambda expression 'x => {from Student c in x.Students where ([c].Id == __studentId_0) select [c]}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.'

static void Main(string[] args)
    {
        var studentId = 1;

        var context = new SchoolContext();
        var data = context.Grades.Include(x => x.Students.Where(c => c.Id == studentId)).SingleOrDefault();
    }

A:
I'm looking for solution without adding Grade property in Student class

So you want to be able to get the Grade for a Student, but don't want to add Grade navigation property to Student and let the EF Core handle naturally that for you? In other words, losing one of the biggest ORM benefits and start seeking for SQL-ish solutions for a simple requests which ORM can handle with a simple property accessor?
There are ways to do what you want, but I would suggest first asking yourself if you really need that.
Anyway, one possible solution is to use the collection navigation property with Any as filter:
var studentGrade = context.Grades
    .FirstOrDefault(grade => grade.Students.Any(student => student.Id == studentId));

Another is to use the LINQ equivalent of the SQL query:
var studentGrade = (
    from grade in context.Grades
    from student in grade.Students
    where student.Id == studentId
    select grade).FirstOrDefault();

A: You cannot include navigation property by condition. Include can only contains lambda to navigation property without any conditions. To solve your problem you should add navigation property Grade to class Student and select from Students including Grade.
public class Student
{
    public int Id { get; set; }
    public string StudentName { get; set; }
    public Grade StudentGrade { get; set; }
}

…
var data = context.Students.Include(x => x.Grade).Where(c => c.Id == studentId).SingleOrDefault();


text:
Q: Azure Service Bus and Xamarin.Android MessageHandler I am trying to use the Microsoft.Azure.ServiceBus on a Xamarin.Android mobile application.  I would like to subscribe the device to a specific queue and have it continually monitor that queue for any messages.
I was able to find an article to send a message to a queue, but I am having the hardest time finding a way to subscribe to the queue.  Using the following code doesn't seem to be working.
QueueClient queueClient = new QueueClient(connectionString, requestQueueName);
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            MaxConcurrentCalls = 1,
            AutoComplete = false
        };

        queueClient.RegisterMessageHandler(ProcessMessageAsync, messageHandlerOptions);

Has anyone else had a similar issue?
Thanks Jlimited

A: You may want to try setting the TransportType to AmqpWebSockets.  Android can sometimes have issues when the default TCP transport is used.  Since you're not registering an error handler, you wouldn't be observing any exceptions from connection failures.
The easiest way to integrate this into your current snippet would be using the ServiceBusConnectionStringBuilder:
var builder = new ServiceBusConnectionStringBuilder(connectionString);
builder.TransportType = TransportType.AmqpWebSockets;

var queueClient = new QueueClient(builder.ToString(), requestQueueName);

If this is new development with no existing investment in the legacy Service Bus library, you may want to consider using the current generation, Azure.Messaging.ServiceBus.  It's ServiceBusProcessor offers the push-based model that you're using with support for specifying your message handling options and also registering an error handler, which the legacy client does not.


text:
Q: How to use Provider with Base Class in Flutter/Dart I have base and derived classes like this:
abstract class A extends ChangeNotifier{....}
class B extends A{....}

I am using provider like this:
ChangeNotifierProvider<B>(create: (context) => B())

and accessing using both A and B(depending on situation) like this:
Provider.of<A>(context) //This does not work. Why?
Provider.of<B>(context) //This works.

How do I correctly use base class with Provider.of i.e. Provider.of<A>(context)?
Edit: The ChangeNotifierProvider is only for B. I do not have a provider for A. But, I want to access using A as A is the base class of B.

A: You'll have to do something like this:
final b = B();
ChangeNotifierProvider<A>.value(value: b)
ChangeNotifierProvider<B>.value(value: b)

Then you can access your B class by using either:
Provider.of<A>(context) //This now works.
Provider.of<B>(context) //This works.


text:
Q: yacc reduce/reduce conflict I have the following grammar:

*

*x: (z) o

*x: n

*z: x

*z: z x

*o: +|-|/|*

*n: [0..9]

the parser stack currently is : "(z(zx"  the next tokens are )+)*
Which of the rules 3 or 4 is going the parser to reduce and why?
Thank you

A: The answer is: rule 4.
Intuitively, this is because rules 3 and rules 4 are a left-associative pair that converts X's to Z in a greedy way.
Another reason is that if we reduce rule 3, we end up with Z Z on the parsing stack, which is not a possible sentential form. The grammar does not generate partial derivations that have Z Z.


text:
Q: C# - ShowDialog(this) memory leak I have sample code to Show new form dialog:
private void button1_Click(object sender, EventArgs e)
{
    (new Form2()).ShowDialog(this);
    GC.Collect();
}

If the form has buttons, panels labels etc. then Dispose method of this form2 is executed but if I add toolStrip then the method Dispose isn't executed. Why Dispose is executed in these some cases ?
I readed if form is showing by ShowDialog then I should execute Dispose method, but why it works sometimes without it ?
Edit:
Collect method can be added after ShowDialog. This method is only for tests and is executed multiple times.
To check if method Dispose was executed I added breakpoint (in debug mode). Of course Dispose of example with ToolStrip is executed when program is ending.
OK I know how to proper implemented it, for me was intrested why GC can't clean up if on the form is toolStrip ?
The most simple code to show it is:
Example 1 - result - 100,
Example 2 - result > 0 (GC can clean up),
Example 3 - always 0.
Why example 2 and 3 are that different ?
private class Form2 : Form
    {
        public static int disposed = 0;
        byte[] data;
        private System.Windows.Forms.ToolStrip toolStrip11;
        public Form2(bool addToolStrip)
        {
            data = new byte[100000];
            this.Shown += (sender, e) => { this.Close(); };
            this.Controls.Add(new Button());

            if (addToolStrip)
            {
                this.toolStrip11 = new System.Windows.Forms.ToolStrip();
                this.Controls.Add(this.toolStrip11);
            }
        }

        protected override void Dispose(bool disposing)
        {
            ++disposed;
            base.Dispose(disposing);
        }
    }
    private void ShowResult()
    {
        GC.Collect(); GC.Collect();
        GC.WaitForFullGCComplete();
        MessageBox.Show(Form2.disposed.ToString());
        Form2.disposed = 0;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //proper
        for (int i = 0; i < 100; ++i)
        {
            using(Form2 f = new Form2(true))
            {
                f.ShowDialog();
            }
        }
        ShowResult();
        //ok GC can clean - why yes ?
        for (int i = 0; i < 100; ++i)
        {
            Form2 f = new Form2(false);
            f.ShowDialog();
        }
        ShowResult();
        //GC can't clean - why not ?
        for (int i = 0; i < 100;a ++i)
        {
            Form2 f = new Form2(true);
            f.ShowDialog();
        }
        ShowResult();
    }

A: Your code doesn't make sense - you're forcing a garbage collection cycle before making a call that you claim leaks memory.
You should only implement Dispose to get rid of unmanaged resources. For managed resources it simply doesn't make sense to try to beat the garbage collector in any common use case. Also, I'm not sure how you even think you're "leaking memory" since you cannot possibly predict or know when the GC has done its job properly - strictly speaking a .NET program only has a real memory leak if the GC refuses to clean it up properly. Since that is information undisclosed to the developer - even an explicit cleanup can, at its own discretion, elect not to collect all potential garbage - your claim is by definition unverifiable.

A: Many objects that are disposable also have a finalizer.  When an object would normally be cleaned up by the GC it will first check if it has a finalizer that hasn't been run.  If it hasn't, it goes into a queue for its finalizers to be run, and is then actually eligible for garbage collection.
Because of this mechanism it's possible for some disposable objects to have their resources cleaned up even if they are not explicitly disposed.
That said, this is an unreliable mechanism.  You don't know when an object will be collected once it is eligible for collection, and the state that the object is in when the finalizer is run can result in unusual and undefined interactions with "itself".
You should avoid relying on a finalizer whenever possible and instead explicitly dispose of such disposable resources.


text:
Q: What redirect URL to use when logging in with GitHUB with OAuth2? I'm new in ios sdk and English. Therefore, sorry for my Eng.
I try to do authentication through github using OAuthSwift.
In the registration of the application (https://github.com/settings/apps), there is need a redirect URL. In the tutorial from raywenderlich.com was an example, they did authorization through Google. They wrote a unique domain in this line that does not work: com.raywenderlich.Incognito. And in Info.plist, we added a Scheme URL with com.raywenderlich.Incognito, so that (as I understood it) when we go to this address after authentication, we've got into our application. But if you try to add in the application settings (https://github.com/settings/apps) the Redirect URL: something like com.raywenderlich.Incognito, will generate an error, because github wants the URL to have to be valid. If we put the Valid URL there, then when we will be redirected to this address, we will simply go to it and will not return to the application.
I would be grateful for any help.
Sorry for my English.

A: Redirect url in OAuth is the url that the authentication provider navigates to when authentication is successful.

*

*For mobile apps it is the link that launches the app (a sort of deep linking)

*For websites it is the website home screen


text:
Q: SQL Server 2012 Express Silent mode Programmatically I am doing a silent mode SQL Server installation by running my code, This is my code:
string fileName, commandLine = "";

fileName = string.Format(@"{0}\SQLServer\sql64\setup.exe", setupFolder);
commandLine = string.Format(@"PCUSOURCE={0}\SQLServer\sql64 /MEDIALAYOUT=Core /CONFIGURATIONFILE={0}\SQLServer\ConfigurationFile64.ini /ACTION=Install", setupFolder);
Process.Start(fileName, commandLine);

It runs fine and every file is extracted from the installer, after that it pops up an error message

As you notice, I added /ACTION in the command line

/ACTION=Install

Also I checked the configuration file and I found it.
Please help me .. this error killing me :(
Thanks in advance


text:
Q: O que é prolyfill? Já sabemos o que é um polyfill (O que é Polyfill?), mas o que é um prolyfill? Existe alguma relação dele com o próprio polyfill, dado que os nomes são tão semelhantes?
Vi o termo por acaso neste comentário e vi que até existem algumas referências a ele na internet, mas é pouco utilizado. O termo é pouco utilizado ou é sua implementação que pouco comum?

A: Parece haver uma "informação canônica" simples sobre ela por isso vou responder até porque sei que é só para termos aqui um conteúdo útil.
É basicamente o mesmo que o polyfill, mas ao contrário. Enquanto o termo já consagrado se encarrega de fornecer implementações que tornem seu código compatível com mecanismos antigos que ainda não possuem certa capacidade, o prolyfill faz o mesmo com mecanismos que ainda não existem e permitem você testar algo que poderá existir. Isto é útil para demonstrar como seria se fosse implementado para servir de base como proposta de novidade em tecnologia web ou para testar algo que já foi proposto.
Acho o termo desnecessário e até mal pensado, tanto que agora estão chamando de polyfill especulativo, portanto ele não deixa de ser um polyfill e no fundo é a mesma coisa, usa-se do mesmo jeito, tem as mesmas vantagens, a diferença é apenas que ele pode se tornar inútil facilmente porque pode não ser implementado desta forma. Ou até mesmo nunca ser implementado, portanto eles possuem apenas objetivos diferentes. Sua única utilidade é dar uma chance das pessoas testarem uma possível forma como funcionaria aquilo, é útil mais para os implementadores do que para usuários normais de tecnologias, eu não me preocuparia muito com ela, a não ser por curiosidade ou se está entrando no mundo de implementadores dessas tecnologias, especialmente web.
Exemplo. Pelas minhas pesquisas o termo parece ser usado quase exclusivamente aí :D


text:
Q: How to obtain the best fit values of `a` and `b` here is set of data.
{{-6.28319, 3.06707}, {-6.22035, 2.96473}, {-6.15752,
  3.18398}, {-6.09469, 3.22623}, {-6.03186, 2.58625}, {-5.96903,
  2.4081}, {-5.90619, 2.30268}, {-5.84336, 1.75846}, {-5.78053,
  1.53609}, {-5.7177, 1.67376}, {-5.65487, 1.08757}, {-5.59203,
  0.887877}, {-5.5292, 0.764236}, {-5.46637, 0.782493}, {-5.40354,
  0.666159}, {-5.34071, 0.469877}, {-5.27788, 0.353436}, {-5.21504,
  0.32059}, {-5.15221, 0.282072}, {-5.08938, 0.224285}, {-5.02655,
  0.198952}, {-4.96372, 0.180834}, {-4.90088, 0.165968}, {-4.83805,
  0.172037}, {-4.77522, 0.167065}, {-4.71239, 0.150082}, {-4.64956,
  0.153673}, {-4.58673, 0.186473}, {-4.52389, 0.166376}, {-4.46106,
  0.19644}, {-4.39823, 0.213121}, {-4.3354, 0.234954}, {-4.27257,
  0.295397}, {-4.20973, 0.329096}, {-4.1469, 0.354295}, {-4.08407,
  0.427717}, {-4.02124, 0.508824}, {-3.95841, 0.684087}, {-3.89557,
  0.737755}, {-3.83274, 0.970972}, {-3.76991, 1.06964}, {-3.70708,
  1.26858}, {-3.64425, 1.57755}, {-3.58142, 1.89527}, {-3.51858,
  2.00068}, {-3.45575, 2.73965}, {-3.39292, 2.58552}, {-3.33009,
  3.53549}, {-3.26726, 2.9681}, {-3.20442, 3.20238}, {-3.14159,
  3.00147}, {-3.07876, 2.96773}, {-3.01593, 2.88376}, {-2.9531,
  3.52059}, {-2.89027, 2.60561}, {-2.82743, 2.43369}, {-2.7646,
  2.09201}, {-2.70177, 1.75783}, {-2.63894, 1.51186}, {-2.57611,
  1.2753}, {-2.51327, 1.06948}, {-2.45044, 0.946446}, {-2.38761,
  0.735844}, {-2.32478, 0.653638}, {-2.26195, 0.672593}, {-2.19911,
  0.435117}, {-2.13628, 0.374499}, {-2.07345, 0.388105}, {-2.01062,
  0.307276}, {-1.94779, 0.240313}, {-1.88496, 0.198942}, {-1.82212,
  0.237058}, {-1.75929, 0.168411}, {-1.69646, 0.205188}, {-1.63363,
  0.196649}, {-1.5708, 0.178861}, {-1.50796, 0.151156}, {-1.44513,
  0.156568}, {-1.3823, 0.171041}, {-1.31947, 0.180429}, {-1.25664,
  0.209893}, {-1.19381, 0.250246}, {-1.13097, 0.257486}, {-1.06814,
  0.387131}, {-1.00531, 0.356676}, {-0.942478, 0.421306}, {-0.879646,
  0.505373}, {-0.816814, 0.618249}, {-0.753982, 0.742413}, {-0.69115,
  0.96845}, {-0.628319, 1.09753}, {-0.565487, 1.29364}, {-0.502655,
  1.54678}, {-0.439823, 1.74159}, {-0.376991, 2.03285}, {-0.314159,
  2.30415}, {-0.251327, 2.49323}, {-0.188496, 2.70047}, {-0.125664,
  2.92666}, {-0.0628319, 3.147}, {8.88178*10^-16,
  3.00009}, {0.0628319, 2.96506}, {0.125664, 3.69675}, {0.188496,
  2.73919}, {0.251327, 2.59297}, {0.314159, 2.28973}, {0.376991,
  2.37359}, {0.439823, 1.77724}, {0.502655, 1.49895}, {0.565487,
  1.27447}, {0.628319, 1.25117}, {0.69115, 0.88666}, {0.753982,
  0.907868}, {0.816814, 0.652895}, {0.879646, 0.512775}, {0.942478,
  0.459046}, {1.00531, 0.362171}, {1.06814, 0.315906}, {1.13097,
  0.337593}, {1.19381, 0.225286}, {1.25664, 0.200794}, {1.31947,
  0.18601}, {1.3823, 0.176216}, {1.44513, 0.172146}, {1.50796,
  0.15203}, {1.5708, 0.152544}, {1.63363, 0.162791}, {1.69646,
  0.158226}, {1.75929, 0.19074}, {1.82212, 0.179813}, {1.88496,
  0.231289}, {1.94779, 0.282846}, {2.01062, 0.273322}, {2.07345,
  0.347488}, {2.13628, 0.464175}, {2.19911, 0.517131}, {2.26195,
  0.558927}, {2.32478, 0.610471}, {2.38761, 0.795847}, {2.45044,
  0.890453}, {2.51327, 1.07052}, {2.57611, 1.37719}, {2.63894,
  1.63123}, {2.70177, 2.31678}, {2.7646, 2.58171}, {2.82743,
  2.25627}, {2.89027, 2.49236}, {2.9531, 2.73203}, {3.01593,
  3.18419}, {3.07876, 3.41248}, {3.14159, 3.10005}, {3.20442,
  2.96473}, {3.26726, 3.63233}, {3.33009, 3.05719}, {3.39292,
  2.74941}, {3.45575, 2.25327}, {3.51858, 2.02879}, {3.58142,
  2.24308}, {3.64425, 1.66423}, {3.70708, 1.27166}, {3.76991,
  1.1742}, {3.83274, 1.02115}, {3.89557, 0.735588}, {3.95841,
  0.797138}, {4.02124, 0.517385}, {4.08407, 0.42141}, {4.1469,
  0.36229}, {4.20973, 0.392941}, {4.27257, 0.265514}, {4.3354,
  0.291255}, {4.39823, 0.201606}, {4.46106, 0.19618}, {4.52389,
  0.190342}, {4.58673, 0.156961}, {4.64956, 0.185436}, {4.71239,
  0.162217}, {4.77522, 0.17993}, {4.83805, 0.161685}, {4.90088,
  0.166415}, {4.96372, 0.189599}, {5.02655, 0.205805}, {5.08938,
  0.234122}, {5.15221, 0.268397}, {5.21504, 0.303497}, {5.27788,
  0.412239}, {5.34071, 0.477834}, {5.40354, 0.519274}, {5.46637,
  0.618945}, {5.5292, 0.748803}, {5.59203, 0.95291}, {5.65487,
  1.06411}, {5.7177, 1.29203}, {5.78053, 1.88471}, {5.84336,
  1.89622}, {5.90619, 2.19759}, {5.96903, 2.55314}, {6.03186,
  2.49536}, {6.09469, 2.78078}, {6.15752, 3.33169}, {6.22035,
  2.96572}, {6.28319, 3.03594}}

this is my code so far.
 datanlm = Import["datanonlinear.txt", "Data"];
    lpt = ListPlot[datanlm]
    NonLdataFit =
     NonlinearModelFit[datanlm, a*Exp[(-b*Sin^2[x]], {a, b}, x]

i got the error. maybe i supposed put the range of a and b ? i tried
NonLdataFit = NonlinearModelFit[datanlm, a*Exp[(-b*Sin^2[x]],
  {{a, -6}, {b, 5}}, x] but return error too.

with the best fit a and b values, i want to plot y=a*Exp[-b*(Sin^2)[x]] and overlap it on top of the original data points (picture above) to show that both fit nicely to each other.
all help is appreciated. thank you.

A: There is a syntax error. NonlinearModelFit works in this set without setting initial values. The latter remains important in general, however.
f[a_, b_, x_] := a Exp[-b Sin[x]^2]
nlm = NonlinearModelFit[data, f[a, b, x], {a, b}, x]
Show[ListPlot[data], Plot[nlm[x], {x, -2 Pi, 2 Pi}]]
nlm["BestFitParameters"]

where data is the first list in question.


text:
Q: How can I select tables with more than or less than a certain number of rows? I want to identify all tables with more than 6 rows, as well as all tables with 6 or fewer rows.
About the best I can come up with is to loop over the rows for each table and count them, but there must be a more elegant solution. What can I do other than looping and counting to find these tables?

A: You can use jQuery.filter for this:
$("table").filter(function(){
    return $(this).find("tr").length > 6;
});

A: I would use the .filter() method to filter out only the tables that match your criteria. In your case you could select all rows within the table and check the length. Something like this:
// Get tables with more than six rows
$("table").filter(function (){
   return $("tr", this).length > 6;
});

Working demo

A: You're looking for .filter()
$('table').filter(function(index) {
    return $('tr', this).length > 6;
});

A: Here's a technique that uses the :gt (greater-than) selector to count rows for you:
$bigtable = $('table').find('tr:gt(5)').closest('table'); // :gt is zero-indexed

After that, you can use .not() to get all the tables with six rows or less:
$smtable = $('table').not($bigtable);

http://jsfiddle.net/mblase75/44YEf/


text:
Q: The effect of withWatermark without aggregation I wonder what is the effect of .withWatermark() if there is a stream without any aggregation, basically one to one mapping to the output sink? Does date get dropped, or withWarmark time window is ignored in such case?
Thanks for clarification.


text:
Q: How to serialize two nested django tables? iI've updated the post and pasted the complete code. can any fix the code for me. actually i want to POST data with album name and multiple images adn serialize the both and at POST request I want the whole submitted data. means.
{
name : My favourite songs list
media: [
{
media : filename1,
media : filename2
}
]
}
#views.py
@api_view(['POST'])
def addAlbum(request):
if request.method == 'POST':
    serializer = AlbumSerializer(data=request.data)
    albums = request.data.pop('media')
    if albums:
        name = Album.objects.create(name=request.data['name'])
        if serializer.is_valid():
            for file in albums:
                AlbumImages.objects.create(media = file, album = name)
            serializer.save()
            return Response(serializer.data, status.HTTP_201_CREATED)
        return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
    return Response("Please upload the files", status.HTTP_400_BAD_REQUEST)

return Response("Not found", status.HTTP_400_BAD_REQUEST)

#serializers.py
class AlbumImagesSerializer(serializers.ModelSerializer):

class Meta:
    model = AlbumImages
    fields = "__all__"

class AlbumSerializer(serializers.ModelSerializer):
albumimages = AlbumImagesSerializer(many=True, read_only=True)

class Meta:
    model = Album
    fields = "__all__"

#models.py
class Album(models.Model):
name = models.CharField(max_length=30, null=False, blank=False)
def __str__(self):
    return self.name

class AlbumImages(models.Model):
album = models.ForeignKey(Album, related_name='albumimages', on_delete=models.CASCADE)
media = models.ImageField(upload_to='album/images')

def __str__(self) -> str:
    return f'Files of ' + self.album.name

Album is being generated, files are being associated with album table, but the question is how i'll serialize both tables to show response on post request. waiting for help.

A: I adjusted your code a little bit but it wasn´t tested.
If you don´t want to adjusted the album-ForeignKey field you must change the behavoiur of saving instead of using .objects.create(). It should work.
You wrote a lot of validations. Your serializer can do that. You can use extra_kwargs = {'media': {'required': True} at your AlbumImage-serialzer for example. If you need more explenation don´t hasitate to ask.
   album = Album(**validated_data)`
   album.albumimages = albumimages_set
   album.save()

#views.py
class AlbumView(APIView):
    def post(self, request, *args, **kwargs):
        resp = Response()
        serializer = AlbumSerializer(data=request.data)
        if serializer.is_valid():
            resp.data = serializer.save()
        else:
            resp.status_code = HTTP_400_BAD_REQUEST
            resp.data = serializer.errors
        return resp

#serializers.py
class AlbumImagesSerializer(serializers.ModelSerializer):

    class Meta:
        model = AlbumImages
        fields = "__all__"

class AlbumSerializer(serializers.ModelSerializer):
    albumimages = AlbumImagesSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = "__all__"

    def create(self, validated_data):
        albumimages = validated_data.pop('albumimages')
        albumimages_set = [AlbumImages.objects.create(**element) for element in albumimages ]

        album = Album.objects.create(**validated_data)
        album.albumimages.set(albumimages_set)
        album.save()

        return album

#models.py
class Album(models.Model):
    name = models.CharField(max_length=30, null=False, blank=False)
    def __str__(self):
        return self.name

class AlbumImages(models.Model):
    album = models.ForeignKey(Album, related_name='albumimages', blank=True, null=True, on_delete=models.CASCADE)
    media = models.ImageField(upload_to='album/images')

    def __str__(self) -> str:
        return f'Files of ' + self.album.name


text:
Q: Primary Key issue on iOS8 implementation of IndexedDb The issue is when you have two different object stores in the same indexeddb, primary key values appear to be "shared" across all stores.
<body>
    <script type="text/javascript">
        //prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange

if (!window.indexedDB) {
    window.alert("Your browser doesn't support a stable version of IndexedDB.")
}

var db;
var request = window.indexedDB.open("newDatabase", 4);

request.onerror = function(event) {
  console.log("error: ");
};

request.onsuccess = function(event) {
  db = request.result;
  console.log("success: "+ db);
};

request.onupgradeneeded = function(event) {
        var db = event.target.result;
        var objectStore = db.createObjectStore("customers", {keyPath: "arseid"});
    var objectStore = db.createObjectStore("test", {keyPath: "id"});
}

function add1() {
        var x = new Date();
    var h1 = x.getHours();
    var m1 = x.getMinutes();
    var s1 = x.getSeconds();
    console.log('starting insert on ' +  h1 + ':' + m1 + ':' + s1);

    var tx = db.transaction(["customers"], "readwrite");
    for (var i = 0; i < 1000; i++) {
        var request = tx.objectStore("customers")
                .put({ arseid: i, name: "Jonathan Smith", email: "jonathan.smith@anemailaddress.com", favourite: "chocolate cake", pet: "rudolph the red nose reindeer", address: "999 letsbe avenue, townton, countyshire" });
    }

    tx.oncomplete = function (e) {
            // Re-render all the todo's
            var x2 = new Date();
            var h2 = x2.getHours();
            var m2 = x2.getMinutes();
            var s2 = x2.getSeconds();
               console.log('transaction complete ' + h2 + ':' + m2 + ':' + s2);
        }
}

function add2() {
    //tx 2
    var tx2 = db.transaction(["test"], "readwrite");
    for (var i = 0; i < 1000; i++) {
        var request2 = tx2.objectStore("test")
                .put({ id: i, name: "Robwin Mwengway", email: "jonathan.smith@anemailaddress.com", favourite: "chocolate cake", pet: "rudolph the red nose reindeer", address: "999 letsbe avenue, townton, countyshire" });
    }

    tx2.oncomplete = function (e) {
            var x3 = new Date();
            var h3 = x3.getHours();
            var m3 = x3.getMinutes();
            var s3 = x3.getSeconds();
               console.log('transaction complete ' + h3 + ':' + m3 + ':' + s3);
        }
}

    </script>
<button onclick="add1()">Add1 data to indexedDb</button>
<button onclick="add2()">Add2 data to indexedDb</button>
</body>

(Fiddle:  http://jsfiddle.net/jonnyknowsbest/4pdp8vxe/)
In iOS8, if you run up the fiddle and click "Add1 data to IndexedDb", then 1000 entries get added to the "customers" table. If you then click "Add2 data to IndexedDb", then 1000 entries get added to the "suppliers" table, but the 1000 from the "customers" is removed.
Has anyone else come across this? Is this part of the IndexedDb specification? Chrome does not seem to have this problem.
EDIT: Found this W3 Org IndexedDB Recommendation: "There can never be multiple records in a given object store with the same key." Apple seem to have applied this at the database level.

A: I can confirm that iOS8 is definitely buggy here. I tried a few workarounds, but the best I can suggest is a primary key that combines some unique string, like the name of the objectStore, with a number. So for example, given two objectStores called people and notes, I'd store data with keys like so:
people/X
notes/X
You can set X manually, or, use the .count() method on the objectStore to find the count and add one. Here is an example:
//Define a person
var person = {
    name:"Ray",
    created:new Date().toString(),
}

//Perform the add
db.transaction(["people"],"readwrite").objectStore("people").count().onsuccess = function(event) {
    var total = event.target.result;
    console.log(total);
    person.id = "person/" + (total+1);

    var request = db.transaction(["people"],"readwrite").objectStore("people").add(person);

    request.onerror = function(e) {
        console.log("Error",e.target.error.name);
        //some type of error handler
    }

    request.onsuccess = function(e) {
        console.log("Woot! Did it");
    }

}

Note that I specified keyPath of "id" for this OS.

A: I had a similar problem however my first insert to the objectstore was a small array with just username and email and the second objectstore was very large with several nested arrays of data.
My insert method below would call back success on the all items however only the second object store would be written to the db correctly.
When I tried reversing the order I was writing to the database (writing the large objectstore items first and the username/email second) both objectstores were written correctly however the the primary keys were shared between the two objects stores.
Pilots Primary Key: 1,2,3,4,5
AC Primary Key: 6,7,8...
function insert_GroupRecord(Record, Store){
    //update individual sync record
    var trans = dbGroup.transaction([Store],"readwrite");
    var store = trans.objectStore(Store);
    var request = store.put(Record);
    request.onsuccess = function(e){
        IOS_postMessage({Message:"SyncStatus", status:"Group_Insert "+Store});
    };
    request.onerror = function(e){
        GroupSyncERROR = true;
        //IOS_postMessage({Message:"SyncStatus", status:"GroupSyncFail "+Store});
    };

    request.onupgradeneeded = function(evt){
        var objectStore = evt.currentTarget.result.createObjectStore("AC",{ keyPath: "id", autoIncrement: true });
        objectStore.createIndex("ident", "ident", { unique: true });
        var objectStore2 = evt.currentTarget.result.createObjectStore("Pilots",{ keyPath: "id", autoIncrement: true });
        objectStore2.createIndex("chatname", "chatname", { unique: true });
        console.log("KFM_Group Upgrade Completed");

    };
}


text:
Q: Can someone explain the dependence of coupling coefficient to inductance value to me? It seems counter intuitive According to the formula \$K=M/\sqrt{L_1 L_2}\$, it seems that k is inversely proportional to the inductance values of the two coils. However, it seems to me that a coupling between two 2uH inductor should be weaker than say between a 2uH and a 2mH inductor. I also came across formulae like the following in which there seems to be no dependence on inductance value at all. Another paper also stated that coefficient of coupling is independent of number of turns. All of these conflicting things are extremely confusing to me. Can someone please clear this up?

A:
However, it seems to me that a coupling between two 2uH inductor should be weaker than say between a 2uH and a 2mH inductor.

The coupling is determined by the physical construction of the transformer -- in particular its core -- and reflects the ratio of the common and stray magnetic fluxes. Specifically, \$K\$ is the fraction of coupled magnetic flux and \$1-K\$ is the fraction of uncoupled magnetic flux.
This video is a good overview of the two different ways transformers are modeled:
Mutual inductance versus transformer: the power electronics perspective
https://www.youtube.com/watch?v=qLoXOlrqZCU
See slide #4 at time 1:39 for a definition of \$K\$ in terms of the common and stray magnetic fluxes.
See the next couple slides for how \$M\$ is used in simulation software to model a transformer. Basically, \$M\$ is used as a coefficient for current-controlled voltage sources in the transformer simulation.
Another good video is this one which derives the modelling of a transformer from first principles:
Demystifying the meaning of leakage inductance of transformers and coupled inductors
https://www.youtube.com/watch?v=TUfaN40T1Yg


text:
Q: Verify my proof of the irrationality of $\sqrt{6}$. Here's my proof for the irrationality of $\sqrt{6}$:
Proof:
Let $\sqrt{6}$ be a rational number. Then
$\frac{a}{b}$ = $\sqrt{6}$ , where $a$ and $b$ are coprime.
Therefore,

$a^2 = 6 b^2$.
Here $a^2$ is divisible by both $2$ and $3$. Which means, $a$ too is divisible by both $2$ and $3$ (fundamental theorem of arithmetic).
Thus, $6b^2=(3\cdot2\cdot k)^2$ ; where $k$ is an integer.
$6b^2=36k^2$ or
$b^2=6k^2$.
Here $b^2$ is divisible by both $2$ and $3$. Which means, $b$ too is divisible by both $2$ and $3$. Therefore, $a$ and $b$ have common factors, which is a contradiction. Therefore $\sqrt{6}$ is not rational.

Is the above proof correct? Is there an easier way to prove this?

A: This is correct! This is pretty much the standard way to show that a number of this form in not rational and can actually be adopted to all non-perfect squares if you're a little careful (hint: all non-perfect squares are the product of a square-free number and a perfect square).

(these comments have been adopted into the OP) Two notational comments: The theorem that refer to is more commonly called the "fundamental theorem of arithmetic" or simply "the unique prime factorization theorem." Secondly, using a period to denote multiplication is something to be very much avoided. Use \cdot or\times to produce $\cdot$ and $\times$ respectively instead.

A: That works fine, but you don't need to do both $2$ and $3$. If:
$$a^2=6b^2$$
Then $a$ must be even, $a=2a_0$, and then: $4a_0^2=6b^2$ or $$2a_0^2=3b^2.$$
So $3b^2$ must be even, so by the fundamental theorem of arithmetic, $b$ must be even, and you are done.

A: Yes, your proof is valid. You have used a standard technique.


text:
Q: How to catch error from promise (node js) let commandPromise = async (command) => {
    try {
        return new Promise((resolve, reject) => {
            try {
                child_process.exec(command, (error, stdout, stderr) => {
                    if (error) return reject(error);
                    if (stderr) return reject(stderr);
                    return resolve(stdout)
                })
            } catch (err) {
                return reject(err)
            }
        })
    } catch (err) {
        throw err
    }
};

Is it the correct way to catch the error in this case or exist better way? The code seems not good.

A: For your case everithing will work if you add 'await' before new Promise()
 let commandPromise = async (command) => {
   try {
       return await new Promise((resolve, reject) => {
           try {
               child_process.exec(command, (error, stdout, stderr) => {
                   if (error) return reject(error);
                   if (stderr) return reject(stderr);
                   return resolve(stdout)
               })
           } catch (err) {
               return reject(err)
           }
       })
   } catch (err) {
       throw err
   }
 };

A: You are missing concepts here but, this is the golden rule:

*

*For sync code, use try / catch

*For async code, avoid try / catch because doesn't work and go for callback(err, data) or Promise reject styl

*If you are using new ES7 syntax await/sync then you can use try / catch

On your code, this is one simple approach:
const commandPromise = async (command) => {
  return new Promise((resolve, reject) => {
    child_process.exec(command, (error, stdout, stderr) => {
        if (error) {
          return reject(error);
        }

        if (stderr) {
          return reject(stderr);
        }

        return resolve(stdout)
    });
  });
};

ES7 way:
const commandPromise = async function(command) {
  child_process.exec(command, (error, stdout, stderr) => {
      if (error) {
        throw error;
      }

      if (stderr) {
        throw stderr;
      }

      return stdout;
  });
};

A: Both of the try - catch blocks are unnecessary and you can get rid of them.
Moreover, because commandPromise does not use await keyword, you can also remove the async keyword from the function declaration.
Any errors occured during the execution of the child_process would be passed as error in the callback which your code already handles.
Here is the better code:
let commandPromise = (command) =>
    new Promise((resolve, reject) => {
        child_process.exec(command, (error, stdout, stderr) => {
            if (error) return reject(error);
            if (stderr) return reject(stderr);
            return resolve(stdout);
        });
    });

And to use it:
commandPromise(/* some command */)
    .then(() => {
        /* ok */
    })
    .catch((error) => {
        /* handle error */
    });

A: Errors thrown or rejected in promises can be caught by .catch() method. Try/catch doesn't work with asynchronous code.
You can use it like:
promise.catch(function(err) {
    // do something
})

For more details, look at other stackoverflow answers which target the same question.


text:
Q: How can I center an integer variable in a string? This is what I'm trying to do:
   Time        Distance
----------    ----------
    1              100
    2              200

I've tried:
count = 1
print('   Hour   ' + '\t' + ' Distance ')
print('----------' + '\t' + '----------')
while count <= timeTraveled:
print(str.center(10[str(count)]) + '\t' + str.center(10[str((speedOfVehicle * count))]))
count = count + 1

No matter how much I try to make my variables a string for formatting purposes I always encounter:
TypeError: 'int' object is not subscriptable

A: I think I see your problem: you've mistaken the meta-syntax of documentation for Python syntax.
When a document describes a command with optional fields, brackets denote the option parts.  This description style is at least 45 years old, dating back to the days when IBM drove all things computer in the western hemisphere.  For help in writing your command, see the examples farther down.
In your case, you need something like
print(str(count).center(10))

This is a method of the string class; it operates on the string with which you call it.  In your case, that string is str(count).  Can you follow the rest from there?


text:
Q: Link to document properties/metadata in SharePoint 2013 Designer document approval workflow My company is using SharePoint 2016 on premise. I used SharePoint Designer 2103 to build a document approval workflow. The workflow sends an email note to the members of a SharePoint group when a user checks in a major version of a document. The email note contains a link that opens the document and a link that takes the user to the document approval task, and all of that works correctly. I have now been asked to add a link to the email note that takes the approver to a page that displays the document metadata (please see attached "document metadata dialog" image) BEFORE the initiate the approval. Is that possible?

A: Absolutely. The forms that show the list of metadata are the Display Form (read-only, when you "view properties") and the Edit Form (editable, as in your screen shot).
You can construct the correct URL to that form in your workflow. In your question, you are calling your screenshot the "document metadata dialog", so I am assuming you have your library set to open forms in a dialog. That may be the behavior you ultimately want to keep, but if you want to see how the URLs are constructed, you can go into your library settings, advanced settings, and set "Launch forms in a dialog" to No:

and then go and "view properties" or "edit properties" for one of your documents, and then look at the address bar.
You will see that for the Display Form, the URL is
<Your site URL>/Lists/YourLibraryName/Forms/DispForm.aspx?ID=<the ID of the document>

and for the Edit Form, the URL is
<Your site URL>/Lists/YourLibraryName/Forms/EditForm.aspx?ID=<the ID of the document>

So, you can construct either of those URLs in your workflow.  You can get the site URL from the workflow context:

Getting the site URL that way includes a trailing slash, so you don't need to add one between that and Lists/.  Choose which form you want to direct people to, construct the URL to that form, and then add the ID of the current item as the ID query parameter:
[%Workflow Context:Current Site URL%]Lists/YourLibraryName/Forms/DispForm.aspx?ID=[%Current Item:ID%]

or
[%Workflow Context:Current Site URL%]Lists/YourLibraryName/Forms/EditForm.aspx?ID=[%Current Item:ID%]

and then use that URL in the link in your email.


text:
Q: How to make a timespan column based on a time stamp column? I have a datatable with timestamps in column 1 and events in column 2. The timestamps have the format Y-m-d H:M:OS3 (e.g. "2019-09-26 07:29:22,778").
I would like to add a new column with time-span values of the difference between timestamp 2 to timestamp 1, then 3 to 1 etc. E.g.:
timestamp                  event           diff in sec
2019-09-26 07:29:22,778    X
2019-09-26 07:29:23,918    Y               1.140
2019-09-26 07:29:25,118    Z               2.340
.
.

A: In base:
dt1$timediff <- cumsum(c(0, difftime(tail(dt1$timestamp,-1), head(dt1$timestamp,-1))))

or using data.table:
library(data.table)

dt1[ , timediff := cumsum(c(0, diff(as.numeric(timestamp))))][]
#>                  timestamp event timediff
#> 1: 2019-09-26 07:29:22.778     X     0.00
#> 2: 2019-09-26 07:29:23.917     Y     1.14
#> 3: 2019-09-26 07:29:25.118     Z     2.34

Another dplyr solution base off of akrun's answer:
library(dplyr)
dt1 %>%
  mutate(difftime = difftime(timestamp, timestamp[1], unit = 'sec'))

Data:
N.B: I am using data.table to read the data.
fread(text="date time  event
 2019-09-26 07:29:22.778    X
 2019-09-26 07:29:23.918    Y
 2019-09-26 07:29:25.118    Z") -> dt1

dt1$timestamp <- as.POSIXct(paste(dt1$date, dt1$time), format="%Y-%m-%d %H:%M:%OS")

dt1 <- dt1[,4:3]

A: We can use difftime
library(dplyr)
library(lubridate)
df1 %>%
   mutate(timestamp = ymd_hms(timestamp),
          diffinsec = cumsum(as.numeric(difftime(timestamp,
       lag(timestamp, default = timestamp[1]), unit = 'sec'))))

A: Here a solution with dplyr. I assumed that you want the time difference from the first event. Otherwise @akrun's answer with lag() is the correct one.
library(dplyr)
df %>%
  mutate(start = min(timestamp)) %>%
  mutate(diff = timestamp - start)
#>             timestamp             event               start      diff
#> 1 2019-09-26 07:29:22                 X 2019-09-26 07:29:22 0.00 secs
#> 2 2019-09-26 07:29:23                 Y 2019-09-26 07:29:22 1.14 secs
#> 3 2019-09-26 07:29:25                 Z 2019-09-26 07:29:22 2.34 secs

data
df <- structure(list(timestamp = structure(c(1569479362.778, 1569479363.918,
                                                 1569479365.118), class = c("POSIXct", "POSIXt"), tzone = ""),
                         event = c("X", "Y", "Z")), row.names = c(NA,
                                                                                -3L), class = "data.frame")