text:
Q: Divergence theorem and discontinuous vector fields in electrostatics Wikipedia defines Gauss Divergence Theorem for a continuously differentiable vector field; but in many idealized physical situations, we use it for non-differentiable fields. For example, the electric field about a conductor is zero inside the conductor, but right at the boundary, it has a non-zero value (just like a step-function).
This may lead to erroneous results, and I want to check this idea by the means of an example.
Assume a sphere of volume $\mathbf{V}$, with volume and surface charge densities:
$$\rho_b = - \nabla \cdot \mathbf{P} \ on \ V$$
$$\sigma_b = \mathbf{P} \cdot \mathbf{ \hat n } \ on \ \Sigma V$$
Here, $\mathbf{P}$ is a vector field which has some non-zero value on $\Sigma \mathbf{V}$ and in $\mathbf{V}$, but is zero for all points out side the boundary of the sphere, i.e., it is a discontinuous field.
As can be verified, the total bound charge is zero.
Thus, if we assume a Gaussian shell $\mathbf{S}$ around this sphere, whose radius is slightly bigger than the sphere, but tending to the radius of the sphere, then we can apply Gauss's law and see that:
$$\int_S \mathbf{E} \cdot d \mathbf{a} = \frac {q_{enc}} {\epsilon_0}$$
which simplifies by using the fact that:
$$\mathbf{E} \cdot \mathbf{\hat n} = E_{||} = \frac {\sigma_b} {\epsilon_0}$$
where $\sigma_b$ is a function of the vector $\mathbf{r'}$ which lies on the boundary of the sphere. Since, since $q_{enc} = 0$, thus:
$$\int_S E_{||} da = \int_S \frac {\sigma_b} {\epsilon_0} da = 0$$
But since any two shells are isomorphic in Euclidean space, hence, we can replace $da$ with $\lambda da'$, where $\lambda$ is a scaling factor. This scaling factor embodies the fact that we can project an area element $da$ from the shell to the boundary of the sphere, and we'll get a scaled down projection area element $da'$ on the surface of the sphere. The factor $\lambda \to 1$ as $\mathbf{S} \to \Sigma \mathbf{V}$.
Now, we can complete the integration to get:
$$\frac {\lambda} {\epsilon_0} \int_{\Sigma V} \sigma_b da' = 0$$
and thus:
$$\int_{\Sigma V} \sigma_b \  da' = 0$$
This implies that the total surface charge is zero, which isn't generally true.
So where did I make a wrong assumption? Or is this inconsistency because the field $\mathbf{P}$ is discontinuous?
$\bf{UPDATE:}$
This question has been answered by user $\bf{Kyson}$:
He pointed out that I was wrongly assuming $\vec{E}_{out}⋅n̂  = E_{||} = \frac {\sigma_b} {\epsilon_0}$, whereas this is correct only for a conductor. Since in my case, we don't have a conductor, the correct relation is:
$$(\vec{E}_{out} - \vec{E}_{in})⋅n̂  = \frac {σ_b} {ϵ_0}$$
which solves the inconsistency.


text:
Q: When during the slug build process does my rails app have access to the ENV variables set by Heroku? I am looking to load a file into my rails cache with a cache key based on any of the possible values set by the Heroku Labs: Dyno Metadata addon (https://devcenter.heroku.com/articles/dyno-metadata).
Within that article, I am looking for a unique identifier which is available early within the slug build process.

HEROKU_RELEASE_CREATED_AT:       2015-04-02T18:00:42Z
HEROKU_RELEASE_VERSION:          v42
HEROKU_SLUG_COMMIT:              2c3a0b24069af49b3de35b8e8c26765c1dba9ff0

These are the three that are of some interest to me (example data above). During my asset pre-compilation step, I am dependent on a unique value which I have decided to use any of the 3 above. This step is done before my rails app is operational.
Initially I tried HEROKU_RELEASE_VERSION however I noticed that it is not set until the slug build process is completed which means during my asset pre-compilation step, it is nil.
I am then trying HEROKU_SLUG_COMMIT to see if this is known before asset pre-compilation. Is this correct? From some initial testing, it seems to work correctly (it is at least known before asset pre-compilation), however I would like to know the correct order that these are set.
If this is not an earlier value that is available within ENV[], what would be a better suggestion?
====== UPDATE:
I have been playing around with the configuration below with the values:

HEROKU_RELEASE_CREATED_AT:       2015-04-02T18:00:42Z
HEROKU_RELEASE_VERSION:          v42
HEROKU_SLUG_COMMIT:              2c3a0b24069af49b3de35b8e8c26765c1dba9ff0

I have noticed that before building the assets, those above values do not change pre-build but rather post-build. Below, I have the resulting output below. As you can see, the current deploy is 2583508 but ENV['HEROKU_SLUG_COMMIT'] returns 8318914 during the build process until the application has finished, then ENV['HEROKU_SLUG_COMMIT'] is updated to 2583508.
=== sample-app Releases - Current: v356
v356  Deploy 2583508   email@gmail.com    2017/04/26 20:05:51 -0400 (~ 40s ago)
v355  Deploy 8318914   email@gmail.com    2017/04/26 19:51:33 -0400 (~ 14m ago)
v354  Deploy c054f1e   email@gmail.com    2017/04/26 19:40:42 -0400 (~ 25m ago)

BROWSER RESTRICTIONS SLUG COMMIT: 83189141e4e45643bf71d9aa78604e479ea210f1

Is there a way to uniquely know the current build before actually building? Maybe not using the heroku lab addon?

A: I have received a response from Heroku support which seems to fix the needs that I am looking for.
Heroku's response:

Unfortunately, at this point, our dyno metadata lab flags and the
  config vars made available during the build don't entirely match up.
  During the build, you can use the SOURCE_VERSION environment variable,
  which will be the commit hash. Then, at runtime, you can use
  HEROKU_SLUG_COMMIT to get the same value.
The reason behind this difference is mostly a difference of context.
  Naming that variable HEROKU_SLUG_COMMIT during build wouldn't make
  sense, as it's not a slug yet.
Since we will never set both config vars, you should be able to use
  any of them, and fallback to the other if it's not set.

My current implementation now is:
ENV["SOURCE_VERSION"] || ENV['HEROKU_SLUG_COMMIT'] in that order. This works for me.

A: I have solved this for myself by using a deploy script and using the heroku-cli tool to update my app with the new commit hash before pushing the code:
deploy.sh
...
heroku config:set APP_VERSION=<commit hash> --app <your app name>
git push heroku master
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wearing Winter Bash hats although Winter Bash is over? It's still cold outside.
Look at my profile picture, I don't have long hair. Is there anything wrong if I put on a Winter Bash hat, although the Winter Bash period has ended?
Technically, I have taken a screenshot of my avatar wearing a hat and I could just upload that screenshot as my avater image. I just wanted to know if this is considered as abuse. I don't want to affront anybody.

A: You can upload your avatar with wearing the hat.
It won't be considered as abuse.

A: Yeah, feel free to use any hats in your avatar that you have saved from the event. Near the end, Balpha had this interesting idea of making a button that lets you create a new avatar based on your current avatar and the hat you were currently wearing, I think that would be a rather neat feature for next year, in my humble opinion :)
I also really look forward to that time of year every year, ever since the first Winter Bash - it's just an amazing amount of fun and I frequently smile while recalling it.


text:
Q: Got error when run async select with EF Core dbcontext public class Person
{
    [Key]
    public Guid Id { get; set; }
    public string FullName { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<Person> People { get; set; }
}

public class Program
{
    public void Main()
    {
        using var context = new ApplicationDbContext(*configuration here*);
        var doWorks = Enumerable.Range(0, 1000).Select(x => context.People.AsNoTracking().ToArrayAsync());
        await Task.WhenAll(doWorks);
    }
}

I get this error:

System.InvalidOperationException: 'A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.'

How can I run multi tasks like that and get rid of that error?

A: The easiest way is to create a new ApplicationDbContext object inside each task:
public class Program {
    public void Main() {
        var doWorks = Enumerable.Range(0, 1000).Select(async x => {
                          using var context = new ApplicationDbContext(*configuration here*);
                          await context.People.AsNoTracking().ToArrayAsync();
                      });
        await Task.WhenAll(doWorks);
    }
}

Notice I made your lambda async and used await. Otherwise, the context would get disposed before the query is finished.
If you're doing this as a load test, that's fine. Just be aware that in some cases, executing 1000 tasks simultaneously might perform worse than other ways.


text:
Q: Embed a PDF document from server in HTML page using Java Servlet /JSP I am currently able to serve up files from my server directory to the HTML front end. However, I am currently only able to have these files downloaded, or opened fully on the page. What I want to do is embed them within my webpage.
I can easily do this if the files are stored in the web directory but using the embed tag.
Currently I am doing something along the lines of this:
Servlet file :
@MultipartConfig
@WebServlet
public class FileServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        File file = new File("filePath");
        String mimeType = getServletContext().getMimeType(file.getName());
        response.setHeader("Content-Type", mimeType);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "embed; filename=\"fileName.pdf\"");
        Files.copy(file.toPath(), response.getOutputStream());
     }
}

JSP :
<form action="getFile" method="post" id="fileForm">
  <input type="hidden" name="fileName" value="<%out.print(cvKey);%>/<%out.print(name);%>.pdf"/>
</form>

Where the form is automatically submitted on page load.
I've been trying to set the source of the embedded tag to the output of the Servlet file, but nothing I have tried works in the way I want it to.
Any help would be amazing!!
UPDATE:
I've tried a few more things; including using an iframe like :
<iframe name="frame" width="500" height="300"></iframe>

And then setting the target of the form to the name of that frame. This still doesn't work and I just get an empty frame and the file gets downloaded :/.
EDIT :
Tried using the embed tag with a path directly to the file unsuccessfully :
My code :
<embed id="embeddedPDF" src="/home/user/resources/candidate.pdf" width="1000" height="1000" type='application/pdf'></embed>

And the error :
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.


text:
Q: jquery- how to run some code within a form only when some text within that form is selected by the user I want to run some code only when the user has selected some text within the form- the selected text may be the label of an input element within the form, or some text directly given within the form.
Currently I am using the following--
$('form').each(function(){
    // the 'this' below refers to a form- any element within the form is a child of the form...
    //hence the listener checks for focus being set to any element within any form of the web page...
    $(this).children().focus(function() {

  ......MY CODE HERE.............

Is there a better way to modify the code above, so that it works only when the user has selected some text within the form?

A: Try this;
$("form *").focus(function () {
alert("focus");
});

A: There's javascript for looking at text selection but it';s in some ways more of a mess than the DOM APIs. I don't have a full solution for you but look at Rangy for a sane selection API and register events to something like mouseup to check the current selection.


text:
Q: Python append to csv file without white rows and without repeating columns hi I have some problem.
import csv
test = ['a','b','c','d','e']

for t in test:
    with open('names.csv', 'a') as csvfile:

        fieldnames = ['acol', 'bcol', 'ccol']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({'acol': t, 'bcol': t, 'ccol': t})

'names.csv' result
acol    bcol    ccol
a   a   a
acol    bcol    ccol
b   b   b
acol    bcol    ccol
c   c   c
acol    bcol    ccol
d   d   d
acol    bcol    ccol
e   e   e''
there is whiteline and colume repeat
i want result without white rows and without colume repeat

A: You could try this
import csv
test = ['a','b','c','d','e']

with open('names.csv', 'wb') as csvfile:
    fieldnames = ['acol', 'bcol', 'ccol']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for t in test:
        writer.writerow({'acol': t, 'bcol': t, 'ccol': t})

A: import csv
test = ['a','b','c','d','e']

for i,t in enumerate(test):
    with open('names.csv', 'a') as csvfile:

        fieldnames = ['acol', 'bcol', 'ccol']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if i == 0:
            writer.writeheader()
        writer.writerow({'acol': t, 'bcol': t, 'ccol': t})

The other solution provided by Divakar is more elgant and faster since you do not open the file in every loop.

A: Use this
import csv
test = ['a','b','c','d','e']

for t in test:
    with open('names.csv', 'w') as csvfile:

        fieldnames = ['acol', 'bcol', 'ccol']
        writer = csv.writer(csvfile)
        writer.writerow(fieldnames)

        for elem in test:
            writer.writerow(elem * 3)

here is my output from names.csv it dosen't have any newline
acol,bcol,ccol
a,a,a
b,b,b
c,c,c
d,d,d
e,e,e

A: import csv
test = ['a','b','c','d','e']

with open('names.csv', 'a') as csvfile:
    fieldnames = ['acol', 'bcol', 'ccol']
    writer = csv.DictWriter(csvfile,delimiter=' ',fieldnames=fieldnames,lineterminator=' ')
    writer.writeheader()
    for t in test:
        writer.writerow({'acol': t, 'bcol': t, 'ccol': t})

you are writing headers inside the loop so they are rewritten many times,by default line terminator is '\n' which gives new white space at end of line.This gives the result you cited above


text:
Q: How to validate spring security antmatcher in a custom filter I have defined a custom filter, i added just after BasicAutenticationFilter...
Issue is, when i ping my microservice (by the health check of rancher in this case) it always go to the filter, and do stuff is suppose it shouldn't, I say it suppose it shouldn't because i put the ping into the antmatchers to permitAll requests, the code in my filter is this:
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    logger.debug(this + "received authentication request from " + request.getRemoteHost() + " to " + request.getLocalName());

    if (request instanceof HttpServletRequest) {
        if (isAuthenticationRequired()) {
            authenticate(request,response);
        } else {
            logger.debug("session already contained valid Authentication - not checking again");
        }
    }
    chain.doFilter(request, response);
}

private boolean isAuthenticationRequired() {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if ((existingAuth == null) || !existingAuth.isAuthenticated()) {
        return true;
    }
    return false;
}

I assumed, when you SecurityContextHolder.getContext().getAuthentication(); it should validate the antmatchers and return existingAuth with true, i know  i know this is to magical to think as i do, but then, i need to find a away to validate the request and tell spring security is inside the antmatchers list..

A: You could just use the filter to do the health check. place it in position FIRST
public class HealthFilter extends OncePerRequestFilter {

    private String healthPath = "/healthcheck/**";
    private AntPathRequestMatcher matcher = new AntPathRequestMatcher(healthPath);

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        if (matcher.matches(request)) { //evaluate health check
            //do anything you want over here.
            //including performing your health check
            response.getWriter().write("OK");
            response.setStatus(200);
        }
        else {
            //only execute the other filters if we're not doing a health check
            filterChain.doFilter(request, response);
        }

    }
}

Online integration tests are available


text:
Q: EWS email folder owner Everyone in our office is setup with their own mailbox. But a few special ones have access to a shared mailbox. I have written an app to track email activity on this "shared" mailbox using EWS API.
The problem i encountered is when an email is deleted. The app detected a "moved" event. From the event, it gets the new folder which happens to be the personal "Deleted" folder. Is there a way to get the owner of that "Deleted" folder via EWS API?
There's a workaround solution I came up which is to import all user's email folders. This solution works, it is just tedious to maintain because we have new/remove users almost every week.

A: If you use ConvertId with a generic non resolvable email address it should the return the actual address the FolderId belongs to when you try a convert eg
        AlternateId aiAlternateid = new AlternateId(IdFormat.EwsId, SharedFoder.Id.UniqueId, "mailbox@domain.com");
        AlternateIdBase aiResponse = service.ConvertId(aiAlternateid, IdFormat.EwsId);
        Console.WriteLine(((AlternateId)aiResponse).Mailbox);

(Where SharedFolder is an EWS Managed API folder).
Cheers
Glen


text:
Q: Want to design a REST API but I have too much parameter to send , is it okay to replace them with one JSON? I am designing a REST API one of my resources is all about to getting some basic data from user side.
Here are two points that I needs to mention:

*

*all the user's information needs to send to server side with only one http request

*the user's information is about 30 different fields.

So I think having a long list of argument in server side can not be that much good and I want to replace this part with a single argument which is accepting a JSON.
Do you think is it correct to do that?

A: Yes.  You will want to change the method to a POST instead of a GET and in the request body send the JSON formatted data.
Example using C# syntax:
Assume you have a method that returns an object called ObjectList and in order to generate the list you the constructor requires an ObjectListRequest object -
public ObjectList GetObjectList(ObjectListRequest request)
{
    return new ObjectList(request)
}

Your ObjectListRequest class could contain various different parameters that the request would use -
public class ObjectListRequest
{
    public string SearchText { get; set; }
    public string CreatedBy { get; set; }
    public int SequenceStartRange { get; set; }
    public int SequenceEndRange { get; set; }
    public bool HasMetaData { get; set; }
}

Now to call this method using a POST with JSON in the body you would send the following
Method:   POST
Url:      http://your.service.com/GetObjectList
Headers:
   Content-Type: application/json

Body:
   {
      "request":{
          "SearchText":"test text",
          "CreatedBy":"myusername",
          "SequenceStartRange":0,
          "SequenceEndRange":15,
          "HasMetaData":"true"
      }
   }

This is a specific example which assumes you are using C# and built in Serialization libraries from microsoft, but if not, you can still use the same basic idea to do what you are trying to do.


text:
Q: Finding a document in RethinkDB that meets multiple criteria I want to create a wrapper function that accepts an array of requirements. This wrapper function will ask rethinkDB for any documents that meet all criteria. The values will be numerical and I want anything returned which has >= the asked for value.
The syntax supplied in the API is like this:
r.table("name").filter(
r.row("cond1").lt(val1).and(r.row("cond2").gt(val2))
).run(conn, callback);

But that doesn't allow me to query for an arbitrary amount of conditions.
Is there a feature that I am missing, or is the solution to:
 1. build a string and eval it - or -
 2. pass a function to the RethinkDB server with my array of requirements included ?
An example that might make more sense: I have a database of monster trucks. I want to allow someone to say "show me trucks with a power score of at least 5 and with a speed of at least 10". Here is a failed attempt at passing a function:
r.db('test').table('monstertrucks').filter(
function(item){
var fail = 0,
    arr = [{attr: "speed", val: 5}, {attr: "power", val: 10}];
for(var i = 0; i < arr.length; i++){
  if(item(arr[i].attr).lt(arr[i].val)){fail++}
}
return fail ? false : true;
})

A: RethinkDB doesn't just run your function on the server, it calls your function once to build up a predicate.  (See http://rethinkdb.com/blog/lambda-functions/ .)  You can build up the predicate you want and return it like so:
r.db('test').table('monstertrucks').filter(function(item) {
  var pred = r.expr(true);
  arr = [{attr: "speed", val: 5}, {attr: "power", val: 10}];
  for (var i = 0; i < arr.length; i++) {
    pred = pred.and(item(arr[i].attr).lt(arr[i].val));
  }
  return pred;
}


text:
Q: javascript/jquery - hide/show table row if radio buttons checked I am very new to js and jQuery.
I have a simple bootstrap table. In two rows, I have radio buttons, one for item 1a and another for item 2a. I have another two rows with classes of price-1 and price-2. I am hiding price-2 initially (class="hidden"), so the only visible row is price-1.
I would like to use js or jQuery to show/hide .price-1 and .price-2 depending on which radio is selected. So, if the radio for Item 1a (id="radioItem1) is selected, I want .price-1 (Item 1 row) to be visible and .price-2 (Item 2 row) hidden. If the radio for Item 2a (id="radioitem2) is selected, I want .price-2 (Item 2 row) to become visible and hide .price-1 (Item 1 row). Only one of them should be visible at a time
Eventually, I will be making the bootstrap table rows clickable, so if someone clicks on the row (not the radio) it will select the radio. Because of this, if possible, I want the js to look if the radios are actually "checked" (not clicked), as I want to remove any possible human error component where a user can accidentally click twice on a row which will essentially toggle a click event twice. I think the on.click function works great for checkboxes, but not necessarily for radios.
How can I accomplish this?
HTML:

<select id="licenseRegs" class="form-control selectPCs" name="licenseRegs" style="width: 50%;">
    <option value="5" selected="selected" prodid="43" price="49.99" productname="product1">5 </option>
    <option value="10" prodid="44" price="99.99" productname="product1">10 </option>
    <option value="15" prodid="56" price="149.99" productname="product1">15 </option>
    <option value="20" prodid="68" price="199.99" productname="product1">20 </option>
    <option value="25" prodid="54" price="299.99" productname="product1">25 </option>
    <option value="50" prodid="45" price="599.99" productname="product1">50 </option>
    <option value="75" prodid="62" price="899.99" productname="product1">75 </option>
    <option value="100" prodid="53" price="1199.99" productname="product1">100 </option>
    <option value="125" prodid="78" price="1499.99" productname="product1">125 </option>
  </select>

Order Total:

        <input type="radio" id="radioItem1" name="productOptionItem" value="oneYear" checked>
        Item 1a

        <input type="radio" id="radioItem2" name="productOptionItem" value="twoYear" >
        Item 2a

        Item 1 row

      Item 2 row
      13

Here is a link to my jsfiddle where I am playing with what I am trying to do.
https://jsfiddle.net/dhs3gphz/6/

A: Here is your solution:jsFiddle
$(document).ready(function() {
  var pricePerRegUnder = 10;
  var pricePerRegAbove = 12;
  var licenseRegsSelect = $('#licenseRegs');

  function updateTotalPrice() {

    licenseRegs = parseInt(licenseRegsSelect.val(), 10);

    var total;
    if (licenseRegs < 25) {
      total = licenseRegs * pricePerRegUnder;
    } else {
      total = licenseRegs * pricePerRegAbove;
    }

    $('.price-1').html(total);
  }

  licenseRegsSelect.change(function() {
    updateTotalPrice();
  });
$('.rowAnnual').click(function(){
    $(this).find('input').prop('checked', true);
  if($(this).find('input').attr('id')=='radioItem1'){
        $('#addItem1').removeClass('hidden');
        $('#addItem2').removeClass().addClass('hidden');
  }
  else{
        $('#addItem1').removeClass().addClass('hidden');
        $('#addItem2').removeClass('hidden');
  }
});

  updateTotalPrice();
});


text:
Q: for loop specific elements of a vector in R I want to run a for loop which makes a calculation only for specific elements from a column in a data frame. The elements are referenced from an adjacent column in the matrix. I can do this by visually observing which elements correspond to the values - e.g. for(i in 1:5){ # in a column of 301 elements. However, I would like to be able to specify this without apriori knowledge of the element numbers.
e.g. in the following data frame I want to run a for loop on the elements of the column data.LICOR$flux when data.LICOR$day.night=='d'
   data.LICOR.day.night data.LICOR.flux
1                   d       26.89
2                   d       27.89
3                   d       28.77
4                   d       28.92
5                   d       29.30
6                   n       28.51
7                   n       28.98
8                   n       28.41
9                   n       27.87
10                  n       28.18

This is what my previous code did by specifying element 1:5 and 6:10 which correspond to day.night = 'd' and day.night ='n' respectively
# replace day fluxes
for(i in 1:5){
    if(data.LICOR$flux[i] > av.day.flux+2*sd.day.flux)
      data.LICOR$flux[i] <- av.day.flux
    else if(data.LICOR$flux[i] < av.day.flux-2*sd.day.flux)
      data.LICOR$flux[i] <- av.day.flux
}

# replace night fluxes
for(i in 6:10){
    if(data.LICOR$flux[i] > av.night.flux+2*sd.night.flux)
      data.LICOR$flux[i] <- av.night.flux
    else if(data.LICOR$flux[i] < av.night.flux-2*sd.night.flux)
      data.LICOR$flux[i] <- av.night.flux
}

this removes values that are greater than 2 standard deviations from the mean and replaces them with the mean value.
Thanks for any suggestions.

A: Given the loops in your comment to Gavin's answer, I think you want something like this (assuming your example data are in an object named data.LICOR).
# within() allows us to evaluate all the expressions (the 2nd argument)
# using the data in 'data.LICOR'.
data.LICOR <- within(data.LICOR, {
  # ave() applies 'FUN' to the subsets of 'flux' specified by 'day.night'
  # and returns an object the same length as 'flux'.
  av.flux <- ave(flux, day.night, FUN=mean);
  sd.flux <- ave(flux, day.night, FUN=sd);
  # ifelse() returns 'av.flux' when the first argument is TRUE
  # and 'flux' when it's FALSE.
  flux <- ifelse(flux > av.flux+2*sd.flux |
                 flux < av.flux-2*sd.flux, av.flux, flux) })

A: Use the subset function to get the subset of the data-frame you want. E.g. if df is your original data-frame, you can do:
df.d <- subset(df, day.night == 'd')

And then you can do whatever calc you want on df.d.
To replace the "large" and "small" values by their mean, you could do it in base R using Joshua's approach (using ave and within) or using the ddply function from the plyr package:
require(plyr)
## ddply breaks up the data-frame according to the value of "DayNight" ('d' or 'n') and
## WITHIN each category, "transforms" the flux column as desired
ddply(df, .(DayNight), transform,
      flux = ifelse( flux > mean(flux) + 2*sd(flux) | flux < mean(flux) - 2*sd(flux),
                     mean(flux),
                     flux ))

I'm using shortened versions of your column names, but I'm sure you get the idea. If you know the "right" level of the average and std deviation a priori, you can replace the mean(flux) and sd(flux) in the above code, with those values.

A: You can get the subset using:
subset(data.YSI, subset = day.night == "d")

But now tell us what you want to do with it?

A: Another possibility for the last two lines of the answer provided by Ulrich is:
 flux[which(flux> av.flux+2*sd.flux & flux < av.flux-2*sd.flux)] <- av.flux

This is, arguably, faster, because you only need to replace those values which do not fit the criteria. However, I'm not sure if this is truly faster in R, and for small datasets I guess it won't matter.
And kepping the loop (not a good practice in R if it's possible to vectorize, but may be in other languages), you just need to do this:
for (i in unique(data.Licor$day.night) {
      if (data.LICOR$flux[which(data.LICOR$day.night==i)] > ...

Note here that the modifications are: the use of which and use of factors in the for statement.


text:
Q: how to send mail using perl with attachement? I've try to send mail using perl with attachment I've tried with Email::Stuff and  MIME::Lite,during run time i got some error as Authentication failed or server not connected can anybody help me?
corresponding code is:
   use MIME::Lite;
use Net::SMTP;
### Adjust sender, recipient and your SMTP mailhost
my $from_address = 'atme04@gmail.com';
my $to_address = 'thiyagu040@gmail.com';
my $mail_host = 'smtp.gmail.com';

### Adjust subject and body message
my $subject = 'A message with 2 parts ...';
my $message_body = "Here's the attachment file(s) you wanted";
my $your_file_zip = 'my.zip';

$msg = MIME::Lite->new (
  From => $from_address,
  To => $to_address,
  Subject => $subject,
  Type =>'multipart/mixed'
) or die "Error creating multipart container: $!\n";
MIME::Lite->send('smtp', 'smtp.gmail.com' ,
                          Port =>465 ,
                          Timeout=>320 ,
                          Debug => 1 ,
                          Hello => $mail_host,
                          User  => $from_address,
                          Password  => 'Thiyagu.04' );
#$mime_msg->send() or die "Error sending message: $!\n";

#MIME::Lite->send('smtp',$mail_host,AuthUser=> $from_address, AuthPass=>"apssword");

$msg->send();

error message is;
 SMTP Failed to connect to mail server: A connection attempt failed because the connected party did not properly respond aft
    er a period of time, or established connection failed because connected host has failed to respond.
     at mail.pl line 54.

thanks in advance

A: The error message seems pretty clear to me. The problem is with your connection to the mail server - so changing the module that you're using is unlikely to achieve anything useful. I don't know enough about Gmail's server settings to comment on what the problem is, but this page has some suggestions that you might follow. Specifically, you could check that the Gmail account has 'allow authentication' turned on and that your mail client (the Perl program) is using SSL for the connection.
Also, this might be easier if you used an email that was specifically designed for use with Gmail. Email::Send::SMTP::Gmail looks tailor-made for your requirements.


text:
Q: flutter displaying different types of images in child I am doing something funky. The user is allowed to choose images from his phone's gallery or take a picture with his camera.
I then upload that image to Firebase storage and retrieve the URL to save it to firestore, so that I can reference that image when the user wants to edit his selections.
That portion works great.
When the edit page opens, there is a quick error that displays, but the image still displays. I want to get rid of that "quick error".
this is the error I get before the image is loaded:
RangeError (index): Invalid value: Valid value range is empty: 0

the other problem I do not know what image is being loaded into my variable it can a FILE (user can change the image from his gallery/camera) or a string (URL from firestore, displaying image that was previously selected)
my wonderful nested:
child: (imageFile1 != null)
                    ? Image.file(
                        imageFile1,
                        width: (size.width - 8 * 4) * 0.33,
                        fit: BoxFit.cover,
                      )
                    : (imageList[0] == null)
                        ? Image.asset(
                            defaultImage,
                            width: (size.width - 8 * 4) * 0.33,
                            fit: BoxFit.cover,
                          )
                        : Image.network(
                            imageList[0],
                            width: (size.width - 8 * 4) * 0.33,
                            fit: BoxFit.cover,
                          ),

imagelist gets loaded in the initstate (Therefore, I have a method with Future and await involved to go fetch that information from firetsore)
imageFile1 gets loaded when the user decides to change the image to another one from his gallery/camera
default image, if both are null then display missing image jpg.
I tried debugging and it seems the scaffold is being called before the initstate??? Which is strange to me...
Thoughts?

A: We could avoid address this issue by the means of a CircularProgressIndicator that will be drawn while the imageList[] is empty:
child: imageList == null || imageList.isEmpty() ? CircularProgressIndicator() : _buildImageFiles(),

A: ok, here is how I did it....First, thank you all for your inputs
My Scaffold I already had CircularProgressIndicator implemented with Visibility widget and having the visible paramter: isLoading
so, before and after my await call in the Future function (this function gets called in the inistate function) I did a setState of isloading = true/false.
This part was key since I needed it to pre-load my form components with the data coming from Firestore.
That solves my pre-loading form data.
As for null imagelist.... I ended up with this freakishly looking nested if statement
(imageList.isEmpty)
                        ? Image.asset(
                            defaultImage,
                            width: (size.width - 8 * 4) * 0.33,
                            fit: BoxFit.cover,
                          )
                        : (imageFile1 != null)
                            ? Image.file(
                                imageFile1,
                                width: (size.width - 8 * 4) * 0.33,
                                fit: BoxFit.cover,
                              )
                            : (imageList[0] == null)
                                ? Image.asset(
                                    defaultImage,
                                    width: (size.width - 8 * 4) * 0.33,
                                    fit: BoxFit.cover,
                                  )
                                : Image.network(
                                    imageList[0],
                                    width: (size.width - 8 * 4) * 0.33,
                                    fit: BoxFit.cover,
                                  ),


text:
Q: How to align 1 and -1 in Linear equation?

How to align 1 and -1 like the picture do?
I am trying to typeset the following equation:
\documentclass{article}
\usepackage{systeme}
\begin{document}
\systeme{x_1+2x_2-x_3=-1, 2x_1+2x_2+x_3=1, 3x_1+5x_2-2x_3=-1}
\end{document}

A: As @JohnKormylo has noted in a comment, you may achieve your formatting objective by employing an array environment.

\documentclass{article}
\usepackage{array} % for '\newcolumntype' macro
\newcolumntype{C}{>{{}}c<{{}}}

\begin{document}

\begingroup % localize scope of next instruction
\setlength\arraycolsep{0pt} % default: 5py
a) $\left\{ \
   \begin{array}{ rCrCr @{{}={}} r}
     x_1 & + & 2x_2 & - &  x_3 & -1 \\
    2x_1 & + & 2x_2 & + &  x_3 &  1 \\
    3x_1 & + & 5x_2 & - & 2x_3 & -1
   \end{array}
   \right.$
\endgroup

\end{document}

A: The documentation of the systeme package is in French, so it's maybe difficult to understand.
\documentclass{article}
\usepackage{systeme}

\sysalign{r,r}

\begin{document}

\systeme{x_1+2x_2-x_3=-1, 2x_1+2x_2+x_3=1, 3x_1+5x_2-2x_3=-1}

\end{document}

The first r refers to right alignment in the left-hand sides, the second one refers to right alignment in the right-hand sides.


text:
Q: How to remove last alphabet in a word using regular expression python '''
string = (" qtoday X fridayq qblue aqb")
string = re.sub('^ q+', '', string)
string
I want to remove only aplhabet q which is in the starting of the word and ending of a word...

A: You may try:
inp = "qtoday X fridayq qblue aqb"
output = re.sub(r'\bq|q\b', '', inp)
print(output)

This prints:
today X friday blue aqb

The regex pattern \bq|q\b matches the letter q when it is either preceeded or proceeded by a word boundary, i.e. it is the starting or ending letter in a word.
One edge case here might be if you wanted to preserve q should it appear standalone, e.g.
inp = "qtoday q fridayq aqb"
output = re.sub(r'\bq(?=\w)|(?<=\w)q\b', '', inp)
print(output)

This prints:
today q friday aqb

Here, we check in the regex pattern that the q is preceeded/followed by at least one other word character, to spare the standalone q.


text:
Q: Is there an option in ReSharper to not put an object initializer on multiple lines? Every time I type an object initializer as a parameter, like this:
SomeFunc(new { Id = id })

and type the semicolon afterwards, ReSharper formats what I just typed, as configured.
However, I cannot find an option in ReSharper to make it not turn my code into this:
SomeFunc(new {
  Id = id
});

I did confirm it actually is ReSharper doing the formatting.

A: If you want to keep ReSharper from formatting your object initializers (so you can decide how you want to format them yourself), I think a combination of these settings will do the job.
Keep existing line breaks : [Checked]
Place simple array, object and collection on single line : [Checked]
Wrap object and collection initializer : 'Simple wrap'
Wrap long lines : [Unchecked]
Of course, these settings might not fit everyone's situation, but I'm sure you can adapt them to your needs.

A: It looks like you need to set Wrap object and collection initializer option to Chop if long in Code Editing -> C# -> Formatting Style -> Line Breaks and Wrapping section.


text:
Q: second and third update statements aren't actually updating I tried changing the ";" in all different orders and any other way then this doesn't update any columns. But when its like this it only runs the first statement. PS: I'm using mimir if that matters.
This is the code:
ALTER TABLE MODEL
ADD MOD_WAIT_CHG INT(11);

UPDATE MODEL
SET MOD_WAIT_CHG = 100
WHERE MOD_CODE = 'C-90A';

UPDATE MODEL
SET MOD_WAIT_CHG = 75
WHERE MOC_CODE = 'PA23-250';

UPDATE MODEL
SET MOD_WAIT_CHG = 50
WHERE MOC_CODE = 'PA31-350';

A: I think the problem is because of MOC_CODE You must type  MOD_CODE
and also you Cannot specify a column width on data type int.
for this situation better to use Transaction as bellow:
begin transaction;

    ALTER TABLE MODEL ADD MOD_WAIT_CHG INT;

    UPDATE MODEL SET MOD_WAIT_CHG = 100 WHERE MOD_CODE = 'C-90A';

    UPDATE MODEL SET MOD_WAIT_CHG = 75 WHERE MOD_CODE = 'PA23-250';

    UPDATE MODEL SET MOD_WAIT_CHG = 50 WHERE MOD_CODE = 'PA31-350';
 commit;


text:
Q: How to get android app to top of search result in play store similar to uber Can anyone explain how to get my android application on play store search results similar to uber. (as shown in image below)
Thanks in advance

A: If you want your application on top.There are many different factors by which you can bring your app to top:-
1)choose a very unique name for your app.
2)If the app has just been launched and has less than 10 downloads then the google
 play store doesn't show it to users(try searching with package name).
3)Doing some marketing for your app will surely help.


text:
Q: Postgresql - How to query nested array elements I have JSON array data in PostgreSQL 13 table. I want to query this table to see all the nested array data in the output. I tried the below query, but it's not giving the expected output.
select
json_data::json -> 'Rows' -> 0 -> 'Values' ->> 0 as Lid
,json_data::json -> 'Rows' -> 0 -> 'Values' ->> 1 as L2LicenseId
,json_data::json -> 'Rows' -> 1 -> 'Values' ->> 0 as Lid
,json_data::json -> 'Rows' -> 1 -> 'Values' ->> 1 as L2LicenseId
from test;

Can someone please help me?
Sample Data
CREATE TABLE IF NOT EXISTS test
(
    json_data text
);

INSERT INTO test (json_data) VALUES ('{"Origin":"api","Topic":"licenses","Timestamp":"2023-02-07T12:46:42.2568898+00:00","Columns":["LId","L2LicenseId","SfdcAccountId","SfdcLineItemId","SL","Quantity","StartDate","EndDate","DisplayName","ProductPrimaryKey"],"Schema":["string","string","string","string","string","int32","datetime","datetime","string","string"],"Rows":[{"Values":["1234","123456","ACC_","PurchaseT","SKU-0000","1","2023-01-09T00:00:00.0000000","2024-01-08T00:00:00.0000000","Automation with 5 users","lc11dev.my-dev.com"]},{"Values":["8967","8967-e567","fihikelo","Addon_00000490_2nd_GB","SKU-0490","3","2023-01-01T00:00:00.0000000","2023-01-22T00:00:00.0000000","Automation, Data 5GB","mygreattest01311433.my-dev.com"]}]}')

Expected Output

DB FIDDLE

A: You can do it using PostgreSQL function jsonb_array_elements (or json_array_elements). This function extracts all Json array elements like as rows view.
select
    a2.value -> 'Values' ->> 0 as Lid,
    a2.value -> 'Values' ->> 1 as L2LicenseId
from test a1
cross join jsonb_array_elements(a1.json_data::jsonb->'Rows') a2

-- Result:
lid  | l2licenseid |
--- -+-------------+
1234 | 123456      |
8967 | 8967-e567   |


text:
Q: Bufferedimage into circle shape I have a buffered image from byte array. How do I make the image into a circle? Crop? I don't want a circle, I want the orginal image to become circle shape and display
 def bufferedImage = imgSvc.convertByteArrayToBufferedImage(crop.image)

A: If bufferedImage is squared, then with this code :
int width = bufferedImage.getWidth();
BufferedImage circleBuffer = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = circleBuffer.createGraphics();
g2.setClip(new Ellipse2D.Float(0, 0, width, width));
g2.drawImage(bufferedImage, 0, 0, width, width, null);

you get a circular cropped image in circleBuffer

A: this can help
    g.setClip(new Ellipse2D.Float(x, y, w, h));
    g.drawImage(yourBufferedImage, x, y, w, h, null);

A: You can use setClip() method of the Graphics class to restrict the drawing area of a graphics context to a specific region. The drawback of this is that this clipping will not be anti-aliased.
There are some more advanced tricks to achieve a better-looking result, see the answers to the following questions:
Drawing a part of an image (Java)
How to make a rounded corner image in Java

A: import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageCircle {
    static Image img;
    static String imgFile =
            "yourFileName.jpg";
    public static void main(String[] args) {
        try {
            img = ImageIO.read(new File(imgFile));
        } catch (IOException fne) {
            fne.printStackTrace();
        }
        int width = img.getWidth(null);
        int height = img.getHeight(null);

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bi.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        int circleDiameter = Math.min(width,height);
        Ellipse2D.Double circle = new Ellipse2D.Double(0,0,circleDiameter,circleDiameter);
        g2.setClip(circle);
        g2.drawImage(img,0,0,null);
        try {
            ImageIO.write(bi, "PNG", new File("yourFileName.png"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
Q: diagonalisability of matrix few properties What are the most important things one should remember to check the diagonalisability of a matrix?
Please help, I have exams on next week.
Say some best and easy methods,time efficient.

A: Let $A\in \mathcal M_{n\times n}(\Bbb C)$.
Some common criteria are:

*

*If $A$ has $n$ distinct eigenvalues, then $A$ is diagonalizable.

*$A$ is diagonalizable if, and only if, the sum of the geometric multiplicties of all the eigenvalues equals $n$. (Note that 1. is a particular case of this).

*$A$ is normal if, and only if, $A$ is unitarily diagonalizable.

*$A$ is hermitic if, and only if, $A$ unitarily similar to a diagonal matrix with only real entries.

*$A$ is unitary if, and only if, $A$ is unitarily similar to a diagonal matrix which entries on the main diagonal have absolute value equal to $1$.

A: A matrix is diagonalizable iff its minimal polynomial has distinct roots and factors into linear factor.

A: You can see diagonalisability of matrix few properties
in Wikipedia, by coincidence this article has the same title as your question.


text:
Q: Website doesn't load in firefox/safari ( Linux, OS X ) Have problem with loading website. This is SPA ( angularjs 1.5v ). In Firefox and Safari doesn't load. Tested on Linux and OS X . When open that site no any errors.
In others browsers works as expected.
Do you have any ideas? What need check etc.
Thanks for help!


text:
Q: R DataExplorer package - Cannot use functions I successfully installed boxuancui's DataExplorer package in R, but when I go to use functions from this package, I'm getting errors.

Error: could not find function "plot_missing"
  Error: could not find function "create_report"

I downloaded from GitHub:
if (!require(remotes)) install.packages("remotes")
remotes::install_github("boxuancui/DataExplorer")

Any suggestions as to why?
Below are my particulars.
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          3.2
year           2016
month          10
day            31
svn rev        71607
language       R
version.string R version 3.3.2 (2016-10-31)
nickname       Sincere Pumpkin Patch


text:
Q: ARM TrustZone-M secure world variable shadows nonsecure variable? I have an application written for an STM32-L552ZE Cortex M-33 based MCU which makes use of TrustZone-M.
Both worlds have a main.h, main.c and both wolds' header files declare a variable foo (i.e. both the secure main.h and nonsecure main.h declare foo).
To my mind, this should be fine because the way I learned about TrustZone (admittedly, I am coming more from a TrustZone-A, SGX world) makes me believe that the two worlds are independent from each other and only interact through a welldefined interface (secure-/nonsecure function calls through the NSC region).
Unfortunately, when debugging my code, I noticed that the nonsecure world's writes to foo were ignored. Through checking the address of foo, which was at 0x3..., I noticed that it was allocated in the secure world's SRAM. After having uncommented the secure world's foo declaration and leaving the rest unchanged, the memory address of foo seen by the nonsecure world changed to 0x2..., which is in the nonsecure world.
Question:
How is a variable in the secure world able to shadow a nonsecure variable? I am aware that TrustZone-M implements separation through memory addresses, though I would have assumed the linker to be smart enough to differentiate between the two instances of foo.

Clarification:
To make the situation clearer, following is an excerpt from the code:
secure main.h:
#ifndef __MAIN_H
#define __MAIN_H

/* Includes */
#include "stm32l5xx_hal.h"
#include "secure_nsc.h"        // Header file declaring the functions into secure world

/* Private includes*/
/* USER CODE BEGIN Includes */

#include "inttypes.h"
#include "string.h"

/* USER CODE END Includes */

...

typedef struct ringbuf{
    volatile int16_t prod_ind;
    volatile int16_t cons_ind;
    volatile int16_t isr_ctr;
    volatile bool_t  empty;
             byte_t  buf[RBUF_LEN];
}ringbuf_t;

ringbuf_t foo;

...

#include "helper.h"

#endif /* __MAIN_H */

nonsecure main.h:
#ifndef __MAIN_H
#define __MAIN_H
/* Includes */
#include "stm32l5xx_hal.h"

#include "secure_nsc.h" /* For export Non-secure callable APIs */

/* Private includes */
/* USER CODE BEGIN Includes */
#include "inttypes.h"
#include "string.h"
/* USER CODE END Includes */

...

typedef struct ringbuf{
    volatile int16_t prod_ind;
    volatile int16_t cons_ind;
    volatile int16_t isr_ctr;
    volatile bool_t  empty;
             byte_t  buf[RBUF_LEN];
}ringbuf_t;

ringbuf_t foo;

...

#include "helper.h"

#endif /* __MAIN_H */

Both helper.h, i.e. the secure and nonsecure one, have the following declaration (the definition exists in their respective helper.c files):
bool_t rb_produce_one(ringbuf_t* rb, byte_t ibyte);

This function rb_produce_one is the one used by the nonsecure world to access its ringbuffer foo.
Secure main.c doesn't use its instance of foo (yet, will use it later).
Nonsecure main.c accesses foo through a function which is declared in helper.h and defined in helper.c (again, helper.h, helper.c exist twice, once in the secure and once in the nonsecure world).


text:
Q: Text not allowed in element ul in this context I do not understand this error message from the markup validation service and I have been unable to find an answer. It seems that the Service is pointing to the &nbsp. I want to put a blank line between each of my links. Thank you.
Text not allowed in element ul in this context

Green Light Data Technologies

Product List

Patch Cords

Ethernet Cards

Bulk Wire

RJ45* Connectors

A: While waiting for an answer, I kept looking and this is what I found on:
http://www.webmasterworld.com/forum21/8348.htm
Not a direct quote, add the &nbsp within the li tags. I think the answers came from Tedster and Span in response to a similar question asked by JayCee.
This worked for me.
Kindest Regards


text:
Q: Encog : Reinforcement Learning / Actor-Critic Model I have a basic neural net problem where I want a "rocket" to maintain it's altitude at a given height. (This is a simple version of the problem, it will get more complex).
I am using the encog platform and it isn't clear how to use it to implement reinforcement learning.
I think that I want to use the Actor-Critic model where two separate NNs exist. One of them analyzes the reward that's due according to the current state. The other NN calculates the force it should apply to the rocket.
I can calculate a reward schema (drive the distance between rocket and target height to 0). But I can't figure out how to make the "Actor" NN learn. It seems like I would take the error from the "Critic" NN and use that same error as the backpropagation error for the Actor. But I can't figure out how to do this in Encog.
Thanks so much for any help!


text:
Q: P4 Python error: file(s) not on client I am using the p4 Python module to try and open several files for edit.  Basically I have a list of files that I am grabbing from a txt document.  I then do some formatting to each item in the list and append those items to an empty list.  My method is not the most efficient but I am just trying to get this to work before optimizing.
edit_files = []

with open('C:\\Users\\rgriffin\Desktop\\replace.txt', 'r' )as f:
    for line in f:
        l = line.partition(',')[0]
        e = l.replace('#(', '')
        r = e.replace('U:\\', '//Stream/main/')
        q= r.replace('\\', '/')
        edit_files.append(q)
f.close

for i in edit_files:
    p4.run("edit" , i)

With this code I get an error:

[Warning]: '"//Stream/main/Data/anims/stuff/char/Emotion_Angry.hkx" - file(s) not on client.'

If I change the last line to this...
p4.run("edit" , "//Stream/main/Data/anims/stuff/char/Emotion_Angry.hkx")

The file is checked out as expected.  I did a type check and i is a string.
Input data:
#("U:\Data\anims\stuff\char\Emotion_Angry_Partial.hkx", "u:\Assets\Actors\stuff\char\Animation\char_Idle.max")

A: In the following command, there are quote characters at ends. Do remove them. Also seems like there are empty lines.
Change
for i in edit_files:
    p4.run("edit" , i)

to
for i in edit_files:
    f=i.replace('"','').strip()
    if len(f)>0:
      print "Opening  ["+f+"]"
      p4.run("edit" , f)

or One liner
[p4.run("edit" , i.replace('"','').strip()) for i in edit_files if i.strip()]

Or you may want to change your populating code itself:
Use:
with open('C:\\Users\\rgriffin\Desktop\\replace.txt', 'r' )as f:
    for line in f:
        l = line.partition(',')[0].replace('#(', '').replace('U:\\', '//Stream/main/').replace('\\', '/').replace('"', '').strip()
        if len(l)>0:
            edit_files.append(l)
f.close


text:
Q: How can I get fireworks? What are the requirements for making fireworks appear at the end of a level in the original Super Mario Bros.?

A: From the Super Mario Wiki:

At the end of every level in Super Mario Bros., with the exception of a castle level, fireworks would go off when Mario or Luigi entered the tiny castle (if the last number of the timer is 1, 3, or 6 at the end of the level). If the last number was 1, one firework would go off; if the last number was 3, three fireworks would go off and so forth. Each explosion would award the player with 500 points.

The page also details the appearance of fireworks in numerous other Mario titles.


text:
Q: eliminate overlapping quarters from grouped user usage I have a table of user activity. I have the HWA, the date of activity, and a groupID. I get the quarters a user had activity based on a date range i.e.:
Date Range: 2011-08-01 - 2012-07-31
Q1 - Aug-Oct
Q2 - Nov-Jan
Q3 - Feb-Apr
Q4 - May-Jul

Some HWAs are replacements of others. In these cases they have the same groupID to show that they are linked. In these cases, I need to cancel out overlapping quarters. To clarify, if two HWAs have usage in quarter 2 and they have the same groupID, then I need to only count quarter 2 for one of them (which does not matter). Below is the query I am now using with the output I get:
SELECT act.HWA, count(act.HWA), m.Status, m.GroupID
    FROM (
        SELECT
          a.HWA, a.Date,
          CASE
            WHEN MONTH(a.Date) BETWEEN 8 AND 10 THEN 'Q1'
            WHEN (MONTH(a.Date) BETWEEN 11 AND 12 OR MONTH(a.Date) = 1) THEN 'Q2'
            WHEN MONTH(a.Date) BETWEEN 2 AND 4 THEN 'Q3'
            WHEN MONTH(a.Date) BETWEEN 5 AND 7 THEN 'Q4'
          END AS quarter,
          CASE
            WHEN MONTH(a.Date) <= 7 THEN YEAR(a.Date) - 1
            ELSE EXTRACT(YEAR_MONTH from a.Date)
          END AS quarteryear,
          COUNT(*) AS num_activites
        FROM activity a
        WHERE a.InstitutionNumber = '000000000075'
          AND (a.HWA = '001372EADBC4'
            OR a.HWA = '180373E241DB'
            OR a.HWA = '180373E23DE7')
          AND (a.Date between '2011-08-01' and '2012-07-31')
        GROUP BY
          quarter,
          a.HWA
    ) act, machine m
    where act.HWA = m.HWA
    group by act.HWA

Which returns this:
HWA             quarters      status      groupid

001372EADBC4        3        deleted        59970
180373E23DE7        2         online        59970
180373E241DB        1        deleted        59970

Expected results would be:
HWA             quarters      status      groupid
001372EADBC4        2        deleted        59970
180373E23DE7        2         online        59970
180373E241DB        0        deleted        59970

Here is a list of quarters for each HWA that I produce by changing the above query a little. You can see that all three HWAs have share quarter 3 and I want only one of them to have quarter 3:
001372EADBC4    1   deleted 59970
001372EADBC4    2   deleted 59970
001372EADBC4    3   deleted 59970
180373E23DE7    3   online  59970
180373E241DB    3   deleted 59970
180373E23DE7    4   online  59970

A: So I figured it out by just changing around groupings for the most part:
SELECT act.HWA, count(act.HWA), m.Status, m.GroupID
  FROM (
   SELECT
      a.HWA, a.Date,
      CASE
        WHEN MONTH(a.Date) BETWEEN 8 AND 10 THEN '1'
        WHEN (MONTH(a.Date) BETWEEN 11 AND 12 OR MONTH(a.Date) = 1) THEN '2'
        WHEN MONTH(a.Date) BETWEEN 2 AND 4 THEN '3'
        WHEN MONTH(a.Date) BETWEEN 5 AND 7 THEN '4'
       END AS quarter,
       CASE
          WHEN MONTH(a.Date) <= 7 THEN YEAR(a.Date) - 1
          ELSE EXTRACT(YEAR_MONTH from a.Date)
        END AS quarteryear,
        COUNT(*) AS num_activites
      FROM activity a, machine m
      WHERE
        a.InstitutionNumber = '000000000075'
        AND m.InstitutionID = 14
        AND (a.HWA = '001372EADBC4'
            OR a.HWA = '180373E241DB'
            OR a.HWA = '180373E23DE7')
        AND a.HWA = m.HWA
        AND (a.Date between '2011-08-01' and '2012-07-31')
        AND a.EngineRequests > 0
        AND a.FilesAnalyzed > 0
      GROUP BY
        quarter,
        m.GroupID
  ) act, machine m
WHERE act.HWA = m.HWA
AND m.InstitutionID = 14
GROUP BY act.HWA

I added in the following in the SELECT act:
AND m.InstitutionID = 14
 Group By m.GroupID
and I removed the following from the SELECT act:
Group By a.HWA


text:
Q: How to add time (like 9:25:03 + 11:36:27 = ) of single column in sql server 2008 i have column(time datatype) which contains values like
9:25:03
4:43:21
2:50:13
11:25:33

,what query should i write to get sum of all values in the column

A: try this:
;with cte as(
select SUM(DATEPART(hh,tm))*3600+
       SUM(DATEPART(MI,tm))*60+
       SUM(DATEPART(SS,tm)) tme
from time_table)
SELECT cast(datepart(hh,cast(CONVERT(varchar(8),
       DATEADD(ss, tme  , 0), 114) as time))+
       datediff(dd,'1900-01-01',CONVERT(varchar,
       DATEADD(ss, tme  , 0), 121))*24 as varchar(20))+
       right(CONVERT(varchar(8), DATEADD(ss, tme  , 0), 114),6)
from cte

result
28:24:10

SQL Fiddle demo

A: Turn your times into seconds and sum them instead.
with YourTable(TimeCol) as
(
  select '9:25:03' union all
  select '4:43:21' union all
  select '2:50:13' union all
  select '11:25:33'
)

select sum(datediff(second, 0, TimeCol)) sumSeconds
from YourTable

Result:
sumSeconds
-----------
102250

A: try this:
create table tbl123(tm time)

insert into tbl123
values('9:25:03'),('4:43:21'),('2:50:13'),('11:25:33')

;WITH CTE as(select SUM(DATEPART(hh,tm)) as hh,SUM(DATEPART(mi,tm)) as mm,SUM(DATEPART(ss,tm)) as ss from tbl123)

SELECT cast(hh+(mm+(ss/60))/60 as varchar(10))+':'+
       cast((((mm+(ss/60))%60)) as varchar(10))+':'+
       cast(ss%60 as varchar(10))
       from CTE

Result:
   28:24:10


text:
Q: Join query not working properly while connecting two tables Here i am doing cab allocation module,here i will explain my requirement,admin allocate the cab to the employees in shift wise.this details i stored in cab_allocation allocation table.

cab_allocation (Table Name)

allocationId                date                  cabId    shiftTiming

1                         2017-08-12              CBX100     1
2                         2017-08-12              CBX100     2
3                         2017-08-12              CBX101     3

Here cabId CBX100 having two allocation and CBX101 having one allocation per day. after this i want to track this trip is happening or not, for this tracking details i stored in trip_details table

trip_details (table name)

tripId    cabNo    shiftId   tripDate   startTime   endTime    tripStatus

 1       CBX100      1       2017-08-12  09:30:00    11:30:00       1
 2       CBX100      2       2017-08-12  12.10.00                    0

Here cabId CBX100 has completed his shiftId 1, shiftId start time is 09:30:00 and end time 11:30:00  and tripStatus 1 that means this trip is completed.
Next cabId CBX100 has started second shift, start time is 12.10.00 , but this trip is not completed so there is no end time and tripstatus
Next cabId CBX101 has not started his trip, so there is no entry is this table,
Now my expected result is which are the trip is incomplete i want to take details in cab allocation. here cab_allocation table allocationId i am using forien key trip_details table tripId.

I tried but i am not getting exact result,because CBX101 cabId not yet started his trip ,so entry not there in trip_details table, so i am not able get details.

I Tried like this
    $sql = "SELECT * FROM `cab_allocation` a INNER JOIN trip_details b ON a.allocationId=b.tripId WHERE b.tripStatus !='1'";
  $mysql = mysql_query($sql);
  $count =mysql_num_rows($mysql);
  if($count > 0){
      while ($row = mysql_fetch_assoc($mysql)) {
        $data[] = $row;
      }
  $arrayName = array('status' => 'success', 'count' => $count, 'data' =>$data );
  echo json_encode($arrayName);
 }else{
    $arrayName = array('status' => 'error', 'data' =>'Data not found' );
    echo json_encode($arrayName);
 }

I am getting Results
{
"status": "success",
"count": 1,
"data": [
    {
        "allocationId": "2",
        "date": "2017-08-12",
        "shiftTiming": "2",
        "routeId": "1",
        "cabId": "CBX100",
        "tripId": "2",
        "cabNo": "CBX100",
        "driverId": "G2E100",
        "shiftId": "2",
        "tripDate": "",
        "startTime": "12.10.0",
        "endTime": "",
        "tripStatus": "0"
    }
]

}
Expected Results
{
"status": "success",
"count": 2,
"data": [
    {
        "allocationId": "2",
        "date": "2017-08-12",
        "shiftTiming": "2",
        "cabId": "CBX100",
    },
    {
        "allocationId": "3",
        "date": "2017-08-12",
        "shiftTiming": "3",
        "cabId": "CBX101",
    },
]
}

A: The proper SQL would be:
    SELECT a.allocationId, a.date, a.shiftTiming, a.cabId
      FROM cab_allocation a
LEFT JOIN trip_details b
        ON a.allocationId = b.tripId
     WHERE b.tripStatus !='1'

LEFT JOIN will match records on cab_allocation that isn't on trip_details

A: User LEFT JOIN Instead Of INNER JOIN
SELECT a.* FROM cab_allocation as a
LEFT JOIN
trip_details as b ON a.allocationId=b.tripId
WHERE b.tripStatus !='1'

This image will definitely help you


text:
Q: LINQ to XML query Here I had very similar xml structure, but now I have this:
<Fields>
    <Company>My Company</Company>
    <Address2>Villa at beach</Address2>
    <Email2>email2@mail.com</Email2>
    <Mobile>333-888</Mobile>
    <ContactMethod>Facebook</ContactMethod>
    ...etc...
</Fields>

And now I need the same output as on the given link:
Company: My Company
Address2: Villa at beach
Email2: email2@mail.com
What would be the query for it?
Thanks,
Ile

A: Assuming you want the results as a dictionary you could do this:
        string xml =
@"<Fields>
  <Company>My Company</Company>
  <Address2>Villa at beach</Address2>
  <Email2>email2@mail.com</Email2>
  <Mobile>333-888</Mobile>
  <ContactMethod>Facebook</ContactMethod>
</Fields>";

        XDocument doc = XDocument.Parse(xml);
        XElement fields = doc.Root;

        Dictionary<string, string> result = fields.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value);

        foreach (var i in result)
        {
            Console.WriteLine(i.Key + ": " + i.Value);
        }


text:
Q: Phonegap can't add platform FireFox OS I have problems adding Firefox OS as a platform to my Cordova project. I tried the simplest way:
installed phonegap globally:
sudo npm install -g phonegap

created phonegap project:
cordova create HelloWorld com.domain.hello HelloWorld

CD'd into the new HelloWorld folder, then added iOS as platform:
cordova platform add iOS

which worked, but when trying to add Firefox OS, I get
[Error: Platform "firefoxos" not recognized as core cordova platform.]
I tried updating the platform with:
phone gap platform update firefoxos

but all I get is
[phonegap] updating Fire Fox OS platform...
[error] Platform "firefoxos" is not installed. See "platform list".

A: http://docs.phonegap.com/en/3.4.0/guide_cli_index.md.html#The%20Command-Line%20Interface
You want to use Cordova not PhoneGap (yes, there is a difference).
npm install -g cordova

then follow along in the link provided.
Additional information related to Cordova and FirefoxOS:
http://docs.phonegap.com/en/3.4.0/guide_platforms_firefoxos_index.md.html#Firefox%20OS%20Platform%20Guide


text:
Q: Sql query to find Album records which have no Song in the Songs table I am using a sqlite database in C# and need help with a  a sql query, I do not know if what I am trying to get is possible in single query my current solution is very inefficient and poor which I have put it in the end but first my problem...
I have two tables Songs and Albums, the tables are shown below
I need to write a query to get all Album records which have no song in the songs table...
    Songs

    Artist           Album         Filename
    Taylor Swift     Red           track1.mp3
    Taylor Swift     Red           track2.mp3
    Taylor Swift     Fearless      track1.mp3
    Taylor Swift     Fearless      track2.mp3
    Shakira          GrandesExitos track1.mp3

    Albums

    Artist           Album
    Taylor Swift     Red
    Taylor Swift     Fearless
    Taylor Swift     Beautiful Eyes
    Shakira          The remixes
    Jackson          Fearless
    Taylor Swift     The remixes

Need all records of Albums which have no Song in the Songs table,.
    So in this case the records of Album I need are

    Taylor Swift     Beautiful Eyes
    Shakira          The remixes
    Jackson          Fearless
    Taylor Swift     The remixes

My current solution is very inefficient and present below , I only need help with query not the C# code..
    dt = db.GetDataTable(String.Format("select distinct artist, album from files");

    foreach (DataRow r in dt.Rows)
    {
       string artist = (string)r[0];
       string album = (string)r[1];
       //I have create a status column in the Albums table to solve this problem
       query = string.Format("update Albums set status = {0} where artist = '{1}' and album = '{2}'", 1, artist, album);

       int nModified = db.ExecuteNonQuery(query);
     }
     // Then I get all records from Albums whose status is not 1
      dt = db.GetDataTable(select * from Albums where status = 0");

     }

A: You can use SQL statement EXISTS to check if no songs exist for specific album:
SELECT alb.Artist, alb.Album
FROM Albums alb
WHERE NOT EXISTS (
    SELECT 1
    FROM Songs s
    WHERE s.Artist = alb.Artist AND s.Album = alb.Album
)

This SQL Statement returns all records from table Album, that have no related records in table Songs.

A: You can try this
Select * from albums where album not in(select album from songs)

A: SELECT artist,album FROM Albums WHERE album NOT IN(SELECT DISTINCT Album FROM songs)

A: Don't forget about joins.
select
    album.Artist, album.Album
from
    Albums album
    left outer join Songs song
        on album.Artist = song.Artist and album.Album = song.Album
where
    song.Filename is null -- if it's valid for some reason to have a null song name, just change this to song.Artist is null

This way you don't need nested queries.


text:
Q: Can't installing R packages on linux mint 15 32bits I'm trying to install de ggplot library so I use this command
 install.packages('ggplot2', dependencies = TRUE)

When I write library(ggplot2) nothing happens there isn't an error message so I supouse that  the installation process work, but when I try to use the gplot function I get this:
 Error: could not find function "gplot"

I try to open R Studio as super user and install again, and also try to install the library from the tar.gz package but all the time I get the exact same error.
Thanks in advance

A: Actually the Function is "qplot" not gplot.
For reference visit:
https://cran.r-project.org/web/packages/ggplot2/ggplot2.pdf
Then go to Page No. 145 and check out for qplot (Quick plot):
Usage:
qplot(x, y = NULL, ..., data, facets = NULL, margins = FALSE,
geom = "auto", xlim = c(NA, NA), ylim = c(NA, NA), log = "",
main = NULL, xlab = deparse(substitute(x)),
ylab = deparse(substitute(y)), asp = NA, stat = NULL, position = NULL)

A: Perhaps you might try "ggplot()" rather than "gplot()"


text:
Q: Cache manifest is not working in MVC4 application Here is my CacheManifestHandler.

Manifest file generated  doesn't cache any thing that is specified in virtual path.
  Kindly review the code. Manifest file generated
  by the below code does not contain the items in cache file.

public class CacheManifestHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/cache-manifest";
        context.Response.Write("CACHE MANIFEST" + Environment.NewLine);
        context.Response.Write("CACHE:" + Environment.NewLine);

        WriteBundle(context, "~/bundles/jqueryval");
        WriteBundle(context, "~/bundles/modernizr");

        context.Response.Write(System.Web.Optimization.Scripts.Url("~/Images/orderedList1.png") + Environment.NewLine);
        context.Response.Write(System.Web.Optimization.Scripts.Url("~/Images/orderedList2.png") + Environment.NewLine);
        context.Response.Write(System.Web.Optimization.Scripts.Url("~/Images/orderedList3.png") + Environment.NewLine);
        context.Response.Write(System.Web.Optimization.Scripts.Url("~/Images/orderedList8.png") + Environment.NewLine);
        context.Response.Write(System.Web.Optimization.Scripts.Url("~/Images/orderedList9.png") + Environment.NewLine);

        context.Response.Write("NETWORK:" + Environment.NewLine);
        context.Response.Write("*" + Environment.NewLine);

        if (IsDebug)
            context.Response.Write(Environment.NewLine + DateTime.Now.ToLongTimeString());
    }

    private void WriteBundle(HttpContext context, string virtualPath)
    {
        if (IsDebug)
        {
            foreach (string contentVirtualPath in System.Web.Optimization.BundleResolver.Current.GetBundleContents(virtualPath))
            {
                context.Response.Write(Scripts.Url(contentVirtualPath).ToString() + Environment.NewLine);
            }
        }
        else
        {
            context.Response.Write(System.Web.Optimization.Scripts.Url(virtualPath).ToString() + Environment.NewLine);
        }
    }
}

Layout Page:
<!DOCTYPE html><html manifest="cache.manifest"></html>

Web Config:
    <httpHandlers>
  <add verb="GET"  path="cache.manifest"
 type="SampleCacheManifest.Models.CacheManifestHandler" />
  </httpHandlers>

Cache manifest generated:

    CACHE MANIFEST
    CACHE:
   /Scripts/jquery.mobile-1.4.2.js
   /Scripts/jquery-2.1.1.js
   /Scripts/jquery-ui-1.10.4.js
   /Scripts/jquery.unobtrusive-ajax.js
   /Scripts/Hwy905Scripts/Hwy905Custom.js
   /Scripts/Hwy905Scripts/CheckInventory.js
   /Scripts/Hwy905Scripts/CycleCount.js
   /Scripts/Hwy905Scripts/DirectedPickingSearch.js
   /Scripts/Hwy905Scripts/DirectedPutaway.js
   /Scripts/Hwy905Scripts/ManualPickingSearch.js
   /Scripts/Hwy905Scripts/Hwy905SerialNumberCapture.js
   /Scripts/Hwy905Scripts/UnitToUnit.js
   /Images/accent.png
   /Images/bullet.png
   /Content/HwyImages/Highway905Bg_1.jpg
   /Content/HwyImages/Highway905Bg_1.png
   NETWORK:
   *

   5:07:24 AM


text:
Q: FN keys F9 - F12 do not work on an Asus U30sd  Using the Keyboard Utility I was able to select the asus layout and after that I was able to get the majority of the function keys to work(screen brightness, wifi, sleep, num lock, and scroll lock). However F9 - F12 (disable/enable trackpad, volume mute, up, and down) do not work.
Does anybody have a fix for that? I've tried the eeepc scripts to see if that would work but it doesn't seem to do anything so far.
Update: After some digging I found some reference to an old acpi edit: http://forum.eeeuser.com/viewtopic.php?id=3573 I was able to follow the instructions however the first instruction requires that you change Power Management to have the acpid and acmd options filled. But this doesn't appear to be in latest version of ubuntu. Does anyone happen to know where to select these options? or is there another script that I would need to edit somewhere?
Also I've checked the asus downloads page and they don't appear to have anything for linux on their site available for download. Any help with this would be appreciated.
Update 2 Aug 2 2011: I upgraded to the ubuntu 11.10 alpha and it looks like my volume hotkeys are working.... I'm not sure what's difference is between 11.04 11.10 keyboard settings... but I guess they've figured it out...

A: These issues have been resolved as of the 11.10 update. All hotkeys are working on the new OS, thanks canonical for being awesome.


text:
Q: Why is it illegal for variables to start with numbers? Why is it illegal for variables to start with numbers?I know it's a convention but what's the reason?
Edit:
I mean variables like "1foo" or "23bar" not only numbers like "3"

A: Because the lexer in most languages will assume you are trying to specify a numeric literal.  And then you could declare variables that are indistinguishable from numeric literals, creating a huge bombshell of ambiguity.

A: Pop quiz: in a hypothetical language that permits a variable to begin with a number, what is this?
0xDEADBEEF

In C (and related languages) this can only be a hexadecimal number.  If a language allows a variable name to begin with a digit, that could be a variable or a hexadecimal number.  That's one quick example of potentially millions.

A: Numbers are interpreted 'as is' without any syntax whereas strings/characters are mostly represented with quotes.
So, the program can understand the difference between a variable name containing characters and a string of characters but it does not goes the same with numerals.

A: One reason, probably the most obvious one, is that it would make your life more difficult, without bringing anything reasonably useful to the table. For example, in C, you wouldn't be able to tell whether a string of digits is an identifier or a numeric literal.
int 10 = 15;
int 15 = 10 + 5;

In the second line, is 10 a variable holding the numeric literal 15 or is it the numeric literal 10?
Another reason is that allowing a variable name to begin with a digit makes error checking during compilation a lot more complicated, again, without bringing anything reasonably useful to the table.

A: In languages such as Prolog, Erlang, and some early versions of Fortran, you very nearly got to do this, for completely different reasons.
Prolog/Erlang don't have variable assignment, they have unification. IIRC, if X is a variable, then code following 2 = X, or X = 2 is processed if X may have the value 2. So if X is already unified with a value, then that value must be 2, and if not, X becomes 2 from then on. So writing 3 = 3 is fine - it should become a no-op, and 2 = 3 always fails - either a non-match in Prolog or (I think) a runtime error in Erlang. Numbers behave like variables which have already been unified with the value the numbers represent.
In early Fortran ( apologies for not having used fortran in twenty years and forgetting its syntax ), all function arguments were passed by reference, so if you have a function which was equivalent to void foo ( int &x ) { x = 3; } and called it with a number, the compiler would store the number in a static variable and pass that. So calling foo (2) would set that static stored value of 2 to 3. If it happened to use the same static variable for the literal 2 somewhere else, such as calling another function with the literal 2, then the value passed to the second function would be 3 instead.
So you can have variables which are syntactically identical to numbers, as long as they are automatically initialised to the value of the literal. But if you allow them to be mutable rather pure variables, weirdness abounds.


text:
Q: MPD: receive actual mpd-status with Linux bash script I want to know how to receive the actual status of the mpd player with a linux bash script. I know how to start and stop the player...
#!/bin/bash
mpc play
mpc volume +1
mpc stop

...but i need to know if mpd is playing a song or not. Also the current volume setting is interesting.
I tried to receive it with mpcstatus=cat /var/tmp/mpd_status or actvol=cat /var/tmp/mpd_volume but the files do not exist. I'm working with Volumio/Debian on a RaspberryPi.

A: I've got it!
Play:
if mpc status | grep playing >/dev/nul      # If mpd is playing
then
 command...
fi

Volume:
ACTVOL=`mpc status | sed -n '/volume/p' | cut -c8-10 | sed 's/^[ \t]*//'`


text:
Q: Weird glitch with accordion-style script No idea when or why this suddenly started happening which doesn't really help. >_<
This is my website: http://kaye.at/baby/
When 'August' is clicked and closed, it disappears and everything goes a bit glitchy! Doesn't seem to be happening on mobile safari though.
It doesn't seem to be a conflict as it still happens when I remove everything else 'Navigation/Header/Banner' off of the page.
Problem seems to occur no matter what month is at the top. If I remove 'August' it will happen to 'July'. :/

A: Fixed it. It was this on the CSS:
-webkit-transform: translate3d(0,0,0);


text:
Q: I am not getting image link in my firebase database even after following the firebase code example The link saves perfectly fine in storage but doesn't save at all in database in any format.
  private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

                StoringTextToFirebaseStorage();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

This is my code where I should be saving the link, I am using the code from https://firebase.google.com/docs/storage/android/download-files#download_data_via_url
I believe the issue may be that postimagesreference is also responsible for generating a random id for the image in the storage but I am not sure as I made a copy of the reference called postimagesreference 1 and it still didn't work. Is there anything I'm missing for it to save to database properly? Should I insert the code in a different location?
Here is my entire code if need be:
public class PostActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ProgressDialog loadingBar;

private ImageButton SelectPostImage;
private Button AddPostButton;
private EditText PostDescription;

private static final int Gallery_Pick = 1;
private Uri ImageUri;

private StorageReference PostsImagesReference;
//private StorageReference PostsImagesReference1;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();
    //PostsImagesReference1 = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
    AddPostButton = (Button) findViewById(R.id.add_post);
    PostDescription = (EditText) findViewById(R.id.post_description);
    loadingBar = new ProgressDialog(this);

    mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Update Post");

    SelectPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            OpenGallery();

        }
    });

    AddPostButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            ValidatePostInfo();
        }
    });

}

private void ValidatePostInfo()
{
    Description = PostDescription.getText().toString();

    if(ImageUri == null)
    {
        Toast.makeText(this, "Please select image", Toast.LENGTH_SHORT).show();
    }
    else if(TextUtils.isEmpty(Description))
    {
        Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Post Uploading");
        loadingBar.setMessage("Please Wait");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

        StoringImageToFirebaseStorage();

    }
}

private void StoringTextToFirebaseStorage()
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", PostsImagesReference);

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

                StoringTextToFirebaseStorage();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

private void OpenGallery()
{
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, Gallery_Pick);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        SendUserToMainActivity();
    }

    return super.onOptionsItemSelected(item);
}

private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
    startActivity(mainIntent);
}

}
My dependencies:
implementation fileTree(dir: 'libs', include: ['*.jar'])

        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'com.google.android.material:material:1.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'com.google.firebase:firebase-auth:17.0.0'
        implementation 'com.google.firebase:firebase-database:17.0.0'
        implementation 'com.google.firebase:firebase-storage:17.0.0'
        implementation 'com.squareup.picasso:picasso:2.71828'
        testImplementation 'junit:junit:4.12'
        implementation 'com.firebaseui:firebase-ui-database:6.2.1'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
        implementation 'com.google.firebase:firebase-messaging:20.2.0'
        implementation 'com.google.firebase:firebase-firestore:19.0.0'

        implementation 'com.android.support:multidex:2.0.1'

A: Within
 @Override

            public void onSuccess(Uri uri)
            {
                     String downloadUrl = uri.toString();
                     DatabaseReference db = FirebaseDatabase.getInstance().getReference();
                     db.child("users").child("pics").setValue(downloadUrl);

            }

The uri.toString(); will be your download url :)
private void StoringTextToFirebaseStorage(Uri downloadUrl)
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", downloadUrl.toString());

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {
                      StoringTextToFirebaseStorage(uri);

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}


text:
Q: Specifying ON DELETE NO ACTION in Entity Framework 7? In Entity Framework 7 when I am trying to apply a migration I get the error

Introducing FOREIGN KEY constraint 'FK_ChangeOrder_User_CreatedByID' on table 'ChangeOrder' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
  Could not create constraint. See previous errors.

I know in older versions of Entity Framework you would deal with this by adding
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

to the DbContext but in EF7 modelBuilder does not seem to have a .Conventions to it and google is only returning older EF 4 though EF 6 results.
How do I specific the ON DELETE NO ACTION constraint in Entity Framework 7?
Edit:
The answer provided by Oleg will apparently do it per Foreign Key but I would like to do it globally as it will much easier to use one line of code to declare this globally then have to specify code it out for every single one of the hundreds of relationships I will end up having.
Edit 2: Code for Oleg
public class ChangeOrder
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public Int16? ApprovedByID { get; set; }
    public Byte ApprovalStatusID { get; set; }
    public Int16 AssignedToID { get; set; }
    public Int16 CreatedByID { get; set; }
    public Byte CurrentStatusID { get; set; }
    public DateTime? DateApproved { get; set; }
    public DateTime? EndDate { get; set; }
    public Byte ImpactID { get; set; }
    public Byte PriorityID { get; set; }
    public DateTime? StartDate { get; set; }
    public Byte TypeID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string ReasonForChange { get; set; }

    [ForeignKey("ApprovedByID")]
    public User ApprovedBy { get; set; }

    [ForeignKey("ApprovalStatusID")]
    public ChangeApprovalStatus ApprovalStatus { get; set; }

    [ForeignKey("AssignedToID")]
    public User AssignedTo { get; set; }

    [ForeignKey("CreatedByID")]
    public User CreatedBy { get; set; }

    [ForeignKey("ImpactID")]
    public ChangeImpact Impact { get; set; }

    [ForeignKey("PriorityID")]
    public ChangePriority Priority { get; set; }

    [ForeignKey("TypeID")]
    public ChangeType ChangeType { get; set; }

    [ForeignKey("CurrentStatusID")]
    public ChangeStatus CurrentStatus { get; set; }
}

public class JobSightDBContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelbuilder)
    {
        base.OnModelCreating(modelbuilder);
    }

    DbSet<ChangeApprovalStatus> ChangeApprovalStatus { get; set; }
    DbSet<ChangeImpact> ChangeImapct { get; set; }
    DbSet<ChangeOrder> ChangeOrders { get; set; }
    DbSet<ChangePriority> ChangePriorities { get; set; }
    DbSet<ChangeStatus> ChangeStatus { get; set; }
    DbSet<ChangeType> ChangeTypes { get; set; }
    DbSet<User> Users { get; set; }
}

A: After digging around on GitHub, and working with a very patient guy from MS there, the current solution is to add this to the DbContext
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
    foreach (var relationship in modelbuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
    {
        relationship.DeleteBehavior = DeleteBehavior.Restrict;
    }

    base.OnModelCreating(modelbuilder);
}

A: The construction
modelBuilder.Entity("myNamespace.Models.ChangeOrder", b =>
    {
        b.HasOne("myNamespace.Models.User")
            .WithMany()
            .HasForeignKey("CreatedByID")
            .OnDelete(DeleteBehavior.Cascade);
    });

will means creating FK_ChangeOrder_User_CreatedByID with REFERENCES [dbo].[User] ([CreatedByID]) ON DELETE CASCADE. It should exist in protected override void BuildModel(ModelBuilder modelBuilder) of YourContextModelSnapshot.cs created during migration. I'm not sure that I full understand your question, but I think that you should either add such construct to XXXModelSnapshot.cs or to remove unneeded construct, which already exist here.
UPDATED: I see that you have the problem in the Model. You have the following properties in
public Int16? ApprovedByID { get; set; }
public Int16 AssignedToID { get; set; }
public Int16 CreatedByID { get; set; }

// navigation properties

[ForeignKey("ApprovedByID")]
public User ApprovedBy { get; set; }

[ForeignKey("AssignedToID")]
public User AssignedTo { get; set; }

[ForeignKey("CreatedByID")]
public User CreatedBy { get; set; }

By default migration try to set DeleteBehavior.Cascade on all the properties.
You can overwrite the behavior by changing OnModelCreating, which sets either DeleteBehavior.Restrict behavior for all the keys or to set on one only key the DeleteBehavior.Cascade or DeleteBehavior.SetNull behavior. For example, the below code uses DeleteBehavior.Cascade on CreatedByID (which creates ON DELETE CASCADE on the foreign keys) and DeleteBehavior.Restrict on other foreign keys (no ON DELETE on the foreign keys):
public class JobSightDBContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelbuilder)
    {
        base.OnModelCreating(modelbuilder);

        modelbuilder.Entity(typeof (ChangeOrder))
            .HasOne(typeof (User), "ApprovedBy")
            .WithMany()
            .HasForeignKey("ApprovedByID")
            .OnDelete(DeleteBehavior.Restrict); // no ON DELETE
        modelbuilder.Entity(typeof (ChangeOrder))
            .HasOne(typeof (User), "AssignedTo")
            .WithMany()
            .HasForeignKey("AssignedToID")
            .OnDelete(DeleteBehavior.Restrict); // no ON DELETE
        modelbuilder.Entity(typeof (ChangeOrder))
            .HasOne(typeof (User), "CreatedBy")
            .WithMany()
            .HasForeignKey("CreatedByID")
            .OnDelete(DeleteBehavior.Cascade); // set ON DELETE CASCADE
    }

    DbSet<ChangeApprovalStatus> ChangeApprovalStatus { get; set; }
    DbSet<ChangeImpact> ChangeImapct { get; set; }
    DbSet<ChangeOrder> ChangeOrders { get; set; }
    DbSet<ChangePriority> ChangePriorities { get; set; }
    DbSet<ChangeStatus> ChangeStatus { get; set; }
    DbSet<ChangeType> ChangeTypes { get; set; }
    DbSet<User> Users { get; set; }
}