text:
Q: How do i evaluate $ \bigtriangleup^{10}(1-ax)(1-bx^{2})(1-cx^{3})(1-dx^{4}) $ How do i evaluate $ \bigtriangleup^{10}(1-ax)(1-bx^{2})(1-cx^{3})(1-dx^{4}) $
where $ \bigtriangleup$ is forward difference operator. Now to evaluate this is impossible almost using definition which is $ \bigtriangleup$f(x)=$f(x+h)-f(x)$, so there has to be some trick to do this which i am looking for
Thanks

A: HINT: I would first prove two generally useful facts about $\Delta$.

*

*Prove that $$\Delta^k(x^n)=\begin{cases}
0,&\text{if }k>n\\
n^{\underline k},&\text{if }k\le n\;,
\end{cases}$$ where $x^{\underline k}$ is the falling factorial, defined as $$x^{\underline k}=\underbrace{x(x-1)\ldots(x-k+1)}_{k\text{ factors}}\;.$$ In particular, note that $n^{\underline n}=n!$.

*Prove that $\Delta$ is a linear operator: $\Delta\big(af(x)+bg(x)\big)=a\Delta\big(f(x)\big)+b\Delta\big(g(x)\big)$ for functions $f$ and $g$ and constants $a$ and $b$.
Now observe that once it's been multiplied out, $(1-ax)(1-bx^2)(1-cx^3)(1-dx^4)$ is a polynomial $p(x)$ of degree $10$; why?
The second result above says that you can evaluate $\Delta^{10}\big(p(x)\big)$ one term at a time, just as you might differentiate it one term at a time. And the first result above lets you do those individual evaluations very easily.

A: The  highest term that survives after $\bigtriangleup^1,$
$$abcd\cdot10\{(x+1)^{10}-x^{10}\}=abcd\cdot10\cdot x^9$$
The highest term that survives after $\bigtriangleup^9,$   $$abcd\cdot\prod_{r=0}^8(10-r)\cdot x$$


text:
Q: Status of verb in "winner-take-all" In the expression a "winner-take-all society", I'm interested in the status of the verb: is it an infinitive or an imperative? As a related question, would it look odd to an anglophone if I wrote "a-winner-takes-all society" ? I would be quite grateful if, as a bonus, a user told me the origin of this metaphor: poker or some other game perhaps?
Edit I now realize, following Kosmonaut's comment, that there are several similar constructions in English: a know-it-all, a ne'er-do-well. And interestingly also  in French: "un vaurien" and in German "Ein Taugenichts".

A: As I see it, there are four questions here, and I certainly cannot answer them all.

*

*Which is the correct hyphenated adjectival phrase: winner-take-all society or winner-takes-all society?

*If winner-take-all is correct, why doesn't the verb have to agree with the subject?

*What is the verb form called in this construction?

*What is the origin of this phrase?

To my ear, both winner-take-all society and winner-takes-all society sound fine.
Looking at Google Ngrams, we find: .
So winner-take-all has historically been ahead, but winner-takes-all is rapidly catching up. Note that we cannot compare the phrases winner take all with winner takes all using Google Ngrams, because then we would get constructions like ... and the winner takes all!, which are not adjectival phrases. However, I searched in Google books for the phrase with the indefinite article, a winner take/takes all, and virtually all the hits are adjectival phrases.
The only similar construction in adjectival phrases I can think of is dog-eat-dog. Here the construction is definitely dog-eat-dog (confirmed by Google Ngrams, although dog-eats-dog is occasionally used), and the verb also does not agree with the subject.
So I conclude that in similar adjectival phrases (can anybody think of any others?) the verb does not have to agree with the subject, but I am baffled as to what mood/tense the verb is. In dog-eat-dog world it is clearly not the imperative (it's not a command). The infinitive and subjunctive don't seem likely, either.
UPDATE: There's also buyer-beware as in buyer-beware laws. Here, the verb is definitely in the subjunctive, while Henry in his answer has made a pretty good case for the  verb in dog-eat-dog being the infinitive. The adjectival phrase winner-take-all may have originally been applied to the American electoral system. However, Google books comes up with a number of apparently earlier instances of bets where everybody contributes some amount, and "winner take all." If this was the origin, it is also the subjunctive, as it would presumably have been shortened from a phrase such as Let the winner take all.

A: Personally I would say (note hyphens and verb)

a winner-takes-all society

since you should not use a hyphen after the article and winner-takes-all is acting as an adjective (hence the hyphens) so does not need a hyphen to the noun.  I would also use takes rather than take, as it is clearly the description of a competition where a single winner takes all of the stakes.  In this case, takes is a normal 3rd person singular verb.
I know other variants exist, including a book, but apart from winners-take-all I would regard them as being wrong.
Added: @Kosmonaut's comment It's a dog-eat-dog world is interesting, though there seems to be some debate over the timing of its origin: 1500s here, 1850s here and 1931 here.  Word Origins gives The Times in 1789 saying "As it is an established fact, that sharper will not rob sharper, nor dog eat dog", suggesting that dog eat dog is a set-phrase shortening of dog will eat dog or dog does eat dog, making eat an infinitive.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display UNIQUE options in a dropdown menu with Angular2 using an array of objects fetched from firebase Using Angular2, I have a dropdown menu in my html file that looks like this (I'm using Ink as my CSS framework):

      Role in the Organization

                {{currentRole}}

I am able to confirm that members works correctly, because other html downstream in the same template works.
The problem (I think) is that the members array is retrieved asynchronously. It seems that something like *ngFor="let currentRole of getUniqueRoles(members) | async" doesn't seem to work. I gladly welcome advice! I'm guessing from similar questions that a pipe is the answer, but I'm not quite sure how to implement if I want to filter by a property of member.
Currently, the dropdown displays nothing. To clarify, I see the "Role in the Organization" option, but its own dropdown is populated a blank rectangle."
The typescript of the same component, for reference:
getUniqueRoles(members: Member[]){
    var flags = [], output = [], l = members.length, i;
    for( i=0; i<l; i++) {
      if( flags[members[i].role]) continue;
      flags[members[i].role] = true;
      output.push(members[i].role);
    }
    return output;
  }

My members model:
export class Member {
  public dateCreated: Date = new Date();
  public TWITTERPOPULATION: number = 328000000; // TODO figure of how to globally access this as a const
  public TOTALWORLDWEALTH: number = 60000000000;
  public influenceQuotient: number;

  constructor(public firstName: string, public lastName: string, public illuminatiNickname: string, public sectorOfInfluence: string, public numberOfTwitterFollowers: number, public netWorth: number, public politicalImpactQuotient: number, public suspicionOfIlluminatiMembership: number, public role: string, public salientDetails: string, public imgURL: string, public imgAlt: string) {
    this.influenceQuotient = numberOfTwitterFollowers/this.TWITTERPOPULATION + netWorth/this.TOTALWORLDWEALTH + politicalImpactQuotient - suspicionOfIlluminatiMembership;
  }
}

members[] is just an array of Member objects (but fetched from fireBase).


text:
Q: Is there any penalty on resurrecting dead dwellers in Fallout Shelter? I get dead dwellers from time to time and I use to resurrect them, is there any penalty (temporal or permanent) applied to resurrected dwellers in any way?

A: It does not appear that there are any additionally penalties applied to the dweller (I haven't been able to find anything). You just have to pay the revival fee.


text:
Q: Frontend raw TCP/UDP sockets in a browser, any way at all in 2021? I've seen many questions about using raw TCP/UDP sockets in web browsers using JavaScript/Html5 however they are all old like this one posted 5 years ago. It is now 2021 and I'm wondering if there is any possibility at all to avoid using WebSockets and instead use raw TCP/UDP sockets so my local Web page can talk with my local Python socket server.
I don't mind if it's not accessible via internet, or if I need an extension as it's only for a home project where a web page on my Raspberry Pi zero will communicate with my main computer to request data via its Python socket server.
I know that Chrome apps had a socket API before the apps were dropped and I saw this article about Chromium devs wanting to add sockets, but failed to find any real info about it.
Does anyone know of any way to use raw TCP/UDP sockets in a browser?


text:
Q: Extend default AccountController/Manage with custom UserProfile The default MVC 4 application includes an AccountController which does implement the usual account related methods. After you're logged in, you have  Account/Manage/ which uses LocalPasswordModel to enable you to change your password and manage your external login if OAuth is activated.
After extending the UserProfile with additional data I would like to give my user an option to change it. I could create a new View that uses the UserProfile as model, but I would like to add it to the existing Manage view, but that one is using LocalPasswordModel as a model.
I apologize if my question is really basic, but how can I combine the two?


text:
Q: DataGridView Datatable Copy-Keep-Add-Update rows I am developing Windows application (environment: Visual Studio 2010 and C#)
I use a datagridview with records completed by datatable dt:
 dataGridView1.DataSource = dt;

This datatable has 20 columns with 1 identity column - column[0] = autonumber, and  column[1] called "RecordChecked" implemented as Boolean (checkbox).
I need to solve next problems:

*

*Select rows filtered by column[2] (in code example: DrawingNo='DM-3012');

*Keep these records

*Add exactly the same records below existing but update column[2] with different value like DrawingNo='DM-3013' (so we'll have twice more records)

I started from copying records from one datatable into another (see code below) – this code works ok, but then stacked how to add copied records below existing and then update them:
DataTable dtSource = ((DataTable)dataGridView1.DataSource);

DataTable dtTarget = new DataTable();

dtTarget = ((DataTable)dataGridView1.DataSource).Clone();

DataRow[] rowsToCopy;

rowsToCopy = ((DataTable)dataGridView1.DataSource).Select("DrawingNo='DM-3012'");

foreach (DataRow temp in rowsToCopy)
{
      dtTarget.ImportRow(temp);
}

dt = dtTarget;

Thanks,

A: I think I found a good approach to this problem.
1. Create Stored Procedure (mySP).
This SP creates temp table where we located all records selected with clause 'WHERE DrawingNo = @CopyFrom'.
Then this SP updates temp table with statement like:
    UPDATE #TempTbl1 SET RecChecked = 0, DrawingNo = @CopyTo WHERE DrawingNo = @CopyFrom.
Then SP inserts updated records from temp table into the main table.
Finally SP drops temp table and selects all needed records from the main table.
2.  Now we can run this SP in app and bind data to datagridview like:
//Run SP
using (SqlCommand cmd = new SqlCommand("mySP", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@CopyFrom", SqlDbType.VarChar).Value =   sValueFrom;
    cmd.Parameters.Add("@CopyTo", SqlDbType.VarChar).Value = sValueTo;
    con.Open();
    cmd.ExecuteNonQuery();
}

//Create SELECT statement
string strSelect = "SELECT Recid, RecChecked, DrawingNo, ...  FROM Tbl1 WHERE DrawingNo = '" + sValueTo + "'"

//fill dataadapter
sda = new SqlDataAdapter(@strSelect, con);
dt = new DataTable();
sda.Fill(dt);

That works!


text:
Q: Replacing multiple items(commas, periods, etc.) in SQL code Here is the code that I am using currently, I am trying to replace commas and periods in my database but right now it is only doing one or the other. Thanks
(Case when dim.obligorname like '%,%' then Replace(DIM.[ObligorName], ',', ' ')
           Else case when dim.obligorname like '%.%' then Replace(DIM.[ObligorName], '.', ' ')
            Else Dim.ObligorName end end) as Obligorname,

A: Why not just try something like this:
UPDATE myTable DIM
  SET DIM.[ObligorName] =
    Replace(Replace(DIM.[ObligorName], ',', ' '), '.', ' ')

A: How about something like this:
Replace( Replace(DIM.[ObligorName], ',', ' '), '.', ' ')


text:
Q: WPF DragDropEffects not set properly in Drop event I'm trying to drag-and-drop some data within my application. I want the DragDropEffects to be Move if the control key is NOT pressed, and Copy if the control key is pressed. It seems like this should be trivial, but I've searched a bunch and haven't found an answer to this.
Here is my code, based loosely on Microsoft's example:
private static void dragSource_MouseMove(object sender, MouseEventArgs e)
{
    DragDrop.DoDragDrop(currentDragDef.DragSource, currentDragDef.Data, DragDropEffects.All);
    e.Handled = true;
}

private static void dropTarget_DragOver(object sender, DragEventArgs e)
{
    bool ctrlKey = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
    if ((e.Effects & DragDropEffects.Move) == DragDropEffects.None || ctrlKey)
    {
        // Control key is pressed or move is not allowed. Do copy/link.
        e.Effects &= ~DragDropEffects.Move;
    }
    else
    {
        // Control key not pressed. Do move.
        e.Effects &= (DragDropEffects.Move | DragDropEffects.Scroll);
    }
    e.Handled = true;
}

e.Effects is getting set fine in dropTarget_DragOver. The mouse cursor adds a '+' icon whenever I press control. However, in the Drop event, e.Effects equals DragDropEffects.All again. Why is this? How to I get e.Effects to equal something different in the Drop event? Or is this even possible?
private static void dropTarget_Drop(object sender, DragEventArgs e)
{
    if (e.Effects == DragDropEffects.None || !e.Data.GetDataPresent(DataFormats.FileDrop))
        return;
    var effects = e.Effects;
    // effects == DragDropEffects.All, but I want it to have the Move or Copy flag removed
}

Aside: another thing is that I'm using Keyboard.IsKeyDown instead of e.KeyStates because e.KeyStates seems to always equal DragDropKeyStates.LeftMouseButton. The DragDropKeyStates.ControlKey bit is always 0, even if control is pressed. Any idea why this is?

A: You should duplicate the logic in your DragOver function in the Drop function, to determine the effects again.
Instead of reading the effects field from DragEventArgs, you should write it back. The value is passed back to the source and is the return value from the function DoDragDrop.
This is more or less described by Microsoft in
https://msdn.microsoft.com/en-us/library/ms742859%28v=vs.100%29.aspx, but the behaviour is not obvious. I made the same mistake as you.


text:
Q: Expected coverage after sampling with replacement 'k' times
Possible Duplicate:
probability distribution of coverage of a set after X independently, randomly selected members of the set

If I sample with replacement $k$ times from a jar of with a finite population of $N$ unique marbles.  What is the probability distribution for the fraction of the unique marbles that I sample?

A: We answer only the expectation question in the title, and not the more complicated distribution question asked in the body of the post.
Questions like this one have been asked several times on MSE. There is also a large technical literature on related questions.
For $i=1$ to $N$, let random variable $X_i$ be $1$ if $i$ is chosen at least once, and let $X_i=0$ otherwise.
The probability that $X_i=1$ is $1$ minus the probability that the number is chosen no times. On any one trial, the probability of not choosing $i$ is $\frac{N-1}{N}$.
Hence
$$\Pr(X_i=1)=1-\left(\frac{N-1}{N}\right)^k.$$
The number $Y$ of $i$ chosen is given by
$$Y=\sum_{i=1}^N X_i,$$
so by the linearity of expectation,
$$E(Y)=\sum_{i=1}^N X_i=N\left( 1-\left(\frac{N-1}{N}\right)^k \right).$$
For the expected proportion, divide by $N$.


text:
Q: RaphaelJS stroke opacity I tried to set stroke opacity to 1 to avoid darken color on duplicate line. Fiddle example here.
var paper = Raphael(0, 0, 400, 400);

paper.path('M10 20 L100 20');
paper.path('M50 20 L100 20');

I need to have same color every time.

Edit:
Thanks to Robert Longson - I got solution.
Before:                                       After:

A: That's not opacity, it's antialiasing you're encountering. Either
a) add 0.5 to the co-ordinates e.g.
paper.path('M10 20.5 L100 20.5');
paper.path('M50 20.5 L100 20.5');

or b) turn antialiasing off e.g. add this to your CSS
path {
    shape-rendering:crispEdges
}

Note that Raphael will stop you setting shape-rendering via the attr function so you have to work around that.


text:
Q: PrimeNg (7.x) p-dropdown boolean value I would like to have a p-dropdown that contains two options.
But the items do not get selected based on the control boolean value.
The control (NOTIF_ALL) receive a boolean value
oldPendingTasksOptions=[
 {"oldPendingTaskId": false, "oldPendingTasksName": "Not activated", "version": 1},
 {"oldPendingTaskId": true, "oldPendingTasksName": "Activated", "version": 1}
 ]

<p-dropdown [options]="oldPendingTasksOptions"
  [showClear]="true"
  placeholder="Select an option"
  optionLabel="oldPendingTasksName"
  formControlName="NOTIF_ALL"></p-dropdown>

A: Convinced the client that a radio was better ;)


text:
Q: How to allow both types ref callback and MutableRefObject? I've trying to allow both types (ref: any) => void Or MutableRefObject<any>
 interface RowProps extends React.HTMLAttributes<React.ReactHTML> {
    componentRef: (ref: any) => void | React.MutableRefObject<any>;
    //...
}

RowProps interface has componentRef which has multiple type.
I expected to allow both types, but:
    let refFuncVer = React.useRef(null);
    let refObjectVer = React.useRef(null);

    // It is okay
    componentRef={(ref) => {refFuncVer.current = ref;}}

    // type error:
    componentRef={refObjectVer}

Why is it?

A: You forgot to put parentheses around your function type definition:
componentRef: ((ref: any) => void) | React.MutableRefObject<any>;

The TypeScript compiler thinks you meant:
componentRef: (ref: any) => (void | React.MutableRefObject<any>);


text:
Q: How to send JavaScript to specific tab in Chrome Extension? Thanks for helping.
Right now I am working on a chrome extension. I have an extension background script that uses a function to open new tabs in the browser to complete different 'tasks'. The function uses variables obtained from an api to decide the tab url and at what time to open it, etc.
Here is my function:
function NewTask(var1, var2, var3) {
chrome.tabs.create({url: var1+var2+var3, active: false}, tab=>{
    tab.console.log(var5, var6)
})

}
As you can see, I try to console.log var5 and var6 on the new tab as an example. However, this does not work the way I intended. Is there a way I can pass the var5 and var6 variables through the function to the new tab?

A: This is one of the more confusing aspects of extensions. chrome.tabs.create is running in the "background" of the extension (where it has access to manipulate tabs by tabId)
So the callback you pass as the last parameter also runs in the background, to run javascript in a certain tab, you can use
chrome.tabs.executeScript(tabId, { code: `console.log("I run in the tab, not the background!")` })

The code run in the tab is passed as a string, If you want to pass a variable from  the background script, you could do so like below (if the use of "string ${variable}" is confusing, check out Expression interpolation)
var urlFromBackground = "https://google.com"
var colorFromBackground = "rebeccapurple"
chrome.tabs.create({url: urlFromBackground, active: false}, tab=>{
    chrome.tabs.executeScript(
      tab.id,
      { code: `document.body.background = ${colorFromBackground}` }
    )
})


text:
Q: What is the difference between Microsoft WebMatrix and Visual Studio? I understand that using the WebMatrix is easier as the tool seems more focused towards ASP.NET. However, I was curious to know through if it is possible to also create the same ASP.NET files using just Visual Studio. Would using the WebMatrix be a good start for understanding how to create web applications. Visual Basic can create applications that will run on your computer also right?

A: WebMatrix is a do it all package with Express IIS, Visual Studio is an IDE developed towards the .Net framework. Basically Webmatrix is specialized towards Web Development and Visual Studio is a powerhouse package that has a Web development aspect. That is the basics of it. Hopefully someone has a much more in depth answer but to tell you the truth, this is easily re-searchable via Google.

A: Webmatrix = web application focus;
Visual Studio = you decide the application focus;
If you want to do only Web and feel that Visual Studio is too much for the kind of project you want to do, which is true in a lot of cases, then I would suggest just using Web Matrix. As your project grows, however, you will soon find yourself in Visual Studio simply because it has more power and reach to build more complex systems.
I generally spin up a Web Matrix app if I want a quick catch all solution (kind of like MAMP or XAMMP) to test a small application, or play around with sql.

A: As far as I understand the major difference is Webmatrix supports PHP and node.js.
You can read more here :
http://www.microsoft.com/web/platform/tools.aspx


text:
Q: Can I write tests for invalid lifetimes? I'm writing some Rust code that manipulates raw pointers. These raw pointers are then exposed to users through structures that use ContravariantLifetime to tie the lifetime of the struct to my object.
I'd like to be able to write tests that validate that the user-facing structures cannot live longer than my object. I have code like the following:
fn element_cannot_outlive_parts() {
    let mut z = {
         let p = Package::new();
         p.create() // returns an object that cannot live longer than p
    };
 }

This fails to compile, which is exactly what I want. However, I'd like to have some automated check that this behavior is true even after whatever refactoring I do to the code.
My best idea at the moment is to write one-off Rust files with this code and rig up bash scripts to attempt to compile them and look for specific error messages, which all feels pretty hacky.

A: The Rust project has a special set of tests called "compile-fail" tests that do exactly what you want.
The compiletest crate is an extraction of this idea that allows other libraries to do the same thing:
fn main() {
    let x: (u64, bool) = (true, 42u64);
    //~^ ERROR mismatched types
    //~^^ ERROR mismatched types
}

One idea that gets halfway there is to use Cargo's "features".
Specify tests with a feature flag:
#[test]
#[cfg(feature = "compile_failure")]
fn bogus_test() {}

Add this to Cargo.toml:
[features]

compile_failure = []

And run tests as
cargo test --features compile_failure

The obvious thing missing from this is the automatic checking of "was it the right failure". If nothing else, this allows me to have tests that are semi-living in my codebase.

A: You are able to annotate a test that you expect to fail.
#[should_fail]

As such, you can write a test that attempts to breach the life time it should have, and thus fail, which would actually be a pass.
For an example of a test for 'index out of bounds' see below (pulled from the Rust guides)
#[test]
#[should_fail]
fn test_out_of_bounds_failure() {
    let v: &[int] = [];
    v[0];
}

I believe that this example would be a compilation error, so it would stand to reason your compile lifetime violation error would be caught by this too.


text:
Q: Is a settlement with 50,000 inhabitants a town or a city? I wonder when a place deserves to be called a city.
Suppose that we have a settlement which has 50,000 persons. Is that a town or a city?

A: Whether an urban area is designated a town or a city depends on several factors.
The first is the size of the population: According to: Settlement Hierarchy, Wikipedia:

The population of a city is over 100,000 people up to 300,000. Large town – a large town has a population of 20,000 to 100,000. Town – a town has a population of 1,000 to 20,000. Village – a village is a human settlement or community that is larger than a hamlet but, smaller than a town.

Differencebetween.net points out that:

Cities cover a wider area than towns and as cities advance, they may sometimes incorporate or merge with surrounding areas. Towns on the other hand do not generally expand into other areas in the same way as cities.

But the most important factor is the local naming convention.
In the United Kingdom, city status is granted by the monarch.
(https://en.wikipedia.org/wiki/City_status_in_the_United_Kingdom)
In much of early Christian Europe, city status depended on the presence of a cathedral as a statement of the bishop's authority. In 16th century England:

After founding the Church of England in 1534 Henry VIII created 6 cathedral towns in the 1540's and gave them all city status by letters patent. This created the association between having a cathedral and city status. The other towns with cathedrals at the time also became to be considered cities since "time immemorial".

(http://www.lovemytown.co.uk/Cathedrals/Cathedrals.htm)
So, in answer to your question, your 50,000 strong community is unlikely to be considered a city unless some authority has declared it to be one.


text:
Q: BlackBerry - show info when status bar is pulled down (like 'droid Notification Area) Thanks to Max Gontar, I can put my notification icon in the status bar on 4.6 and up (Blackberry - How to use notification icon in statusbar).
But in later versions (6 I think?) one can click on the status bar and it will drop down with info on latest calls, App World updates etc.

This is similar in some ways to the 'droid Notification Area. What classes / methods should I be looking at to implement this kind of info, so I can add my own section to this drop-down area?

A: Use the ApplicationMessageFolderRegistry and ApplicationMessageFolder classes, and the ApplicationMessage and ApplicationMessageFolderListener interfaces.


text:
Q: applying appscript code for multiple selections in a drop down to multiple sheets in work book Non-coder here. I have found/copied appscript code to enable multiple selections from a drop down list in a Sheet. I've adjusted the code for the Sheet I am referring to and the relevant Columns and it works fine in that Sheet.
How or where do I apply the same basic code to other Sheets in the book while assigning it to different columns on each sheet (e.g. Sheet 1 needs this in Column 6, 5; but Sheet 2 needs this in Column 4, 5)?
This is the code I'm using
function onEdit(e) {
var oldValue;
var newValue;
var ss=SpreadsheetApp.getActiveSpreadsheet();
var activeCell = ss.getActiveCell();
if(activeCell.getColumn() == 6 || 7 &&
ss.getActiveSheet().getName()=="Sheet1")
newValue=e.value;
oldValue=e.oldValue;
if(!e.value) {
activeCell.setValue("");
}
else {
if (!e.oldValue) {
activeCell.setValue(newValue);
}
else {
if(oldValue.indexOf(newValue) <0) {
activeCell.setValue(oldValue+', '+newValue);
}
}
}
}
}

A: function onEdit(e) {
  //e.source.toast('entry');
  const obj = {'Sheet1':{low:4,high:7},'Sheet2':{low:3,high:6}};
  const sh = e.range.getSheet();
  //sh.getRange('A1').setValue(JSON.stringify(e));
  const name = sh.getName();
  if( e.range.columnStart > obj[name].low && e.range.columnStart < obj[name].high ) {
    //e.source.toast('flag0');
    if(!e.value) {
      //e.source.toast('flag1');
      e.range.setValue('');
    } else if(!e.oldValue) {
      //e.source.toast('flag2');
      e.range.setValue(e.value);
    } else if(!~e.oldValue.indexOf(e.value)){
      //e.source.toast('flag3');
      e.range.setValue(`${e.oldValue},${e.value}`);
    }
  }
}


text:
Q: Given some polygon drawn on a clock: how many distinct edges and polygons it contains? I'm creating polygons by stretching strings between numbers on the face of a clock. Those strings represent edges and they create polygons.
I'd like to know how many of those edges, triangles, quadrilaterals (etc.) are distinct.
For instance, in Ex. 1, I get 6 total edges:
$$\{0,3\} \{3,6\} \{6,9\} \{9,0\} \{0,6\} \{3,9\}$$
However, only 2 edges are distinct: $|3|$, and $|6|$.
Similarly, I get 4 triangles:
$$\{0, 3, 6\} \{3, 6, 9\} \{6, 9, 0\} \{9, 0, 3\}$$
Yet they are all of the form $(|3|, |3|, |6|)$. Therefore, I have 4 total triangles, and only 1 distinct triangle.

Here's another example.

In Ex. 2, only 3 edges are distinct and only 2 triangles are distinct.
Final example 3, has only 5 distinct edges, and all of its triangles are distinct.

Here's the question:
Given the coordinates (on an m-faced clock) of some polygon of n-sides, how can you determine the number of the distinct edges and polygons?


text:
Q: How to fix this? RuntimeError: dictionary changed size during iteration When I added an item to dictionary with in a function, it's giving this error:
inv = { "rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12 }
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def AddInventory(invloop, lst):
  for item in lst:
    for k,v in invloop.items():
      if item == k:
        v += 1
      else:
        invloop[item] = 1
  return(invloop)
inv = AddInventory(inv, dragonLoot)

A: Indeed you should not add items to the inventory while looping over it. What's more, you don't need that inner loop, because the advantage of a dictionary is that you have direct access via the keys: you can test whether it has a key or not with the in operator.
So do this instead:
def AddInventory(invloop, lst):
    for item in lst:
        if item in invloop:
            invloop[item] += 1
        else:
            invloop[item] = 1
    return(invloop)


text:
Q: JSTL using ${ } within ${ } I'm wondering if the following is possible:
<c:forEach var="y" begin="0" end="${amountY }">
            <c:forEach var="x" begin="0" end="${amountX }">

                ${${x }-${y } }
            </c:forEach>
            <br />
        </c:forEach>

I have already set a certain amount of attributes with names being as follows:
"an x value" + "-" +"a y value"

The point of the foreach is to call on these attributes but I don't know beforehand how many there will be.
Now I'm wondering if there's a way to do this with maybe a different syntax cus it's not working this way.
Otherwise is it maybe possible to fill a list with strings and have each string be a certain piece of html code. Then foreaching that list so the strings get implemented as html? Probably not but w/e.

A: You can't nest el expressions like that.
First use <c:set> to create a new EL variable.
<c:set var="name" value="${x}-${y}" />

Then use it as key to access the attribute value in a specific scope, e.g. ${requestScope}, or ${sessionScope}, or ${applicationScope}, depending on where you stored the actual values.
E.g. if it's in the request scope:
${requestScope[name]}

Needless to say that this is awkward design. Consider using a collection of maps or beans instead.


text:
Q: Android Unforunately App has stopped I am using 2 menu items, first menu item to send Global Greeting & second item for Settings,
whenever i click on Settings menu item, i am always getting below message:
Unfortunately App has Stopped
Logcat Says:
01-03 16:20:38.102: E/AndroidRuntime(953): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.january.floogoo/android.media.audiofx.BassBoost$Settings}; have you declared this activity in your AndroidManifest.xml?
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1618)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.startActivityFromChild(Activity.java:3843)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.startActivityFromChild(Activity.java:3819)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.startActivityForResult(Activity.java:3395)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.startActivityForResult(Activity.java:3331)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.startActivity(Activity.java:3566)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.startActivity(Activity.java:3534)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.january.floogoo.ContactTab.onOptionsItemSelected(ContactTab.java:90)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.Activity.onMenuItemSelected(Activity.java:2548)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:980)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:166)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.widget.AbsListView$1.run(AbsListView.java:3423)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.os.Handler.handleCallback(Handler.java:725)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.os.Looper.loop(Looper.java:137)
01-03 16:20:38.102: E/AndroidRuntime(953):  at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 16:20:38.102: E/AndroidRuntime(953):  at java.lang.reflect.Method.invokeNative(Native Method)
01-03 16:20:38.102: E/AndroidRuntime(953):  at java.lang.reflect.Method.invoke(Method.java:511)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 16:20:38.102: E/AndroidRuntime(953):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 16:20:38.102: E/AndroidRuntime(953):  at dalvik.system.NativeStart.main(Native Method)

Manifest.xml
  <activity
        android:name="com.january.floogoo.Main"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ContactTab"></activity>
    <activity android:name=".MonthTab"></activity>
    <activity android:name=".WeekTab"></activity>
    <activity android:name=".PersonalGreeting"></activity>
    <activity android:name=".GlobalGreeting"></activity>
    <activity android:name=".AlertPage"></activity>
    <activity android:name=".Settings"></activity>
    <activity android:name=".Alert2"></activity>

A: You already had Setting activity in your manifest, but I think with wrong package name.
Try setting it using full package name like com.january.floogoo.Settings.

A: Declare Settings Activity As in Manifest :
 <activity android:name="com.january.floogoo.Settings" />

and start Settings Activity using full package name because you have imported another package with same Activity name
 Intent intentd=new Intent(Current_Activity.this,
                              com.january.floogoo.Settings.class);
 startActivity(intentd);


text:
Q: Converting a number to a date (DD-MON-YY) in SQL I'm selecting a series of columns to place in a new table. One of these columns (EPISTART_RAW) is a date variable that is currently listed as a raw number, such as 13042015 and 01010216. What I'd like to do is convert these numbers according to a sensible date format, such as 13-APR-15 and 01-JAN-16.
I'm working through various examples I'd found online, but struggling.

A: I believe you just want to_date():
select to_date(EPISTART_RAW, 'DDMMYYYY')

If it is actually stored as a number, you need to handle initial zeros, so:
select to_date(to_char(EPISTART_RAW, '00000000'), 'DDMMYYYY')

A: Date value should be within quote:
select to_date(to_char('01010216'),'DDMMYYYY') dt from dual


text:
Q: fancytree - sortable getting the order of nodes, sorting in same nest level only I am using fancytree with sortable extensions and I found 2 problems which I am trying to fight for hours. Maybe someone might help me.
The goal is to be able to sort between elements in the same nest level, but now I am only able to sort root nodes.
Second think is more important and I have no idea why it works like that. When I am trying to get fancytree nodes (of course i would like to get them in current sorted order), all the time I get same order without relying on view display.
I am using these event to get nodes: $('#tree').fancytree("getTree").toDict()
html:

Javascript:
$(function() { // on page load
  $("#tree").fancytree({
    debugLevel: 0,
    selectMode: 1,
    extensions: ["dnd"],
    source: [{
        title: "Node 1",
        key: "1",
        "baloney": 44
      },
      {
        title: "Node 2",
        key: "2432"
      },
      {
        title: "Folder 2",
        key: "2",
        folder: true,
        children: [{
            title: "Node 2.1",
            key: "3",
            myOwnAttr: "abc"
          },
          {
            title: "Node 2.2",
            key: "4"
          },
                    {
            title: "Node 2.3",
            key: "5"
          },          {
            title: "Node 2.4",
            key: "6"
          },          {
            title: "Node 2.5",
            key: "7"
          }
        ]
      }
    ],
dnd5: {
                    preventForeignNodes: true,
                    preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
                    preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                    dragStart: function(node, data) {

                        return true;
                    },
                    dragEnter: function(node, data) {

                        return true;
                    },
                    dragDrop: function(node, data) {
                        data.otherNode.moveTo(node, data.hitMode);
                    },
                    activate: function(event, data) {
                    },
                    draggable: {
                        appendTo: "body",
                        connectToSortable: '#tree > ul',
                        containment: "parent",
                        revert: "invalid"
                    }
                },
  });

  $('#tree > ul').sortable({
    connectWith:"#fancytree",
    out: function(event, ui) {
      if (event.originalEvent.type === "mousemove") {
        $(ui.item).data('drugout', true);
      }
    }
  });

});

And here is fiddle link: Link

A: You need to add sortable to the child nodes also. Add the below code to fancytree initialization. This function basically observes child node expands and then activates sortable for the child nodes.
expand: function() {
    $('.fancytree-has-children').siblings().sortable();
},

I have updated the jsfiddle also. Check the link: https://jsfiddle.net/3zmLfe1h/11/
Answer to your 2nd Question: I am not sure about it but I guess maybe fancytree is saving the order in some way and returning it to you whenever you are trying to get it. You can get all the values using jQuery and Sortable though.


text:
Q: How to remove programmatically a tab bar item created in xcode My app is a tab bar based app with 5 tab items relation ship segue to view controllers. I would like to build 3 different view controllers with different sizes (iPhone 5, 6 and 6+). My ideas is to bind the 3 different view controllers within xcode graphical and remove the two not needed with the specific iPhone at runtime.
UITabBar *oldbar = self.tabBarController.tabBar;
UITabBar *newbar = [[UITabBar alloc] initWithFrame:CGRectMake(0,0,oldbar.frame.size.width,oldbar.frame.size.height)];
NSMutableArray *olditems = [[oldbar items] mutableCopy];
[olditems removeObjectAtIndex:2];
[olditems removeObjectAtIndex:3];
NSArray *newitems = [[NSArray alloc] initWithArray:olditems];
[newbar setItems:newitems animated:false];
[oldbar addSubview:newbar];

The problem is that xcode shows the "more.." tab because in xcode there are not 5 but 7 tab items?
Is there a better way to program what I need?


text:
Q: How can I format and humanize a video chunk duration using moment.js? I am trying to correctly display a duration with moment.js, but I can't find the right way to do it.
I have two events, start and stop. Both record in a variable a video current time, in seconds (e.g. 254.36 and 428.12).
First, I want to display the start and stop time. I achieve that like this:
var startTime = 12345; //let's say it is my start time in seconds
moment.utc(startTime *1000).format("HH:mm:ss.SSS");

Second, I want to display the duration between start and stop in a human readable way. For example, if stopTime - startTime === 94,23 seconds, I want to:

*

*omit the milliseconds. I could just use Math.round() on my subtraction result but I want to know if it can be done using moment.js.

*present it in an accurate formated version. I started with something like that:
moment.duration(stopTime - startTime , "seconds").humanize();

but it will display 'a few seconds' if I have, for instance, a 4 second input. If I have a stopTime - startTime === 94,23 seconds, I would like to display something like: 1 minute and 34 seconds (and omit the minute if it lasts less than a minute).
Again, I could avoid using moment.js but I want to take advantage of the localization features, learn what can and cannot be done and how to use it properly.


text:
Q: PHP timer for a javascript function I have a setInterval timer and it stores its information into database. Somehow people manage to cheat me. What I need is a PHP function to calculate time since Javascript timer has started and save time in DB? Is that even possible?

A: I think you call your PHP script using an Ajax call from setInterval.
So you can use in you're ajax complete callback :
var end = new Date().getTime();
var time = end - start; // start is defined before ajax call
console.log('Execution time: ' + time);

If you need to calculate it form server-side, use time() in PHP


text:
Q: how to run an executable in html Firstly, I am aware that this question has been asked before (Is it possible to run an .exe or .bat file on 'onclick' in HTML) but I tried to do what was suggested and I could not make it work.
Here is my code:
<html>
<body>

<input type="button" value="Launch Installer" onclick="window.open(file:///S:downloads/thing.sh)" />

</body>
</html>

This code is in a file called "test.html" in my downloads folder.
I ran it in command line with this command
open test.html

and that resulted in google chrome opening a blank page.
Also, I have an shell script in my downloads folder named "thing.sh" containing this code:
echo hello world

Thanks for the help.
Using PHP (I've tried fixing my file path and it still doesn't work)
I tried what was suggested in the link provided by james111 (how to run a .sh file from php?) and this is my code:
<?php
echo shell_exec('Users/mathewlewis/downloads/thing.sh');
?>

I'm not sure how to run a php file from command line like I did with the html file (I have this code saved in a file called test.php) so I tried putting it in a file named test.html and that created a blank page in chrome like before.

A: You cannot run a file like this, plain and simple.
It'll just download the file, that's if your path was correct, which it isn't.
You may consider looking into a php alternative
How to run abc.exe using php
Run sh files how to run a .sh file from php?
Edit:
You've tried to run a bash file using PHP, I'm assuming you're trying to run it from you Downloads folder?
Your path is incorrect, it should look something like this:
/Users/<user_name>/Downloads/thing.sh

But if you're running it from your server (in the folder of your php file), you'd reference the location based on the folder your php file is in.

A: You can use URL Protocol to do the thing according to your requirement.
try this method, Link to url Protocol sample


text:
Q: Java get all webpages(sitemap) for any website I want to get all webpages for a website for example for the bbc website(bbc.co.uk) it would get http://www.bbc.co.uk/news/, http://www.bbc.co.uk/weather/ etc.
One way i can think of going about doing this is just start from the homepage and collect all the links and for each linked webpage on the homepage do the same collection. Essentially the final goal is to generate a sitemap for any website.
Does anybody have any other solutions which would be more efficient than this?
Thanks.

A: Selenium can be used to achieve the same
WebDriver driver = new FirefoxDriver();
driver.load("http://bbc.co.uk");
// get all links from page
List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement link : links){
   // Store link and do something
}

A: I found a free & open source sitemap generator written in java that you could modify here...
Java-Open Source- SiteMap Generator Code


text:
Q: Proving that the Flag Variety $Fl(n;m_1,m_2)$ is connected. I wish to prove that the flag variety $Fl(n;m_1,m_2) = \{ W_1 \subset W_2 \subset V | dimW_i = m_i \}$, for $0 \le m_1 \le m_2 \le n$ where V is an n-dimensional vector space over $\mathbb{C}$ and $W_1, W_2$ are vector subspaces of V, is connected. I'm following a similar method we have been using in lectures for other Lie groups.
I have already shown that $U(n)$ acts transitively on $Fl(n;m_1,m_2)$ and that $U(n)$ is connected. I'm wondering if what follows is proof that $Fl(n;m_1,m_2)$ is connected.
$Fl(n;m_1,m_2)=U(n)/U(n)_{W_1 \subset W_2}$,since $U(n)$ acts transitively on $Fl(n;m_1,m_2)$. Thus, since $U(n)$ is connected, if we can show that $U(n)_{W_1 \subset W_2}$ is connected then it follows that $Fl(n;m_1,m_2)$ is connected.
Consider $U(n)_{W_1 \subset W_2}=\{F\in U(n) |F(W_1)=W_1, F(W_2)=W_2 \}$. It consists of maps with matrices of the form:
A=$ \left( \begin{array}{ccc}
A_{m_1,m_1} & 0 & 0 \\
0 & B_{m_2-m_1,m_2-m_1} & 0 \\
0 & 0 & C_{n-m_2,n-m_2} \end{array} \right)$
Where the index of the block denotes its size. This is because $F(W_2)$ will be orthogonal to $W_1$ and will be linear multiples of $e_{m_1+1},...,e_{m_2}$, and $F(W_1)$ will be orthogonal to $W_2$ and will be linear multiples of $e_{1},...,e_{m_1}$, where $e_1,...,e_n$ is the orthonormal basis of $Fl(n;m_1,m_2)$.
Now I think that I have to show that the blocks in the matrix are themselves contained in a connected component of a Lie group, which would mean that I could connect each of them to the identity matrix of the respective size and thus connect any matrix in the stabiliser subgroup I'm considering to the identity, but I'm not quite sure how to proceed. Could anyone please give me any hints as to the next step?
Many thanks.

A: I think you were already done after the introductory remark:

If the (continuous) action of a connected group $G$ on a space $X$ is transitive, the $X$ is connected.

In fact, assume $X=U_1\cup U_2$ with $U_1,U_2$ open and $U_1\cap U_2=\emptyset$.
Select $x\in X$. Then the map $f\colon G\to X$, $g\mapsto gx$ is continuous, hence $f^{-1}(U_1), f^{-1}(U_2)$ are open and are disjoint and $f^{-1}(U_1)\cup f^{-1}(U_2)=G$.
By connectedness of $G$, one of $f^{-1}(U_1), f^{-1}(U_2)$ is empty. But by transitivity, $f$ is onto, hence $f^{-1}(U_i)=\emptyset$ implies $U_i=\emptyset$ and we conclude that $X$ is connected.


text:
Q: Plot outline around raster cells Using ggplot2 I would like to plot a polygon (convex hull?) that honours the cell boundaries of a raster plot (created with geom_raster). I can use convex hull methods but they would pass through the x-y coordinates rather than around the cells of the raster plot (sorry my terminology is affected by my ignorance). As an example, given the following x-y coordinate data with categorical attribute d:
df <- data.frame(x = c(295, 300, 305, 310, 295, 300, 305, 310),
                 y = c(310, 310, 310, 310, 315, 315, 315, 315),
                 d = c(2, 2, 2, 1, 2, 1, 1, 1))

I can use ggplot2's geom_raster to plot the attribute as a fill:
ggplot(df, aes(x, y)) +
  geom_raster(aes(fill = d)) +
  coord_fixed()

To give:

But what I want is an outline hull of the categories defined by d. Something like this:

Can I do this with base R and ggplot2 or is there a way using the raster package or some other grid/raster/GIS package? I prefer to keep it as simple as possible.

A: You can certainly get those polygons using R's spatial facilities. Here's one way:
library(raster)

## Convert your data.frame to a raster object
r <- rasterFromXYZ(df)

## Extract polygons
pp <- rasterToPolygons(r, dissolve=TRUE)

## Convert SpatialPolygons to a format usable by ggplot2
outline <- fortify(pp)

## Put it all together:
ggplot(df, aes(x, y)) +
    geom_raster(aes(fill = d)) +
    coord_fixed() +
    geom_path(aes(x = long, y = lat, group = group), data = outline,
              size=1.5, col="gold")

A: Unfortunately, fortify() from {ggplot2} is no longer recommended by the package authors. The suggested replacement, tidy() from the {broom} package is also no longer recommend by those package authors!
Fortunately, we can recreate Josh O'Brien's answer using the {sf} package. We still rely on some functions from the {raster} package, but these might be replaceable with the {stars} package once a presumed bug is fixed (see https://github.com/r-spatial/sf/issues/1389). Using {stars} might be advantageous if your raster is very large, because converting the raster (or dataframe) to contiguous polygons can be very slow (see https://gis.stackexchange.com/a/313550/114075).
Here's the code (borrowing from Josh O'Brien's setup):
library(raster)
library(rgeos)
library(ggplot2)
library(sf)

df <- data.frame(x = c(295, 300, 305, 310, 295, 300, 305, 310),
                 y = c(310, 310, 310, 310, 315, 315, 315, 315),
                 d = c(2, 2, 2, 1, 2, 1, 1, 1))

## Convert your data.frame to a raster object
r <- raster::rasterFromXYZ(df)

## Extract polygons
pp <- raster::rasterToPolygons(r, dissolve = TRUE)

## Convert SpatialPolygons to a format usable by ggplot2
outline <- sf::st_as_sf(pp)

## Put it all together:
## The polygon "outline" is filled by default so will cover up the
## raster values. Use fill = NA for the geom_sf() to just use the
## gold border color.
ggplot(df) +
  geom_raster(aes(x = x, y = y, fill = d)) +
  geom_sf(data = outline, size = 1.5, col = "gold", fill = NA)

Alternatively, cast the sf object to be a LINESTRING, then there is no need to use the fill = NA argument in the call to geom_sf():
library(raster)
library(rgeos)
library(ggplot2)
library(sf)

df <- data.frame(x = c(295, 300, 305, 310, 295, 300, 305, 310),
                 y = c(310, 310, 310, 310, 315, 315, 315, 315),
                 d = c(2, 2, 2, 1, 2, 1, 1, 1))

## Convert your data.frame to a raster object
r <- raster::rasterFromXYZ(df)

## Extract polygons
pp <- raster::rasterToPolygons(r, dissolve = TRUE)

## Or you can cast to a linestring instead of using a polygon
## and then having to use the fill = NA argument in the
## geom_sf() call
outline <- sf::st_as_sf(pp) %>% st_cast("LINESTRING")

ggplot(df) +
  geom_raster(aes(x = x, y = y, fill = d)) +
  geom_sf(data = outline, size = 1.5, col = "gold")


text:
Q: MySQL Deadlock Batch Size I am writing data to MySQL. There can be a lot of data (30M rows). The default batch size is 1,000 and I'm writing in parallel, so we could have 8 processes, each writing 1,000 records to the DB at any given time,
I run into deadlock issues quite frequently - I'm not entirely sure why, as I am inserting rows, so we should not have a situation where they're accessing the same row.
I have tried to lower the batch size to 500, but the issue still persists.
Do you have any advice please?
Thanks


text:
Q: Android: Unable to get provider I am building a demo app with a content provider. However, this provider cannot be accessed outside the app. I tried to grant the permission mannually, but the app crashes with error message:
java.lang.NullPointerException: Attempt to read from field 'java.lang.String android.content.pm.PackageItemInfo.packageName' on a null object reference
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2379)

Here is my code:
//AndroidManifest.xml
<provider
    android:authorities="com.coffeeshop.android.slicesbasiccodelab"
    android:name="com.coffeeshop.android.slicesbasiccodelab.TemperatureSliceProvider"
    android:grantUriPermissions="true"
    android:exported="true">

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.app.slice.category.SLICE" />
    </intent-filter>
</provider>

// MainActivity.kt
// package com.coffeeshop.android.slicesbasiccodelab
    ...
    // SLICE_VIEWER_PKG = "com.example.mysliceviewer", this is the package name for another app
    // SLICE_URI = "com.coffeeshop.android.slicesbasiccodelab"
    // somewhere when onResume() is finished
    SliceManager.getInstance(this)
        .grantSlicePermission(SLICE_VIEWER_PKG, Uri.parse(SLICE_URI))
    ...
}

Thanks for any help!

A: solved: slice uri need to be prefixed with "content://"


text:
Q: 'id' in where clause is ambiguous I have a table with some fields and some relations with others.
I get the list view with no problem, but when I try to filter the results (using the search feature in flexigrid table) I get:

A Database Error Occurred Error Number:
    1052Column 'id' in where clause is ambiguousSELECT
    gee_job_boards.*, j32e2cb0f.dp_name AS s32e2cb0f FROM
    gee_job_boards LEFT JOIN gee_distribution_partner as j32e2cb0f
    ON j32e2cb0f.id = gee_job_boards.dp_id WHERE id LIKE '%27%'
    ESCAPE '!'  LIMIT 25Filename:
    models/Grocery_crud_model.phpLine Number: 87

Error Number: 1052Column 'id' in where clause is
  ambiguous

how could i solve this ?
thanks

A: You should qualify your id in where clause, for example like this
j32e2cb0f.id LIKE ...


text:
Q: Rails - Check if the active record is not empty and then call relation on it I am fetching data from database using the following statement
@applications = Job.find(params[:job_id]).job_applications

Using the relationships I have setup if I do
@applications.first.job

This will give me the job, application is linked with.
Inside the view I have the following code, this fails if the @applications is empty.
  <% if !@applications.first.job.procedure %>

No procedure has been assigned to this job.

  <% end %>

How can I update the above if statement so it only runs if the @applications is not empty

A: you can check whether association is present or not..
<% if @applications.blank? || @applications.first.job.try(:procedure).blank? %>

No procedure has been assigned to this job.

<% end %>

OR a one liner, a little ugly though
@applications.try(:first).try(:job).try(:procedure).blank?


text:
Q: How to use try/except in a for loop AND append the result to a dataframe I am trying to only get info from an API for only the rows which do not have an error. I have been trying the try/except technique and append the non-error rows to final_dataframe. But when I check final_dataframe, the variable is not saved with the result of the for loop (even though I write .append)
final_dataframe = pd.DataFrame(columns = my_cols)

for i in stocks['Symbol'][:20]:
    try:
        url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={i}&apikey={key}&outputsize=compact'
        data = requests.get(url).json()
        final_dataframe = final_dataframe.append(pd.Series([i,
                                                            data['Time Series (Daily)'][last_refresh]['5. adjusted close'],
                                                            'N/A'],
                                                           index = my_cols),
                                                 ignore_index = True)
    except:
        pass


text:
Q: How can I ignore some elements in  with Perl's HTML::TreeBuilder? I have to parse this HTML:

abc:
asfkjsdg

$para contains the value of the element
. I am using HTML::TreeBuilder.
$para->as_text
gives me
 abc:asfkjsdg

How can I get only:
 asfkjsdg

A: join('', grep { !ref } $para->content_list)

A: my @arr=$para->content_list()
my $text= $arr[1] #First is Element second is scalar
print $text; #$text is scalar


text:
Q: XML to Calc - starting file seems strange My apologies if this seems pretty basic.  This is my first time converting an xml file. The format of the xml file rendered by an Android app seems at odds with what I am seeing in tutorials on youtube or sources I am reading for importing to LibreOffice Calc.  Here is a sample of the data dumped from my phone's call log:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>

<?xml-stylesheet type="text/xsl" href="calls.xsl"?>
<calls count="3">
  <call number="+15555555555" duration="46" date="1401396504704" type="1" readable_date="May 29, 2014 4:48:24 PM" contact_name="(Unknown)" />
  <call number="+15555555555" duration="62" date="1401487115708" type="1" readable_date="May 30, 2014 5:58:35 PM" contact_name="ICE-In Case of Emergency" />
  <call number="+15555555555" duration="51" date="1401559219530" type="1" readable_date="May 31, 2014 2:00:19 PM" contact_name="ICE-In Case of Emergency" />
</calls>

From research I have done, to create an xslt transformation stylesheet the structure of that data has to be more like this:
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>

<?xml-stylesheet type="text/xsl" href="calls.xsl"?>
<calls count="3">
  <call>
    <number>+15555555555</number>
    <duration>46</duration>
    <date>1401396504704</date>
    <type>1</type>
    <readable_date>May 29, 2014 4:48:24 PM</readable_date>
    <contact_name>(Unknown)</contact_name>
  </call>
  <call>
    <number>+15555555555</number>
    <duration>62</duration>
    <date>1401487115708</date>
    <type>1</type>
    <readable_date>May 30, 2014 5:58:35 PM</readable_date>
    <contact_name>ICE-In Case of Emergency</contact_name>
  </call>
  <call>
    <number>+15555555555</number>
    <duration>51</duration>
    <date>1401559219530</date>
    <type>1</type>
    <readable_date>May 31, 2014 2:00:19 PM</readable_date>
    <contact_name>ICE-In Case of Emergency</contact_name>
  </call>
</calls>

Is there something I am missing for working with the xml file as it presently stands?  I attempted to get support for the author of the phone app which creates this xml file but no luck.  Do I have to edit the source to a more appropriate format like the second screenshot?
Thanks for reading.

A: Both XML files that you posted are valid and well-formed. If the question is, which one is in the right format to be handled by the referenced calls.xsl, it's necessary to know the content of the calls.xsl. The first XML that you suppose to be in somehow unusual format is very common - every call node has several attributes - number, duration, date etc., while in the second XML every call node contains number, duration, date etc. as child nodes with the value as text.
Though not sure if this could be the calls.xsl that is used for the transformation, I found this:
http://android.riteshsahu.com/wp-content/uploads/2010/04/calls.xsl.
Just the relevant part from this template:
<xsl:for-each select="calls/call">

      <xsl:if test="@type = 1">
        Incoming
      </xsl:if>
      <xsl:if test="@type = 2">
        Outgoing
      </xsl:if>
      <xsl:if test="@type = 3">
        Missed
      </xsl:if>

      <xsl:value-of select="@number"/>

      <xsl:value-of select="@contact_name"/>

      <xsl:value-of select="@date"/>

      <xsl:value-of select="@readable_date"/>

      <xsl:value-of select="@duration"/>

</xsl:for-each>

For this template the first input XML is the correct version. When this calls.xsl is applied to your first XML, following result - as example only one row - is generated (added indentation for readability):

    Incoming

    +15555555555

    ICE-In Case of Emergency

    1401559219530
May 31, 2014 2:00:19 PM

    51


text:
Q: How to customize individual field in collection, symfony 2 I need to customize how field in collection is drawn.
I have entity A:
class A {
    ...
    /**
     * @ORM\OneToOne(targetEntity="B", cascade={"persist"})
     * @ORM\JoinColumn(name="b_id", referencedColumnName="id")
     */
    private $b;
    ...
}

and entity B:
class B {
    ...
    /**
     * @var array
     *
     * @ORM\Column(name="cs", type="array", nullable=true)
     */
    private $cs;
    ...
}

I have form types:
class AType {
    ...
    ->add(
        'b',
        new BType(),
        array(
            'label' => false
        )
    )
    ...
}

class BType {
    ...
    ->add(
        "cs",
        "collection",
        array(
            "type" => "hidden",
            'label' => false,
            'cascade_validation' => true,
            'allow_add' => true,
            'allow_delete' => true,
            'data' => array(1,2,3),
        )
    ...
}

Now, what I need is to customize how items in cs are drawn. I googled a bit and try few options what to put into my form theme:
{% block _NAME_ %}
{% endblock %}

with NAME
_a_b_cs_widget
_b_cs_widget
_cs_widget
_atype_b_cs_widget
_atype_btype_cs_widget
_btype_cs_widget

and few others, now have worked. Could someone please help me with this?
Thanks

A: Correct is:
_a_b_cs_entry_widget


text:
Q: Rerun window.onload function I have a script that is beeing executed, when loading the page. I would like to rerun the script, when the user gives an input.
I recreated the problem here: JSFiddle
– How can I make it, so that the "Run Again" button actually makes the function run again?
HTML:
<button onclick="timerAll()">
Run Again
</button>

JS:
function timerAll() {
  window.onload = function () {
  alert("alert");
  }
}
timerAll();

A: I solved it, it's actually pretty easy:
HTML
<button onclick="timerAll()">
Run Again
</button>

JS
function timerAll() {
  alert("alert");
}
timerAll();

window.onload = timer()


text:
Q: Fault when attempting to jmp after entering protected mode - assembly bootloader I've been trying all day to figure this out. I'm following a tutorial on writing a bootloader and I'm stuck when it comes to entering protected mode properly. I don't know what I'm doing wrong and I've been googling all day. I'm compiling using NASM
This is the output I get in Bochs dbg:

It is saying that the CPU is indeed entering protected mode, and I am getting errors shortly after that.
This is the second re-writing of this i've done, aiming primarily to get in to protected mode without errors.  I'd love if anyone could tell me what I'm doing wrong.
My code is as follows:
bootloader.asm
global _start

_start:

[bits 16]
[org 0x7c00]

    mov bp, 0x8000
    mov sp, bp

    mov bx, welcomeString
    call print_func

    call print_newline_func

    call switch_to_pm

    jmp $

%include "io.asm"
%include "print.asm"
%include "gdt.asm"

welcomeString:
    db 'Hello. Welcome to OS', 13, 10,0

switch_to_pm:
    cli

    lgdt [gdt_descriptor]
    mov eax, cr0
    or eax, 0x1
    mov cr0, eax

[bits 32]

    jmp CODE_SEG:init_pm

init_pm:

    mov ax, DATA_SEG
    mov ds, ax
    mov ss, ax
    mov es, ax
    mov fs, ax
    mov gs, ax

    mov ebp, 0x90000
    mov esp, ebp

    call BEGIN_PM

BEGIN_PM:
    mov ebx, MSG_PM
    call print_string_pm

    jmp $

MSG_PM:
    db 'success', 0

times 510-($-$$) db 0

dw 0xaa55

io.asm
BOOT_DRIVE:
        db 0

    ReadDisk:                   ; Reads from drive dl amount of sectors to read dh

        push dx                 ; Store dx to stack

        mov ah, 0x02            ; BIOS read sector code
        mov al, dh              ; Read dh sectors
        mov ch, 0x00            ; Select cyl 0
        mov dh, 0x00            ; Select 1st track,
        mov cl, 0x02            ; Select 2nd sector (1st after boot sector)

        int 0x13                ; Read interrupt code

        jc disk_error           ; Jump if error

        pop dx
        cmp dh, al              ; jump if sectors expected != sectors read
        jne disk_error

        ret

    errorString:
        db 'Disk Read Error.',13,10,0

    disk_error:
        mov bx, errorString
        call print_func
    ret

gdt.asm
gdt_start:
    gdt_null:       ; null descriptor
        dd 0x0
        dd 0x0

    gdt_code:           ; the code segment descriptor
                        ; base =0x0 , limit =0 xfffff ,
                        ; 1st flags : ( present )1 ( privilege )00 ( descriptor type )1 -> 1001 b
                        ; type flags : ( code )1 ( conforming )0 ( readable )1 ( accessed )0 -> 1010 b
                        ; 2nd flags : ( granularity )1 (32 - bit default )1 (64 - bit seg )0 ( AVL )0 -> 1100 b
        dw 0xffff       ; Limit (bits 0-15)
        dw 0x0          ; Base (bits 0 - 15)
        db 0x0          ; Base (bits 16 - 23)
        db 10011010b    ; 1st flags, type flags
        db 11001111b    ; 2nd flags, limit (bits 16-19)
        db 0x0          ; Base (bits 24-31)

    gdt_data:           ; the data segment descriptor
                        ; Same as code segment except for the type flags :
                        ; type flags : ( code )0 ( expand down )0 ( writable )1 ( accessed )0 -> 0010 b
        dw 0xffff       ; Limit (bits 0-15)
        dw 0x0          ; Base (bits 0-15)
        db 0x0          ; Base (bits 16-23)
        db 10010010b    ; 1st flags, type flags
        db 11001111b    ; 2nd flags
        db 0x0          ; Base (bits 24-31)

    gdt_end:            ; Put this label to calculate size of GDT

gdt_descriptor:
    dw gdt_end - gdt_start - 1      ; GDT size, always 1 less than true size
    dd gdt_start                    ; start address of GDT

CODE_SEG equ gdt_code - gdt_start
DATA_SEG equ gdt_data - gdt_start

print.asm
print_func:
    push bx
        mov ah, 0x0e
        ;add bx, 0x7c00                 ; calculate correct address
        print_loop:
            cmp byte [bx], 0            ; if char at bx == 0, jump to exit.
            je print_exit
            mov al, [bx]                ; move char at bx into al
            int 0x10                    ; print
            inc bx                      ; increment bx
            jmp print_loop              ; loop to start of func
            print_exit:
            pop bx
                ret

print_newline_func:
    push ax
    mov ah, 0x0e
    mov al, 10
    int 0x10
    mov al, 13
    int 0x10
    pop ax
    ret

print_hex_func:
    push ax
    push bx
    push cx

    mov ah, 0x0e

    mov al, '0'
    int 0x10
    mov al, 'x'
    int 0x10                    ; print 0x

    ;add bx, 0x7c00

    mov cx, [bx]
    shr cx, 12
    call PrintAsciiFromHex

    mov cx, [bx]
    shr cx, 8
    call PrintAsciiFromHex

    mov cx, [bx]
    shr cx, 4
    call PrintAsciiFromHex

    mov cx, [bx]
    call PrintAsciiFromHex

    pop ax
    pop bx
    pop cx

    ret

PrintAsciiFromHex:
    shl cx, 12
    shr cx, 12
    cmp cx, 9
    jg Add55
    add cx, 48
    jmp Skip
    Add55:
        add cx, 55
    Skip:
    mov al, cl
    int 0x10
    ret

AddressPointer:
    dw 0

PrintAddress:                   ; Moves address of bx into value of AddressPointer
    mov [AddressPointer], bx    ; Passes address of address pointer into bs
    mov bx, AddressPointer      ; prints value of address pointer, therefore printing address
    call print_hex_func
    ret

[bits 32]

                                    ; Define some constants
VIDEO_MEMORY equ 0xb8000
WHITE_ON_BLACK equ 0x0f

                                    ; prints a null - terminated string pointed to by EDX
print_string_pm:
    pusha
    mov edx, VIDEO_MEMORY               ; Set edx to the start of vid mem.
    print_string_pm_loop :
        mov al , [ ebx ]                    ; Store the char at EBX in AL
        mov ah , WHITE_ON_BLACK             ; Store the attributes in AH
        cmp al , 0                          ; if (al == 0) , at end of string , so
        je print_string_pm_done             ; jump to done
        mov [edx] , ax                      ; Store char and attributes at current
                                            ; character cell.
        add ebx , 1                         ; Increment EBX to the next char in string.
        add edx , 2                         ; Move to next character cell in vid mem.

        jmp print_string_pm_loop            ; loop around to print the next char.
    print_string_pm_done :
        popa
        ret                                 ; Return from the function

A: Solved by returning to [bits 16] after the 32 bit function in print.asm and moving jmp to above the change to [bits 32]


text:
Q: Snowflake masking policy with external function support on GCP I want to externally tokenize some columns before loading to snowflake. Later I want to use a masking policy to de-tokenize the column using an external function. Is this possible to be done in snowflake on gcp or is this currently supported only on aws?

A: Yes, external functions are supported on both platforms


text:
Q: Gerund and infinitives I hear everyday people use gerund and infinitive with nouns and pronouns instead of simple verbs. For Example: "Instead of me calling you ........ "or, "The minister to resign next month". These sentences confuse me, because I learned that infinitives and gerunds are used with verbs as nouns, subjects, or objects; but I never learned anywhere that gerunds and infinitives are used with nouns and pronouns. Please help!

A: Gerunds can take objects where they make sense.

Walking makes us healthier.
Walking the dog makes the dog healthier.
Giving is required by the church
Giving 20 dollars to the IRS is required by law.

Object or possessive pronouns can be put in front of -ing words to identify the "subject".  I think possibly in the case of using an object pronoun, the -ing word technically becomes a participial adjective, but I'm not sure.

I walked to be healthier.
Me walking makes me healthier, but probably not someone with a broken foot.
I gave my sister two dollars
Me giving my sister two dollars resulted in my brother getting jealous.


text:
Q: How to give icon value color change in if-else condition in flutter? How to change icon color in an if-else statement in flutter
Icon(_image == null ? MdiIcons.imageSearch : MdiIcons.checkBold,size: 35)

A: You can change color in Icon color parameter
colors : _image == null ?Colors.red : Colors.blue
Icon(_image == null ? MdiIcons.imageSearch : MdiIcons.checkBold,size: 35,color : _image == null ?Colors.red : Colors.blue)

A: use this:
Icon(Icons.add , color: _image == null ? Colors.red : Colors.blue,)


text:
Q: How can I validate the length only when the field is not empty? I have one text box, which I want to check for min-length, but it should check only when some text is there.
If someone has left that textbox empty, then it should not check for min-length.
Any suggestions?

A: If you mean, that the text box can be left empty, then this may be your answer:
$("#your_text_box").rules("add", {
   required: false, // this means the field can be left empty
   minlength: 2
});

Using this, validator will skip this text box if it is empty.
Hope this helps!

A: var yourLimit = 1;
var myLength = $("#eTextBox").val().length;
    if(myLength>=yourLimit){
       //do whatever you want
    }

Hope the above code will help you.


text:
Q: Addition of two multivariate Gaussian exponents This equation in image occurs while evaluating multivariate Gaussian distributions for log likelihood.
I am short of proper linear algebra tools of how the first equation is reduced to the below one in the image.
Here we are using 2 different Gaussians with different mean, but same covariance. Can someone help me derive this with reference to matrix identities that are used?
Update:
The equation is:
$$\frac{1}{2}\left(\mathbf{x}-\boldsymbol{\mu}_{0}\right)^{T} \Sigma^{-1}\left(\mathbf{x}-\boldsymbol{\mu}_{0}\right)-\frac{1}{2}\left(\mathbf{x}-\boldsymbol{\mu}_{1}\right)^{T} \Sigma^{-1}\left(\mathbf{x}-\boldsymbol{\mu}_{1}\right)$$
It can be reduced to $\langle\mathbf{w}, \mathbf{x}\rangle+b$.
Where, $\mathbf{w}=\left(\boldsymbol{\mu}_{1}-\boldsymbol{\mu}_{0}\right)^{T} \Sigma^{-1}$ and $b=\frac{1}{2}\left(\boldsymbol{\mu}_{0}^{T} \Sigma^{-1} \boldsymbol{\mu}_{0}-\boldsymbol{\mu}_{1}^{T} \Sigma^{-1} \boldsymbol{\mu}_{1}\right)$

A: Because the covariance matrix $\ \Sigma\ $ and its inverse $\ \Sigma^{-1}\ $  are symmetric, then
$$
\left(\mathbf{x}-\boldsymbol{\mu}_i\right)^T \Sigma^{-1} \left(\mathbf{x}-\boldsymbol{\mu}_i\right)=\mathbf{x}^T \Sigma^{-1} \mathbf{x}-2\boldsymbol{\mu}_i^T\Sigma^{-1} \mathbf{x}+ \boldsymbol{\mu}_i^T\Sigma^{-1} \boldsymbol{\mu}_i\ .
$$
Thus,
\begin{align}
\left(\mathbf{x}-\boldsymbol{\mu}_0\right)^T \Sigma^{-1} &\left(\mathbf{x}-\boldsymbol{\mu}_0\right) -\left(\mathbf{x}-\boldsymbol{\mu}_1\right)^T \Sigma^{-1} \left(\mathbf{x}-\boldsymbol{\mu}_1\right)\\
&=-2 \boldsymbol{\mu}_0^T\Sigma^{-1} \mathbf{x}+ \boldsymbol{\mu}_0^T\Sigma^{-1} \boldsymbol{\mu}_0+ 2 \boldsymbol{\mu}_1^T\Sigma^{-1} \mathbf{x}-\boldsymbol{\mu}_1^T\Sigma^{-1} \boldsymbol{\mu}_1\\
&=2\left(\boldsymbol{\mu}_1-\boldsymbol{\mu}_0\right) \Sigma^{-1} \mathbf{x}+ \boldsymbol{\mu}_0^T\Sigma^{-1} \boldsymbol{\mu}_0-\boldsymbol{\mu}_1^T\Sigma^{-1} \boldsymbol{\mu}_1\\
&=2\left(\langle\mathbf{w},\mathbf{x}\rangle+b\right)\ .
\end{align}


text:
Q: Responsive Datagrid vertically when maximize the window I'm trying to set the height of the rows in the datagrid dynamically , I mean the height of the datagrid should be based on the data binding ( from the database ) , I don't have a problem with columns , they are responsive when I maximize the window the columns increase and take the available space.
The problem now is with rows so what I need exactly is when I maximize the Window , the datagrid should take the available space vertically ( increase the font size of the headers and the data shown in the datagrid).
Is there any possibility to make the rows of the datagrid responsive ?
Xaml Code:
<DockPanel Grid.Row="2" Width="auto" MinWidth="800" Height="auto" >
   <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto">
      <DataGrid  VerticalScrollBarVisibility="Auto" Margin="20" Height="auto" Width="auto" GridLinesVisibility="All"  ItemsSource="{Binding GridModel}" x:Name="UserGrid" MinWidth="1200"
                 VerticalAlignment="Top" FlowDirection="RightToLeft"
                 AutoGenerateColumns="False" CanUserAddRows="false" MinHeight="800"
                 Grid.RowSpan="2" RenderTransformOrigin="0.497,0.551" MouseDoubleClick="UserGrid_MouseDoubleClick" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Hidden">

         <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
               <Setter Property="Height" Value="Auto"/>
            </Style>
         </DataGrid.RowStyle>
         <DataGrid.Resources>

            <Style  x:Key="DisableSelection" TargetType="DataGridCell">
               <!--  <Setter Property="Focusable" Value="False"/> -->
               <Setter Property="Background" Value="Transparent"/>
               <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
               <Setter Property="BorderBrush" Value="Transparent"/>
            </Style>
         </DataGrid.Resources>
         <DataGrid.Columns>

            <DataGridCheckBoxColumn Header="choose" x:Name="choose" Binding="{Binding isChecked}" >

               <DataGridCheckBoxColumn.CellStyle>

                  <Style  TargetType="DataGridCell"  BasedOn="{StaticResource {x:Type DataGridCell}}">
                     <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                           <Setter Property="IsEditing" Value="True"/>
                        </Trigger>
                     </Style.Triggers>
                     <EventSetter Event="CheckBox.Checked" Handler="OnChecked"/>
                     <EventSetter Event="CheckBox.Unchecked" Handler="OnChecked"/>
                     <Setter Property="Background" Value="Transparent" />

                  </Style>

               </DataGridCheckBoxColumn.CellStyle>
            </DataGridCheckBoxColumn>

            <DataGridTextColumn Width="*" CellStyle="{StaticResource DisableSelection}" Header="IDw" x:Name="workIdcl" Binding="{Binding wId}" IsReadOnly="True"  />
            <DataGridTextColumn Width="*" CellStyle="{StaticResource DisableSelection}" Header="subName" x:Name="subscriberNamecl" Binding="{Binding subName}" IsReadOnly="True"/>
            <DataGridTextColumn Width="*" CellStyle="{StaticResource DisableSelection}" Header="UserName" x:Name="patientNamecl"   Binding="{Binding UserName}" IsReadOnly="True" />

         </DataGrid.Columns>

      </DataGrid>
   </ScrollViewer>

</DockPanel>


text:
Q: What is the IIS Express icon meant to be? Using IIS Express as my development server in Visual Studio 2012, I notice a rather odd-looking silvery-blue icon appear in my system tray.  It turns out this is the IIS Express icon, as shown the the following image (the IIS Express icon is on the left):

What is this icon supposed to represent?  For about a week I thought it was a stylised S, now it looks more like a tin can being crushed by a robot hand.

A: The icon you mention is the IIS Express System Tray application icon.
If you were to debug or run a Web Site or Web Application from the Visual Studio IDE, this icon will be displayed in your System Tray; you can right-click this icon and gain access to further features to stop these web sites and more.
IIS Express is somewhat similar to the Visual Studio Web Server in that it runs the web site/application under a random port on localhost. IIS Express is beneficial to use because incorporates the main Windows IIS Features without the need of requiring the Windows IIS Feature to be installed on the developer's computer; most corporates don't like to have the Windows IIS Feature installed because it represents a security risk to the company and requires more corporate management.
References
http://www.iis.net/learn/extensions/introduction-to-iis-express


text:
Q: Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService after upgrade to ASP.NET Core 2.0 I updated a project to ASP.NET Core 2 today and I get the following error:

Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService

I have the following registration:
services.AddSingleton<IActiveUsersService, ActiveUsersService>();
services.AddScoped<IMongoDbContext, MongoDbContext>();
services.AddSingleton(option =>
{
   var client = new MongoClient(MongoConnectionString.Settings);
   return client.GetDatabase(MongoConnectionString.Database);
})

public class MongoDbContext : IMongoDbContext
{
   private readonly IMongoDatabase _database;

   public MongoDbContext(IMongoDatabase database)
   {
      _database = database;
   }

   public IMongoCollection<T> GetCollection<T>() where T : Entity, new()
   {
      return _database.GetCollection<T>(new T().CollectionName);
   }
}

public class IActiveUsersService: ActiveUsersService
{

   public IActiveUsersService(IMongoDbContext mongoDbContext)
   {
      ...
   }
}

Why DI can't consume the service? All works fine for ASP.NET Core 1.1.

A: You can also add
.UseDefaultServiceProvider(options =>
                    options.ValidateScopes = false)

before .Build() in Program.cs file to disable the validation.
Try this only for development testing, ActiveUsersService is singleton and has a larger lifetime than MongoDbContext which is scoped and will not get disposed.

A: There is another way to approach this issue, and it is by adding the MongoDbContext to the DI as AddTransient like this:
services.AddSingleton<IActiveUsersService, ActiveUsersService>();
services.AddTransient<IMongoDbContext, MongoDbContext>();

The meaning of using this approach is that you'll end up with an instance of MongoDbContext for each Singleton class you have using it.
For example, if you have 10 Singleton classes using MongoDbContext you'll have 10 instances of it, but it's instead of creating an instance for every request.
See this for reference: Cannot Consume Scoped Service From Singleton – A Lesson In ASP.net Core DI Scopes

A: There are important differences between Scoped and Singleton services. The warning is there to bring this to light, and turning it off or switching around lifetimes indiscriminately to make it go away won't solve the problem.
Scoped services are created from an IServiceScope. One of its most important purposes is to ensure that any IDisposable services which are created in that scope are properly disposed when the scope itself is.
In ASP.NET Core, a service scope is automatically created for you on each incoming request, so you ordinarily don't need to worry about this. However, you can also create your own service scope; you just need to dispose of it yourself.
One way to do this is to:

*

*make your singleton service IDisposable,

*inject IServiceProvider,

*create and store an IServiceScope scope using the IServiceProvider.CreateScope() extension method,

*use that scope to create the the scoped service you need,

*dispose the service scope in the Dispose method.

services.AddSingleton<IActiveUsersService, ActiveUsersService>();
services.AddScoped<IMongoDbContext, MongoDbContext>();
services.AddSingleton(option =>
{
   var client = new MongoClient(MongoConnectionString.Settings);
   return client.GetDatabase(MongoConnectionString.Database);
})

public class MongoDbContext : IMongoDbContext
{
   private readonly IMongoDatabase _database;

   public MongoDbContext(IMongoDatabase database)
   {
      _database = database;
   }

   public IMongoCollection<T> GetCollection<T>() where T : Entity, new()
   {
      return _database.GetCollection<T>(new T().CollectionName);
   }
}

public class ActiveUsersService: IActiveUsersService, IDisposable
{
   private readonly IServiceScope _scope;

   public ActiveUsersService(IServiceProvider services)
   {
      _scope = services.CreateScope(); // CreateScope is in Microsoft.Extensions.DependencyInjection
   }

   public IEnumerable<Foo> GetFooData()
   {
       using (var context = _scope.ServiceProvider.GetRequiredService<IMongoDbContext>())
       {
           return context.GetCollection<Foo>();
       }
   }

   public void Dispose()
   {
       _scope?.Dispose();
   }
}

Depending on how you're using these and the scoped services you're consuming, you could instead do one of the following:

*

*create a single instance of the scoped service and use it for the life of the singleton; or

*store a reference to the (injected) root IServiceProvider, use it to create a new IServiceScope inside a using block every time you need a scoped service, and let the scope get disposed when the block exits.

Just keep in mind that any IDisposable services created from an IServiceScope will get automatically disposed when the scope itself does.
In short, don't just change around the lifetimes of your services to "make it work"; you still need to think about those and be sure they get disposed properly. ASP.NET Core handles the most common cases automatically; for others, you just need to do a bit more work.
Ever since C# 1.0 we have had using() blocks to ensure resources are disposed correctly. But using() blocks don't work when something else (the DI service) is creating those resources for you. That's where Scoped services come in, and using them incorrectly will lead to resource leaks in your program.

A: You can't use a service with a smaller lifetime. Scoped services only exist per-request, while singleton services are created once and the instance is shared.
Now only one instance of IActiveUsersService exists in the app. But it wants to depend on MongoDbContext, which is Scoped, and is created per-request.
You will have to either:

*

*Make MongoDbContext a Singleton, or

*Make IActiveUsersService Scoped, or

*Pass MongoDbContext into the user service as a function argument

A: Since some input parameters of the constructor are not interface, engine can not inject an object into the class.
use AddScoped rather than AddSingleton, it maybe resolves the issue.

A: A long Lifetime service can't request a shorter Lifetime service..
The reason is that the longer lifetime service will use the shorter lifetime service for longer time than it was specified.
The instance of shorter service can't be updated as often as needed.

The following options are allowed:
          | Transient | Scoped | Singleton
-------------------------------------------
Transient |     +     |    +   |     +
-------------------------------------------
Scoped    |     -     |    +   |     +
-------------------------------------------
Singleton |     -     |    -   |     +

This exception is only shown for Development environment and not Production


text:
Q: Perl web scraper, retrieve data from text inside a script tag So far I was using perl to obtain data from web pages using HTML::TreeBuilder. This was OK when the data was contained inside meta or div tags; but now I stumbled upon a new structure that I don't know how to crawl, though it looks pretty trivial.
<html lang="en">
    <body>
        <script type="text/javascript">
            panel.web.bootstrapData = {
                "data": {
                    "units": "kW",
                    "horsePower": 100.00
                }
            };
        </script>
    </body>
</html>

The example displays the relevant part of the content that I get from the web. I would like to get the values for units and horsePower.
Fragments of the code I was using so far:
use strict;
use LWP::UserAgent;
use HTTP::Request::Common;
use HTML::TreeBuilder;

[...]

$reply = $ua->get($url, @ns_headers);

# printing the reply would get us the first code snippet.
print $reply->content;

unless ($reply->is_success) {
    [...]
}

my $tree = HTML::TreeBuilder->new_from_content($reply->content);
my @unit_array = $tree -> look_down(_tag=>'meta','itemprop'=>'unit');
my $unit = $unit_array[0]->attr('content');

[...]

Any one knows how to obtain the relevant data and whether I should use something other than HTML::TreeBuilder for that matter? I haven't found any similar cases searching through stackoverflow and the web.

A: You are basically on the right path. But HTML::TreeBuilder doesn't understand anything about JavaScript.
The approach:

*

*find the <script> nodes

*extract the JSON content from those nodes

*

*NOTE: this will be easy for the example given, but will require more finesse for more complicated <script> content

*The escape \; in the regex isn't really required, but the SO syntax highlighter gets confused without it

*use JSON to decode the string to Perl data structures

*access those data structures in your script

A first rough solution without error checking. I left some debugging lines, commented out, in the code so that you can trace what each step is doing:
#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper;
use HTML::TreeBuilder;
use JSON;

my $decoder = new JSON;

my $tree       = HTML::TreeBuilder->new_from_file(\*DATA);
#$tree->dump;
my @scripts    = $tree->look_down(_tag => 'script');
#$scripts[0]->dump;
# NOTE 1: ->as_text() *DOES NOT* return <script> content!
# NOTE 2: ->as_HTML() probably doesn't work for all cases, i.e. escaping
my $javascript = ($scripts[0]->content_list())[0];
#print "${javascript}\n";
my($json)      = $javascript =~ /(\{.+\})\;/s;
#print "${json}\n";
my $object     = $decoder->decode($json);

print Dumper($object);
print "FOUND: units: ", $object->{data}->{units},
      " horsepower: ",  $object->{data}->{horsePower}, "\n";

# IMPORTANT: $tree needs to be destroyed by hand when you're done with it!
$tree->delete;

exit 0;

__DATA__
<html lang="en">
    <body>
        <script type="text/javascript">
            panel.web.bootstrapData = {
                "data": {
                    "units": "kW",
                    "horsePower": 100.00
                }
            };
        </script>
    </body>
</html>

Test run:
$ perl dummy.pl
$VAR1 = {
          'data' => {
                      'horsePower' => '100',
                      'units' => 'kW'
                    }
        };
FOUND: units: kW horsepower: 100


text:
Q: Image Slider using JavaFX Error Syntax error on token(s), misplaced construct(s) package javafx;

import java.util.ArrayList;
import java.util.List;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ImageSlide extends Application {

    // Width and height of image in pixels
    private final double IMG_WIDTH = 600;
    private final double IMG_HEIGHT = 300;

    private final int NUM_OF_IMGS = 3;
    private final int SLIDE_FREQ = 4; // in secs

    @Override
    public void start(Stage stage) throws Exception {
        //root code
        StackPane root = new StackPane();

        Pane clipPane = new Pane();
        // To center the slide show incase maximized
        clipPane.setMaxSize(IMG_WIDTH, IMG_HEIGHT);
        clipPane.setClip(new Rectangle(IMG_WIDTH, IMG_HEIGHT));

        HBox imgContainer = new HBox();
        //image view
        ImageView imgGreen = new ImageView(new Image(getClass()
            .getResourceAsStream("\\Merged1.pngg")));
        ImageView imgBlue = new ImageView(new Image(getClass()
            .getResourceAsStream("\\Merged2.png")));
        ImageView imgRose = new ImageView(new Image(getClass()
            .getResourceAsStream("\\Merged3.png")));

        imgContainer.getChildren().addAll(imgGreen, imgBlue, imgRose);
        clipPane.getChildren().add(imgContainer);
        root.getChildren().add(clipPane);

        Scene scene = new Scene(root, IMG_WIDTH, IMG_HEIGHT);
        stage.setTitle("Image Slider");
        stage.setScene(scene);
        startAnimation(imgContainer);
        stage.show();
        }
    //start animation
        private void startAnimation(final HBox hbox) {
        //error occured on (ActionEvent t) line
        //slide action
            EventHandler<ActionEvent> slideAction = (ActionEvent t) {
                TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
                trans.setByX(-IMG_WIDTH);
                trans.setInterpolator(Interpolator.EASE_BOTH);
                trans.play();
            };
     //eventHandler
            EventHandler<ActionEvent> resetAction = (ActionEvent t) {
                TranslateTransition trans = new TranslateTransition(Duration.seconds(1), hbox);
                trans.setByX((NUM_OF_IMGS - 1) * IMG_WIDTH);
                trans.setInterpolator(Interpolator.EASE_BOTH);
                trans.play();
            };

            List<KeyFrame> keyFrames = new ArrayList<>();
            for (int i = 1; i <= NUM_OF_IMGS; i++) {
                if (i == NUM_OF_IMGS) {
                    keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), resetAction));
                } else {
                    keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), slideAction));
                }
            }
//add timeLine
            Timeline anim = new Timeline(keyFrames.toArray(new KeyFrame[NUM_OF_IMGS]));

            anim.setCycleCount(Timeline.INDEFINITE);
            anim.playFromStart();
        }
    //call main function
        public static void main(String[] args) {
            launch(args);
        }
    }

A: The lines
EventHandler<ActionEvent> slideAction = (ActionEvent t) {
                TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
                trans.setByX(-IMG_WIDTH);
                trans.setInterpolator(Interpolator.EASE_BOTH);
                trans.play();
            };

should be
EventHandler<ActionEvent> slideAction = (ActionEvent t) -> {
                TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
                trans.setByX(-IMG_WIDTH);
                trans.setInterpolator(Interpolator.EASE_BOTH);
                trans.play();
            };

Note the only addition ->. Which IDE are you using?


text:
Q: Login.aspx not using expected SQL Membership Provider database Any help appreciated!
What is needed so that the Login.aspx page is using the database as shown through the MyDatabaseConnection

*

*I created an ASP.NET Web Forms application

*Configured SQL Server Membership Provider (or so I thought) in the main web.config.
Added MyDatabaseConnection:
<connectionStrings>
    <add name="DefaultConnection"
         providerName="System.Data.SqlClient"
         connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-VideoProject-20131115191757;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-VideoProject-20131115191757.mdf"/>
    <add name="MyDatabaseConnection"
         providerName="System.Data.SqlClient"
         connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=videolibrary;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\videolibrary.mdf"/>
</connectionStrings>

MyDatabaseConnection points to the desired database that already has the tables, users and passwords configured (not by me).
<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" defaultUrl="~/"/>
</authentication>

...

<membership defaultProvider="DefaultMembershipProvider">
    <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="MyDatabaseConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
    </providers>
</membership>

*Created Secure.aspx in Secure folder.

*Created web.config in the Secure folder with
<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>

*Using Project\ASP.NET Configuration, I added a user TestAccount.

*Added a link in the application that points to Secure.aspx.
When debugging the application, I select the link that points to Secure.aspx. Through login.aspx, I can login as TestAccount and the Secure.aspx page is displayed as expected.
When I use a login user/password from the MyDatabaseConnection database, it fails. That is, login is unsuccessful. It is not looking at this database but I do not know what else  is needed for the login.aspx page to use it?
After this, I tried adding AspNetSqlMembershipProvider in the following of the main web.config:
    <membership defaultProvider="DefaultMembershipProvider">
        <providers>
            <add name ="AspNetSqlMembershipProvider"
             type="System.Web.Security.SqlMembershipProvider"
             connectionStringName="MyDatabaseConnection"
             applicationName="/" />
            <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="MyDatabaseConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
        </providers>
    </membership>

but received the following error immediately after trying to login:

Parser Error Message: The entry 'AspNetSqlMembershipProvider' has already been added.
  Source Error:
  Line 31:
  Line 32:
  Line 33:
  Line 34:              type="System.Web.Security.SqlMembershipProvider"
  Line 35:              connectionStringName="MyDatabaseConnection"

I searched for AspNetSqlMembershipProvider elsewhere (since said already used) within the web.config and did not see it. Note: Unfortunately, I could not use code formatting adequately due to issues using it.
Thanks,
Buck


text:
Q: iOS: How to define the intent file for no input action shortcuts I want developer a shortcuts action just like this and roomname is i edit in my app
enter image description here
so i define the intents file like this
enter image description here
and my donation code is like this
    LightControlIntent *intent = [[LightControlIntent alloc] init];
    [intent setROOMNAME:@"MY BIG BIG HOUSE"];

    INInteraction *recation = [[INInteraction alloc] initWithIntent:intent response:nil];
    [recation donateInteractionWithCompletion:^(NSError * _Nullable error) {
        if(!error) {
            NSLog(@"donation success");
        }else {
            NSLog(@"donation fail %@",error.localizedDescription);
        }
    }];

but it doesn't work ,this is the Xcode print,
donation fail Cannot donate interaction with intent that has no valid shortcut types: <INInteraction: 0x6000013bc9c0> {
    intent = <INIntent: 0x6000019b3f00> {
    };
    dateInterval = <_NSConcreteDateInterval: 0x6000037ede60> (Start Date) 2020-12-10 06:49:53 +0000 + (Duration) 0.000000 seconds = (End Date) 2020-12-10 06:49:53 +0000;
    intentResponse = <null>;
    groupIdentifier = <null>;
    intentHandlingStatus = Unspecified;
    identifier = 4FEC8BA0-6E7E-4605-8246-7B06833A7863;
    direction = Unspecified;
} for intent <LightControlIntent: 0x6000019a2880> {
    rOOMNAME = MY BIG BIG HOUSE;
}

i try to define the "no parameters" in suggestions section,then i can donation success,but it can't get ROOMNAME.please Help!

A: i have figure this out, just change your parameter to lowcase ,then it works