text:
Q: Calculate the maximum variation in brightness of a star due to the presence of a planet in orbit Background: As a planet orbits around a star, the star's brightness periodically dims as shown in the following picture. By measuring the variation of brightness, we are able to deduce information about the system.

Source: http://blog.timesunion.com/weather/kepler62/2770/
Problem description: To calculate the maximum variation of brightness of a star with an orbiting planet.
Attempted solution:
Let $\ell_\text{max}$ be the brightness of the star (from the earth's POV) when the planet doesn't cross the star and $\ell_\text{min}$ when the planet crosses in its entirety the star. This is the max variation scenario and the variation is given by:
\begin{align*}
\left(\Delta \ell \right)_\text{max} = \frac{\ell_\text{min} - \ell_\text{max}}{\ell_\text{max}}
\end{align*}
When the planet doesn't cross the star:
\begin{align*}
\ell_\text{max} = \frac{L_\text{star}}{4\pi r_\text{es}^2}
\end{align*}
where $r_\text{es}$ is the distance between earth and star (from center to center).
When the planet crosses the star, then the power per $m^2$ that reaches the planet's surface is:
\begin{align*}
\frac{L_\text{star}}{4\pi r_\text{ps}^2}
\end{align*}
where $r_\text{ps}$ is the distance between planet and star. Therefore, the power that is blocked by the entire surface of the planet is:
\begin{align*}
\frac{L_\text{star}}{4\pi r_\text{ps}^2} \pi R_\text{planet}^2 =
\frac{L_\text{star}}{4} \left( \frac{R_\text{planet}}{r_\text{ps}} \right)^2
\end{align*}
The apparent brightness of the star, as seen from earth, will be (EDIT: the way we spread the power loss to the surface of a sphere with radius $r_\text{es}$ is most likely wrong):
\begin{align*}
\ell_\text{min}
&= \ell_\text{max} -
\frac{L_\text{star}}{4} \left( \frac{R_\text{planet}}{r_\text{ps}} \right)^2 \frac{1}{4\pi r_\text{es}^2} \\
&=
\ell_\text{max} - \frac{\ell_\text{max}}{4} \left( \frac{R_\text{planet}}{r_\text{ps}} \right)^2
\end{align*}
\begin{align*}
\left( \Delta \ell \right)_\text{max} =
\frac{\ell_\text{min} - \ell_\text{max}}{\ell_\text{max}} =
-\frac{1}{4} \left( \frac{R_\text{planet}}{r_\text{ps}} \right)^2
\end{align*}
Question 1: I've come accross some sites on the Internet and they give a result that is $\left(R_\text{planet}/R_\text{star}\right)^2$. Basically they take the ratio of planet's area to star's area without any more detailed calculations.
Which makes me think that my calculations are wrong. Any insights ?
Qestion 2 (added afterwards): Why doesn't the transit depth depend on the distance  between the planet and its star (or between us and the planet) ? If the planet was very very close to earth, wouldn't it cause an eclipse of the star ?

A: The inconsistency comes from assuming the planet has a greater-than-infinitesimal size while leaving the star as a point source.
Usually in transit diagrams we think of the star as a disk of radius $R_\mathrm{star}$ emitting parallel rays perpendicular to its surface. The $\pi R_\mathrm{star}^2$ area of the star is partially blocked by the $\pi R_\mathrm{planet}^2$ area of the planet. This is because, to first order, all $\pi R_\mathrm{star}^2$ of the star is emitting the same amount of light in our direction (each point on the surface emits isotropically in all $2\pi$ steradians outward).
If you want to look at the energy intercepted by the planet, things get more complicated. You found the total reduction in luminosity (turned into a brightness via the Earth-star distance) if we were to capture starlight from all $4\pi$ steradians around the star. But of course there is no reduction in the brightness seen by a small detector when the planet is not blocking the line of sight to the star, and at the same time the reduction is greater when the planet is actually transiting.
Take a look at this eclipse diagram from Wikipedia:

Imagine drawing a large sphere around the star. If I define $L_\mathrm{min/max} = 4\pi r_\mathrm{es}^2 \ell_\mathrm{min/max}$, then the $L_\mathrm{max} - L_\mathrm{min}$ you calculated is the change in the total power reaching this sphere between the cases of not having a planet and having a planet. But you can't take that reduction in power and distribute it evenly over the sphere, since during a transit we are in either the penumbra or antumbra, and the amount of light blocked is viewing angle-dependent.
The question you answered correctly is "how much power and power per unit area escapes the star in all directions given there is a planet in orbit?" The problem is during the transit we have a special line of sight. You can't take total power (equivalently, power per unit area averaged over $4\pi r^2$) and propagate it out to our location.


text:
Q: How to mutually replace (change) 2 div nodes in DOM with jQuery? Say I have two node references in variables nodeA and nodeB. I would like to mutually replace them with each other in DOM, keeping their all attributes and attached event handlers etc.
How can I accomplish this with jQuery?
I tried .replaceWith(...) but as I see it works with html text, and I would like to keep the DOM object itself.
There will be two .replaceWith(...) call. And the second one is on a node, which is not in the DOM... It seems not working...
Thanks in advance

A: It will be simmilar as switch variables, but you need to think it in terms of DOM.
var temp = $('<div>');
temp.insertAfter(first);
first.insertAfter(second);
second.insertAfter(temp);
temp.remove();

JS Fiddle: http://jsfiddle.net/qsutQ/

A: Using a function from this answer:
jquery: switch Elements in DOM
function swapElements(elm1, elm2) {
    var parent1, next1,
        parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}

Switching should be pretty simple and doesn't require creating any temporary elements:
swapElements($("#obj1")[0], $("#obj2")[0]);

Fiddle:http://jsfiddle.net/JvAMq/1/
(Click on the text to see alert boxes, the event bindings hold)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to scrape data I'm a newbie to this so trying to get some guidance. I'm trying to develop some code in VBA that will pull the price of an option from yahoo finance. Here's what I was able to put together so far:
Option Explicit

Sub Pull_Option_Price()

    Dim URL As String
    Dim IE As Object
    Dim HTML As Object
    Dim OptionPrice As Object

    Set IE = CreateObject("InternetExplorer.Application")

    IE.Visible = True

    URL = "https://ca.finance.yahoo.com/quote/SQ200717C00065000?p=SQ200717C00065000"

    IE.Navigate URL

    Do Until IE.ReadyState = 4: DoEvents: Loop

    Set HTML = CreateObject("HTMLFile")

    Debug.Print HTML.Document.getElementbyClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D
    (ib)").innerText

    Set IE = Nothing

End Sub

Everytime I run the code, I get runtime error 438 at the line:
Debug.Print HTML.Document.getElementbyClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").innerText

From what I've read on various forums thus far, I can only use .getElementsbyClassName with a lower IE version (below 9) whereas I have version 11, and for whatever reason I can't access References which I believe will allow me to do this another way.
How else can I scrape the website to get the option price?

A: Like braX wrote in his comment getElementsByClassName() generates a node collection. The elements of the collection are spcified by the css class name/s in the brackets. Every element has an index like in an array. The first index is 0. Your node collection has only one element. So you must use the index 0 to get it from the collection.
Another issue is HTML.Document. That doesn't work because HTML is an empty html document you created with the line Set HTML = CreateObject("HTMLFile") and you reference to document too. You can use the document in the IE directly.
The right line is:
Debug.Print IE.Document.getElementsByClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")(0).innerText
You can use the IE, but it is slow:
Sub Pull_Option_Price()

  Dim url As String
  Dim IE As Object

  url = "https://ca.finance.yahoo.com/quote/SQ200717C00065000?p=SQ200717C00065000"

  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate url
  Do Until IE.ReadyState = 4: DoEvents: Loop

  Debug.Print IE.Document.getElementsByClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")(0).innerText
End Sub

The faster option:
If there is no dynamic content you need to load on a page, you can use the faster xml http request. One restriction is getElementsByClassName() only works by early binding with xhr. So you need the following two excel references to libraries:
Microsoft HTML Object Library
Microsoft XML, v6.0
Sub Pull_Option_Price_xhr()

  Dim xhr As MSXML2.XMLHTTP60
  Dim htmlDoc As MSHTML.HTMLDocument
  Dim url As String

  url = "https://ca.finance.yahoo.com/quote/SQ200717C00065000?p=SQ200717C00065000"

  Set xhr = New MSXML2.XMLHTTP60
  Set htmlDoc = New MSHTML.HTMLDocument

  xhr.Open "GET", url, False
  xhr.Send
  htmlDoc.body.innerHTML = xhr.responseText

  Debug.Print htmlDoc.getElementsByClassName("Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")(0).innerText
End Sub


text:
Q: Render view from code in /lib Let's pretend we have a Rails project with a class named Foo residing in the lib directory.
We want to generate some HTML based on its attributes.
Now, creating a big string by concatenating HTML fragments appropriately doesn't feel right in the least bit.
My question is: is there a blessed way to do it?

A: You have a couple pretty straightforward options. If you're using ERB, you can do something like:
ERB.new(File.read(the_file_path)).result

I'm using a library called Tilt (https://github.com/rtomayko/tilt) in one of my applications to render a HAML template. Here's the exact sausage factory code that I'm running right now:
template = Tilt.new(ITEM_TEMPLATE) # ITEM_TEMPLATE is the path of a .haml file
template.render nil, {:item => item, :item_details => item_details}
# item and item_details are now available as local variables in the partial

If you don't want to go the templating route, you could try something like Erector (http://erector.rubyforge.org/userguide.html) as well.
Worst case scenario: instead of concatenating fragments, you could use the HEREDOC to format it nicely:
<<-HTML

    #{thing.method}

#{thing.attribute}

HTML


text:
Q: Friis Transmission Equation and Wavelength dependence The "modern" form of the Friis Transmission Equation states that :
$$\frac{P_r}{P_t} = G_t G_r \left( \frac{\lambda}{4 \pi d} \right)^2$$ where $G_t$, $G_r$ are unitless antenna gains, $\lambda$ is the wavelength "representing the effective aperture area of the receiving antenna", according to Wikipedia, and $d$  is the distance separating the antennas.
If I were to consider perfect isotropic antennas, of gain $1.0$ (or $0$ dBi), this could be rewritten as :
$$P_r=P_t\left( \frac{\lambda}{4 \pi d} \right)^2$$
Under this form, it could be understood that the biggest the wavelength, the biggest the received power at the receiving antenna. I'm pretty sure this is not actually the case, but I'm having trouble understanding why.
My current understanding is that the gains $G_t$ and $G_r$ are functions of $\lambda$, but this collides with the assumption of perfect isotropy of the antennas, meaning a value of $G_t$ and $G_r$ equal to $1$.

A: The confusion is caused by your fixing directivity. A receive antenna's directivity is proportional to its effective receive area $A_r$, so that if it is immersed in a flux of density $S$ then, assuming perfect matched conditions, it receives $P_r=SA_r$ power, and $S=\frac{P_tG_t}{4\pi d^2}$. The effective receive directivity is then defined as $G_r=\frac{4\pi A_r}{\lambda^2}$, or $A_r = G_r\frac{\lambda^2}{4\pi}$. It can also be shown that the receive and transmit directivities can be equal under quite general conditions but not always. Some pulse radar antennas do behave that way. Note that I use the term directivity and not gain for the latter also depends on the RF plumbing behind the antenna.
Just based on dimensional considerations the effective area must be proportional to $\lambda^2$ the wavelength being the only natural length scale. It is a lot more difficult to understand from where the $4\pi$ comes in the denominator, but for details you should consult Slater whose argument you rarely find spelled out anywhere else.
In practice, for any antenna you are usually given $\lambda$ (the operating frequency) and the available effective area to occupy, and consequently the maximum directivity available to you to close the receive link.

You can also immediately see based on dimensional argument that a formula, such as $\frac{P_r}{P_t}=k G_t G_r \frac {\lambda^2}{d^2}$ should hold for dimensionless number $k$ that depends on the geometry of the antennas. That is so because you know that the received power must be inversely proportional to $d^2$ and the factors of $G_t$ and $G_r$ are just there to express how much energy flux (power) goes into the maximum transmit/receive directions, then the only available dimensional quantity to make the ratio a dimensionless number is $\lambda^2$


text:
Q: Best way to indicate more results available We have a service to return messages. We want to limit the number returned, either allowing the caller to specify the max number to return, or else to use an internal hard limit. We also have thought it would be nice to include in the response whether more messages are available. The "best" way to go about this is not clear.
Here are some ideas so far:

*

*Only set the "more messages" indicator if the user did not specify a max limit, and the internal max limit was hit.

*Same as #1 except that "more messages" indicator set regardless of whether the internal hard limit is hit, or the user-specified limit is hit.

*Same as #1 (or #2) except that we internally read limit + 1 records, but only return limit records, so we know "for sure" there is at least one additional message rather than "maybe" there are additional messages.

*Do away with the "more messages" flag, as it is confusing and unnecessary. Instead force the user to keep calling the API until it returns no messages.

*Change "more messages" indicator to something more akin to an EOF indicator, only set when the last message is known to have been retrieved and returned.

What do you think is the best solution? (Doesn't have to be one of the above choices.) I searched and couldn't find a similar question already asked. Hopefully this is not "too subjective".

A: Usually, it helps to look at how others might have done something similar already, and see if that can be used. This is typically how patterns emerge in software (and some are then even formalized as 'design patterns').
I am most familiar with oData, and in ASP.NET, oData supports both client and server side limit. However, it is up to the servers to decide if they want to set an upper limit even if client specified a response size. For example, if the client asked for a million messages, the server may still choose to limit it to 100 to save the bandwidth costs, and not run into performance issues, etc. So oData implements it the following way:

*

*Client can specify how many records to return via the $top parameter.

*Client also specifies how many records to skip via the $skip parameter.

Thus if a client wanted results from 1 to 20, it would set $top=20 and issue the query. For the next page, it would skip the first 20 and thus set $skip=20&$top=20.

*

*The server can also limit the results.

*In that case, in the response, it puts a link for the next page, using the odata.nextLink element.

Thus if a client issued a query and did not specify any limit, the server could decide to send 50 rows and then along with the result, send the query for the next page:
"odata.nextLink":"http://localhost:23645/api/Movies?$skip=50"

By setting $skip=50, the next query will start at item 51. The link I provided earlier to MSDN blog has more details.
You could consider utilizing one or both of these approaches, especially if you are returning JSON responses. If you have developers coming to use your service, they might be able to more easily understand (esp. if they have worked with oData). Or you could pick whichever framework is most likely to be known to your developers, and model based on that.
FYI, you don't have to necessarily model both either. However, in this case, it seems quite likely that if you're able to model $top and $skip, then creating the next page link is quite trivial if you choose to limit on the server.

A: As a consumer of API's, my preference would be 3 or 5.  While it makes coding easy to just go until you get nothing, API requests can be costly.  The choice between 3 or 5 I think would really come down to the penalty for retrieving limit + 1 items.  If there is very little overhead to the backend to check, then it is a very friendly thing to let the user know before they make one more needless request.

A: Maybe you can offer some more flexibility to the client. Your request can have a startWith element and the number of messages to retrieve noOfMessages. Your response can have a field called totalMessages that will held the total number of messages. This will allow you client to have something similar to pagination. startWith will default to zero; noOfMessages to a decent value.
For example if you have 56 messages, if the client wants to retrieve batches of 20s, they can send the following calls:
Request 1:
noOfMessages: 20

Response1:
...message list...
totalMessages: 56

Request 2:
startWith: 21
noOfMessages: 20

Request 3:
startWith: 41
noOfMessages: 16


text:
Q: Getting HTTP/0.0 307 Temporary Redirect in connecting to my vps without typing https:// I ran a graphical version of v2ray(X-UI) on one of my VPS on Hetzner, I also add an A record to bind the IP of this VPS to a DNS on my Cloudflare account.
Well with the below commands, I tried to get a certificate for this subdomain with acme.sh and using letsencrypt as CA provider:
    7  curl https://get.acme.sh | sh
    8  ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt
    9  ~/.acme.sh/acme.sh --register-account -m myemail@mailserver.com
   10  ~/.acme.sh/acme.sh --issue -d sub.mydns.com --standalone
   11  ~/.acme.sh/acme.sh --installcert -d sub.mydns.com --key-file /root/private.key --fullchain-file /root/cert.crt

After adding the IP address of VPS to Cloudflare and setting it in DNS-only mode like the below image:

When I try to connect my panel without typing the https://, I've just got the below page from Firefox:

And also return nothing in the Google Chrome browser(with or without typing https://):

But typing https:// shows me the panel successfully:

Does anyone have any idea why this is happening and how I can fix this?


text:
Q: in ember how are view's names determined with respect to the router? ember rc1.  i don't understand how views are automatically instantiated by naming convention wrt their routes.
i have the following resource defined:
  this.resource('groups', { path : '/groups' }, function() {
      this.resource('received', { path : '/received' }, function() {
        this.route('show', { path : '/:asset_link_group_id' });
  });

when the router instantiates the view for groups/received/index it looks for a view named ReceivedIndexView.  why not GroupsReceivedIndexView ?
the same goes for controllers - it looks for ReceivedIndexController, not GroupsReceivedIndexController. why?

A: "Routes nested under a resource take the name of the resource plus their name as their route name", from http://emberjs.com/guides/routing/defining-your-routes/
My understanding of the setup is that a route is looked at and then it's parent resource in order to automatically derive the patching.  In this way /resource1/sameresourcename/new and /resource2/sameresourcename/new will actually cause problems because it doesn't use the full "tree" to generate these paths/names.

A: I spent a lot of time researching this as i was having problems understanding the hows and whys of the naming conventions. This is the most informative site I have found in regards to which pieces of the route/resources are picked to create the view/controller/resource name.
From Peter "We intentionally only nest one level deep. The correct solution is what @jamesarosen suggested."
https://github.com/emberjs/ember.js/issues/2086


text:
Q: Curve Fitting Data using Polynomial I have this data set in Mathematica:
data = {{1980, 4716.71636}, {1981, 4530.36984}, {1982, 4301.97069}, {1983, 4335.91656}, {1984, 4468.26205}, {1985, 4484.33818}, {1986, 4487.85587}, {1987, 4680.83405}, {1988, 4885.5905}, {1989, 4948.02116}, {1990, 5121.17944}, {1991,  5071.56391}, {1992, 5174.6706}, {1993, 5281.38661}, {1994, 5375.0338}, {1995, 5436.69799}, {1996, 5625.04188}, {1997, 5701.92092}, {1998, 5749.89306}, {1999, 5829.51995}, {2000, 5997.29891}, {2001, 5899.85548}, {2002, 5942.42141}, {2003, 5991.19093}, {2004, 6105.44411}, {2005, 6130.55242}, {2006, 6050.3846}, {2007, 6127.88822}, {2008, 5928.25633},{2009,5493.54791}, {2010, 5700.10834}, {2011, 5572.58478}, {2012, 5371.77717}, {2013, 5522.90837}, {2014, 5572.10631}, {2015, 5422.96568}, {2016, 5306.66246}, {2017, 5270.74853}, {2018, 5416.27788}}

But I do not know how to code to curve fit it in the program. I have read multiple tutorials and watched videos on curve fitting polynomial data, but it is either about creating the dataset from an already established equation, or the instructions just flat out confused me. I have it curve fitted on Excel with a nasty equation that starts with an $x^6$ and numbers with awful decimals. The goal is to get a cleaner equation; how can I do this?
I have the data graphed as such:

A:
The goal is to get a cleaner equation how can I do this?

You can use (the experimental) FindFormula.
Here is an example:
dsFormulas = FindFormula[N@data, x, 5, All, SpecificityGoal -> 1, RandomSeeding -> 23];
dsFormulas = dsFormulas[SortBy[#Complexity &]]

Select a "cleaner" formula:
formula1 = Keys[Normal[dsFormulas]][[1]]

(* 5325.93 + 731.662 Cos[19. x] *)

Plot the formula together with the data:
ListPlot[{data, {#, formula1 /. x -> #} & /@ data[[All, 1]]},
 Joined -> {False, True}, PlotLegends -> {"Data", "Found formula"},
 AspectRatio -> 1/3, PlotTheme -> "Detailed", ImageSize -> Large]

A: The choice of basis makes a difference.  You don't need a Chebyshev basis (see my comment), but a power basis $\{\,(x-c)^k\,\}_{k=0}^n$ centered at a number $c$ in the domain of the data will behave better than one centered far outside it, such as the standard power basis $\{\,x^k\,\}_{k=0}^n$. That's why the OP's polynomial looks so horrible.
Two alternatives are to center at beginning or in middle of the data:
domain = MinMax@data[[All,1]];
basis = (x - First@domain)^Range[0, 6];
basis = (x - Mean@domain)^Range[0, 6];

Here is the result using the first basis:
basis = (x - First@domain)^Range[0, 6];
lmf = LinearModelFit[N@data, basis, {x}];
lmf[x]
Plot[
 lmf[x], {x, Min@domain, Max@domain},
 Prolog -> {Point@data},
 Frame -> True, GridLines -> Automatic
 ]

(*
  4663.63 - 208.806 (-1980 + x) + 50.4679 (-1980 + x)^2 -
   3.9543 (-1980 + x)^3 + 0.167273 (-1980 + x)^4 -
   0.00378372 (-1980 + x)^5 + 0.0000344867 (-1980 + x)^6
*)

A nicer presentation of the polynomial may be achieved in terms of the increment from the beginning of the data:
lmf[First@domain + Δx]

(*
  4663.63 - 208.806 Δx + 50.4679 Δx^2 - 3.9543 Δx^3 +
   0.167273 Δx^4 - 0.00378372 Δx^5 + 0.0000344867 Δx^6
*)

One purpose in fitting is to estimate parameters of a model of a phenomenon from experimental data.  That doesn't seem to have any applicability here, which may be what prompted @MassDefect to suggest an alternative approach.
By the way, I think the OP's original fit was done correctly.

A: EDIT:
If you just want a cleaner function, then stick with the excellent answers from @AntonAntonov and @MichaelE2. As they have shown, curve fitting can be done quite easily for your data in Mathematica, but it's my opinion that it's either the wrong tool for the job, or at least the results are more easily misinterpreted (unless you have a compelling reason to use a function that you haven't expressed here). Also, I stole the plot styling from @AntonAntonov's answer and forgot to give them credit.
ORIGINAL:
I would argue that data smoothing would be better here than curve fitting. Generally, the point of curve fitting is to either extract fitting parameters or to be able to extrapolate (a little ways) past the edge of the data. To do that, you need to have the model (or a small set of candidate models) first.
By modelling with a polynomial of any kind, you're essentially predicting that the emissions will go to $\pm \infty$ at some point in the future and were $\pm \infty$ in the past. By using a cosine model, you're predicting a constant oscillation in the emissions. Either way, the fitting constants/equations are almost certainly meaningless and there is probably no predictive power in choosing a random model. I would strongly caution against using any fitting constants returned for any of these curves unless you have other reasons to believe the model is correct.
With data smoothing, you're simply smoothing out sudden jumps in the data to allow the eye to more clearly follow a long-term trend. You can also do things like filter the data to remove long-period oscillations instead of short ones if you know that they are caused by some outside force.
There are various kinds of filters already available in Mathematica, though you can of course implement any kind of filter you like). I chose a Gaussian filter with a radius of 3 here (so that data over a 7 year period is considered), though other common options might be LowpassFilter, MovingAverage, or MeanFilter.
ListPlot[{
  data,
  {data[[All, 1]], GaussianFilter[data[[All, 2]], 3]}\[Transpose]
  },
 AspectRatio -> 1/3,
 Joined -> {False, True},
 PlotLegends -> {"Data", "7-Year Trend"},
 PlotTheme -> "Detailed"
]


text:
Q: Error 13 VBA in simple find and replace I am new at programmming, so sorry if my question is boring.
I am trying to create a macro that checks for string "Meh" in a range of cells and substitutes the cell above it for "BlahBlah"
So far my code:
Sub Findandreplace()

Dim E As String, Wide As Range, R As Range

E = "Meh"

Set Wide = Range("A1:CM300")

For Each R In Wide

    If InStr(R.Value, "Meh") > 0 Then
        R.Offset(-1, 0).Value = "BlahBLah"

End If

It worked the first time i run it, but now it gives me an error type 13 in the if sentence. I know I have to dim something, but don´t know what.
Thanks for your help!

A: No you dont have to Dim anything. By the way variable names are terrible.
You get type mis match error when the cell value itself is error (like #N/A, #DIV/0!)
Check that in your code with IsError
Sub test()
Dim E As String, Wide As Range, R As Range

E = "Meh"

Set Wide = Range("A1:CM300")

For Each R In Wide

    '/ Check if the cell contains an error.
    If Not IsError(R) Then
        If InStr(R.Value, E) > 0 Then
            R.Offset(-1, 0).Value = "BlahBLah"
        End If
    End If
Next

End Sub


text:
Q: Does GNU Makefile support recursive invocations of .PHONY targets like "clean"? I have a C/C++ project that is organized like this:
project
   |
   +---- c
   |     |
   |     +---- subproject1
   |     |         |
   |     |         +---- bin
   |     |         |
   |     |         +---- obj
   |     |         |
   |     |         +---- src
   |     |
   |     +---- subproject2
   |               |
   |               +---- bin
   |               |
   |               +---- obj
   |               |
   |               +---- src
   |
   +-----+ cpp
   |     |
   |     +---- subproject1
   |     |         |
   |     |         +---- bin
   |     |         |
   |     |         +---- obj
   |     |         |
   |     |         +---- src

  etcetera

At the project level, there's a Makefile that contains the following:
SUBDIRS = c cpp

all: $(SUBDIRS)

.PHONY: $(SUBDIRS)

$(SUBDIRS):
    $(MAKE) -C $@

The c and cpp sub-directories contain similar Makefiles with different SUBDIRS definitions. Typing make at the command prompt from the project, c or cpp directories causes make to change directory to each sudb-directory in SUBDIRS and run make with that sub-directory's Makefile. This behaves exactly as described in the GNU Make Manual and I'm very happy with it. The manual also states that you can add a target like clean after the $@ and it will invoke that target in the sub-directory's Makefile. Also great, but what the manual doesn't give guidance on is what to do when SUBDIRS contains more than one sub-directory, as my project and c directories do. I'm going to give you the two methods that I know work and then I'll pose my question.

*

*Add a target for each sub-directory in the clean target's recipe:

  clean:
      $(MAKE) -C c $@
      $(MAKE) -C cpp $@

*Loop over each sub-directory in the clean target's recipe (basically the same as method 1, but easier to add more sub-projects to):

  clean:
      @for subdir in $(SUBDIRS); do $(MAKE) -C $$subdir $@; done

My question is, is there a way of achieving the above that requires using only existing GNU make constructs, something like this (which doesn't work btw):
$(SUBDIRS) clean:
    $(MAKE) -C c $@

A: I would declare per-directory phony clean targets and add them as pre-requisites of clean:
CLEANSUBDIRS = $(addprefix clean-,$(SUBDIRS))
.PHONY: clean $(CLEANSUBDIRS)
clean: $(CLEANSUBDIRS)
$(CLEANSUBDIRS): clean-%:
    $(MAKE) -C $* clean


text:
Q: why the on start activity - the focus is on my EditText and i can't remove it? I have few ui component on my application ( button, EditText , ListView ).
When i start my application the focus is always on the EditText as default ( even if i didn't focus on this EditText control ) - and the cursor is blinking on this EditText control.
i can use 'setCursorVisible' method - but i don't see any reason to do it.
How i make this EditText to be focus only on click on this controler ?
I try to define 'android:focusableInTouchMode="true"'  but this is not help me.

A: Add android:focusable="true" & android:focusableInTouchMode="true" to a parent element (LinearLayout/RelativeLayout/FrameLayout/..) of your layout. Because the first focusable element in hierarchy gains the focus the parent element will take it and it should resolve your problem.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/companyInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:errorTextAppearance="@style/error_appearance">

            <AutoCompleteTextView
                android:id="@+id/company"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_company"
                android:inputType="text"/>

        </android.support.design.widget.TextInputLayout>

</LinearLayout>


text:
Q: How to call a NodeJs resource from React Js I am trying to call a JSON resource from a URL (on a Node.Js) environment from a React JS project. My attempts so far fail or return nothing.
The Resource API
/* GET users listing. */
app.get('/', function (req, res, next) {
    // res.send('respond with a resource');
    res.json([{
        id: 1,
        name: "Hiccup",
        password: 'hiccup'
    }, {
        id: 2,
        name: "King Arthur",
        password: 'king-arthur'
    }]);
});

React JS
componentDidMount() {
    let url = 'http://localhost:4000/';

    const myHeaders = new Headers();

    fetch(url, {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors',
        cache: 'default',
        credentials: 'omit',
        headers: {
            'Content-Type': 'application/json'
            },
        })
    .then(res => {
        if (!res.ok) {
            throw new Error('Network response was not ok');
        }

        return res.json();
    })
    .then(data => {
        this.setState({ revData: data })
    })
    .catch(err => this.setState({ revData: err }));
}

This gives an error:
Access to fetch at 'http://localhost:4000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
:4000/:1

Failed to load resource: net::ERR_FAILED

Changing mode: 'cors', to mode: 'no-cors' doesn't help.
What am I missing? How should I be going on about it?
Thank you all in advance.

A: try :
npm install cors --save

and just add these lines in your main file where your request is going.
const cors = require('cors');
const express = require('express');
let app = express();
app.use(cors());
app.options('*', cors());


text:
Q: Pivoting Data into a time series format I'm having trouble getting my data into the format I want in a quicker way than copy and pasting. Right now my data looks something like this:

I would like to pivot it so that I have category in a column next to date so it will look something like this:

I feel that this should be a simple transformation but I can't figure it out.
Any help on this would be appreciated!

A: If you have just two categories:
Date column formula:
=INDIRECT("$A"&(ROUND(ROW()/2,0)-MOD(ROW(),2)+1))

Value column formula:
=INDIRECT(ADDRESS((ROUND(ROW()/2,0)-MOD(ROW(),2)+1),MOD(ROW(),2)+2))

The date column formula will pull from column A row 1 for two rows, then move to row 2, etc...
The Value column will follow the same row format as date column and bounce back and fourth between columns 2 and 3 (B and C).
You should be able to copy and paste one row with these two formulas down your sheet.


text:
Q: USB Hard drive has very small chance of being recognized by Macbook Pro each time it is connected, but works with other machines I have a WD "My Passport" 1TB external hard drive. It isn't recognized by my Macbook Pro (retina, 2013) or a friend's very similar model, but it works with every other machine I've tried, including two Linux netbooks and an older iMac.
Sometimes, it mounts after multiple tries unplugging and replugging the cable. Usually, the hard drive spins up and lights its status LED, but it is not mounted or recognized by Disk Utility or the diskutil list command.
This question seems to describe a similar issue, but their drive doesn't connect every few dozen attempts like mine does.
What could be causing this issue?
Edit: When the drive is plugged in, this is output to dmesg:
Starting poll type 4
Restarting poll type 4
Command 0x2 completed. inCount: 2 data:0x5Command 0x1 completed. inCount: 2 data:0x1001Command 0x16 completed. inCount: 2 data:0x40e0Command 0xa completed. inCount: 2 data:0x0Command 0xb completed. inCount: 2 data:0x0Command 0x12 completed. inCount: 2 data:0xffffCommand 0x13 completed. inCount: 2 data:0xffffCommand 0xf completed. inCount: 2 data:0x1b6eCommand 0x10 completed. inCount: 2 data:0x1bacSmartBattery: finished polling type 4
kxld[net.lundman.spl]: In interface net.lundman.kernel.dependencies.28 of __kernel__, couldn't find symbol _panicstr

kxld[net.lundman.spl]: The following symbols are unresolved for this kext:
kxld[net.lundman.spl]:  _panicstr
Can't load kext net.lundman.spl - link failed.
Failed to load executable for kext net.lundman.spl.
Kext net.lundman.spl failed to load (0xdc008016).
 Dependency net.lundman.spl of kext net.lundman.zfs failed to load.
Kext net.lundman.zfs failed to load (0xdc008015).
Failed to load kext net.lundman.zfs (error 0xdc008015).
Kext load request buffer from user space still retained by a kext; probable memory leak.

Edit 2: That output is still displayed when connecting a working flash drive, along with other stuff about USB media and about filesystems. It is not unique to the drive in this question, but it is the only thing outputted when this drive is connected.
Edit 3: So I did in fact have openZFS installed, at least partially. (No idea how or why). After running their uninstall script, nothing is output when this drive is plugged in at all.
Edit 4: Connecting with an ordinary MicroUSB cable instead of a USB 3 cable works every time. I realized that every other device I tested it on that worked didn't support USB 3. I just tested it with a Windows device that supports USB 3, and while it is better than the Mac, it still has a problem recognizing the drive. Interestingly, the Windows computer shows the drive as not supporting USB 3.0.

A: I had the same issue with a WD Elements 2.5" 2TB disk on my retian macbook with macOS High Sierra.
My assumption is that the disk "fell" off the USB bus and macOS instead of gracefully retrying is just giving up.
In my case the disk worked for an hour or two, but then I got the error that I should eject Disks before unplugging them and the errors in the dmesg.
I guess this is a combination of macOS being not very forgiving and the WD on-disk USB controllers being a little wonky.
I was using a USB3 hub between the macbook and the disk, so maybe that was the source of wonkyness.
I have no ZFS drivers installed.


text:
Q: How to access subcollections from Firestore in Javascript? I want to create a collection and a subcollection, with the collection's name being a variable that the user inputs. I don't know the code to actually call the subcollection when the collection is a variable.
I've done it before in Dart, and essentially used:
return db.collection('$company/users').doc(cred.user.uid).set({...
but js appears to just read it as a string.
I've tried several variations:
return db.collection('${company}/users').doc(cred.user.uid).set({...
return db.collection(company'/users').doc(cred.user.uid).set({...
return db.collection(company + '/users').doc(cred.user.uid).set({...
return db.collection(company, '/users').doc(cred.user.uid).set({...
return db.collection(company).collection('users').doc(cred.user.uid).set({...

Expected results: Collection and Subcollection area created, with the collection taking in the company String and the subcollection being users.
The exact code works with a single collection, whether I try "users" or the variable company, but I don't know how to get them to work together.
Actual results: No collection made, error of "Invalid Collection Reference"
(slightly different errors depending on what I tried).


text:
Q: Prime beginning by 2 How to deal with that type of question ?
Are there infinite prime numbers beginning by 2?
I know that there infinite prime ending by 1,3,7 and 9 by Dirichlet's prime number theorem.
I'am only interested by the first term in special case 2. Not for a generalization. I think that this specific case provide a simpler proof than the generalization.


text:
Q: playing a playlist created in windows I had created a playlist in windows 8 which was in .wpl format.
I later converted it to .m3u format.
But i am not being able to play from either of the two on my ubuntu 14.04 which is on the same machine as my windows 8.

A: OK, Here's how I did it I replaced this part of my Windows playlist:
C:\Users\username\Music\

with
/home/username/Music/

Then replaced the \ with /, which got the playlist to play in VLC, but not Banshee.

A: use vlc. open a terminal and type
sudo apt-get install vlc

and then open the wpl or m3u with vlc player.

A: I know this is quite late, but I'm posting this for other future visitors of this thread:
Apart from downloading VLC
(which has created a bit of a headache for me trying to set the hotkeys only to find out that the hotkeys failed to work after the first time it was set, but that's another story.)
, you can use Video(the Ubuntu built-in movie player).
But note that you need to edit your playlist's text file in gedit/Vim before it can be played properly. Also, you need to make sure that your playlist is in the proper location before it can be played by Video.
Here's the detailed procedures:

*

*Trasnfer the WHOLE music folder from Windows onto your Linux machine. (e.g. say the folder is initially E:\MyWindows\Music on the Windows machine, which includes a sub folder E:\MyWindows\Music\Instrumental)

*Transfer your playlist also from Windows to Linux (if it is not already in the file transferred in the previous step), into the same destination file.

*Open terminal in the destination directory (e.g. say you have put it in /home/MyUbuntu/Music, then open terminal and type
cd Music)

*Once you're in that directory, type gedit [InsertPlaylistNameHere].wpl (or use Vim if you )

*Ctrl + H to delete all "E:\MyWindows\Music\" (i.e. the file location appending the song name) and replace all "E:\MyWindows\Music\Instrumental\" to "Instrumental/"
Note the change in the direction of the last slash.
Once you're done just close the gedit and open the .wpl with Video. It should work, although the album arts may not show.
(I have not found a method to make it work with Rhythmbox though.)


text:
Q: Execute JavaScript commands in Chrome Console from Java App I want to create a simple app that will execute JavaScript commands in Chrome Console on a specific page and will return an output.
Namely, I want to get all accessible links from the current page. I can do it by running the following command in Chrome Console:
urls = $$('a'); for (url in urls) console.log(urls[url].href);

It will return a set of links as output, which I'd like to be able to process in my application.
I can run it manually from Chrome Console, but I want to automate this task because I have a lot of links to work with.
The pseudocode is something like the following:
function runCommandOnSite(command, site) { ... }

function main() {
  let site = "facebook.com";
  let command = "urls = $$('a'); for (url in urls) console.log(urls[url].href)";
  let result_links = runCommandOnSite(site, command);
  console.log(result_links);
}

Note: any programming language which could be run from Linux Desktop is acceptable.

A: Sounds like you want to scrape a web page and get all the URLs in that web page. Whenever you face a problem like this, always search for Web Crawler examples for any preferred language.
Given below are some examples for scraping the set of URLs from a given webpage. Of course, you might have to do some filtering on the output. But, do some playing around and see...
Python 3 - Beautiful Soup 4
from bs4 import BeautifulSoup
from urllib.request import urlopen
import ssl

# to open up HTTPS URLs
gcontext = ssl.SSLContext()

# You can give any URL here. I have given the Stack Overflow homepage
url = 'https://stackoverflow.com'
data = urlopen(url, context=gcontext).read()

page = BeautifulSoup(data, 'html.parser')

for link in page.findAll('a'):
    l = link.get('href')
    print(l)

Java - JSoup
Have a look at this example.
Node JS - Cheerio
Have a look at this example.
Use Selenium Web Drivers - For Most Programming Languages
I will not explain this section, because it is so wide, and beyond the scope of this answer.


text:
Q: core controller not overidden I want to override Mage_Sales_Recurring_ProfileController in my custom module.
My /etc/config.xml
<config>
    <frontend>
        <routers>
            <sales>
                <args>
                    <modules>
                        <Namespace_Module before="Mage_Sales">Namespace_Module</Namespace_Module>
                    </modules>
                </args>
            </sales>
        </routers>
    </frontend>
</config>

and my controller file
Namespace/Module/controllers/Sales/Recurring/ProfileController.php

require_once("Mage/Sales/controllers/Recurring/ProfileController.php");
class Namespace_Module_Sales_Recurring_ProfileController extends Mage_Sales_Recurring_ProfileController
{
   public function indexAction()
    {
       // custom code
    }
}

But the control doesnt go in the overriden controller, but the core controller only.
Can anyone tell the reason why.

A: You can do one (and just one) of the following.

*

*Put your controller in Namespace/Module/controllers/Recurring/ProfileController.php and name the class Namespace_Module_Recurring_ProfileController.  (I recommend this one).

*Change in config.xml this <Namespace_Module before="Mage_Sales">Namespace_Module</Namespace_Module> to this <Namespace_Module before="Mage_Sales">Namespace_Module_Sales</Namespace_Module>.  You should use this only if you override multiple controllers from multiple modules in your module. This helps you group the controllers better. If you only override controllers from Mage_Sales, there is no need to do this. Go with the first approach.


text:
Q: DependsOn with if else statement in cloudforamtion yml template Hi i have 2 AWS::ElasticLoadBalancingV2::Listener name Listener1 and Listener2. I have a condition in which either listner1 is deployed or listner1
I have created a ecs service which i want to be depended on Listener.
Service:
    Type: AWS::ECS::Service
    DependsOn: !If [Condition, Listener1, Listener2]
    Properties:

When deployed its giving me error Template format error: DependsOn must be a string or list of strings.

A: Sadly, you can't do the following:
 DependsOn: !If [Condition, Listener1, Listener2]

As the error message says, DependsOn takes only a string value or a list of strings, not a function, e.g:
DependsOn: [SomeExistingResource1, SomeExistingResource2]

Also Fn::If can only be used in metadata attribute, update policy attribute, and property values. From docs:

Currently, AWS CloudFormation supports the Fn::If intrinsic function in the metadata attribute, update policy attribute, and property values in the Resources section and Outputs sections of a template.

Thus you can't use Fn::If in DependsOn.


text:
Q: How to round a column in a DataGridView VB.net I am making an asp.net webpage using VB.Net that calculates the employee's yearly salary.
I have a GridView that displays a column with values of type double (they are double in the database "example: 66,556.91").
I want to round the values of this column so that I have 66,557 instead of 66,556.91.
I checked msdn, and used {0:D} and {0:F0} in the DataFormatString in the gridview taks - edit columns but no value was changed.
<asp:BoundField DataField="C1" HeaderText="calculated taxes" ReadOnly="True" SortExpression="C1" DataFormatString="{0:F0}" />

What do you suggest?

A: Updated your select command like this for salary column, this will perform rounding operation at database end.
SELECT ROUND(SalaryColumnName,0)

A: You can supply a DataFormatString in your boundcolumn definition of {0:f0}  which will round your values to 0 decimal places.
Input Values
1
2.2
3.323
66556.91

Formatted Values
    1
    2
    3
    66557

A: Module Module1
  Sub Main()
  ' Call Math.Round on this Double.
Dim before As Double = 123.45
Dim after1 As Double = Math.Round(before, 1, MidpointRounding.AwayFromZero)
Dim after2 As Double = Math.Round(before, 1, MidpointRounding.ToEven)
Dim after3 As Double = Math.Round(before)

Console.WriteLine(before)
Console.WriteLine(after1)
Console.WriteLine(after2)
Console.WriteLine(after3)
Console.WriteLine()

  ' Use on this Decimal.
Dim before2 As Decimal = 125.101
Dim after4 As Decimal = Math.Round(before2)
Dim after5 As Decimal = Math.Round(before2, 1)

Console.WriteLine(before2)
Console.WriteLine(after4)
Console.WriteLine(after5)
End Sub
End Module

Output

123.45
123.5
123.4
123

125.101
125
125.1


text:
Q: irb returning NameError: uninitialized constant Date ruby-v2.2.3 is supposed to have Date class preloaded into irb, however when I enter...

Date
  NameError: uninitialized constant Date
         from (irb):1
         from /Users/noah/.rubies/ruby-2.2.3/bin/irb:11:in `'

Why should I have to require Date every single time if it's supposed to be preloaded into 2.2.3?

A: Date isn't listed as a core class in v2.2.3 or the current Ruby v2.3.1 core-classes, but Time is. Here's some IRb output:
$ irb -f
irb(main):001:0> Date.class
NameError: uninitialized constant Date
Did you mean?  Data
  from (irb):1
  from /Users/ttm/.rbenv/versions/2.3.1/bin/irb:11:in `<main>'
irb(main):002:0> Time.class
=> Class
irb(main):003:0> Time.methods(false)
=> [:at, :now, :utc, :gm, :local, :mktime]

That is a limited subset of Time's methods though:
irb(main):002:0> require 'time'
=> true
irb(main):003:0> Time.methods(false)
=> [:at, :now, :utc, :gm, :local, :mktime, :parse, :zone_offset, :strptime, :rfc2822, :rfc822, :httpdate, :xmlschema, :iso8601]

A: Why do you say Date is preloaded? It's not a core class, it's part of the stdlib so it needs to be required. Time is a core class instead.

A: You can try to do the following in the beginning of your file:
require 'Date'

A: As far as I know, (and as Ursus said), Date is not preloaded.
Attention: So Tilec suggested to just load the library at the beginning of the file, which gave me (Not sure if that is true in general): this gave me LoadError: cannot load such file -- Date. Trying gem install Date gives me
ERROR:  Could not find a valid gem 'Date' (>= 0) in any repository
ERROR:  Possible alternatives: date

Solution: So I'm proposing to correct to lower case:
require 'date'


text:
Q: How can i get the id related to specfifc user in django I am trying to get the saloon id related to specific employee. After the login employee can add the service, but my filter query show the error
 "Field 'id' expected a number but got <bound method MultiValueDict.get of <QueryDict: {}>>."

i don't know how can i get the saloon id
Model.py
class SaloonRegister(models.Model):
    saloon_name = models.CharField(max_length=50)
    owner_name = models.CharField(max_length=30)
    address = models.CharField(max_length=30)
    contact_no = models.BigIntegerField()
    is_active = models.BooleanField(default=False)

class SignUp(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE)
    contact_no = models.BigIntegerField()

class Men(models.Model):
    saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    Service = models.CharField(max_length=30)
    price = models.BigIntegerField()

View.py
class MenView(TemplateView):
   template_name = 'men.html'

   def get(self, request, *args, **kwargs):

       return render(request, self.template_name)

   def post(self, request):
       saloonId = SaloonRegister.objects.filter(signup__user__signup__saloon=self.request.GET.get)
       try:
          men = Men(
               saloon_id=saloonId,
               user_id=request.user,
               Service=self.request.POST.get('service'),
               price=self.request.POST.get('price')
          )
          men.save()
          return redirect('saloonMenu')
       except Exception as e:
          return HttpResponse('failed{}'.format(e))

A: I think the problem here
    SaloonRegister.objects.filter(signup__user__signup__saloon=self.request.GET.get)

as self.request.GET.get is a function
SignUp.objects.get(user_id =self.request.user.id).saloon_id

Will only work if user is in single Saloon if more than one this will fall


text:
Q: Android Gyroscope - OpenGL LookAt Position I want to get the exact position of the X, Y, Z position that I want to "Look At" through the ability of Gyroscope Sensor
I'm able to get to 9 value from Gyroscope Sensor, but I can't figure out the formula to get the exact position from this Gyroscope sensor.
I want the formula or an example to get the proper answer
Here is the code that I want the result to turn out
double standX = 0.0f, standY = 0.0f, standZ = 0.0f;
double lookX = 0.0f, lookY = 0.0f, lookZ = 1.0f;
double headupX = 0.0f, headupY = 1.0f, headupZ = 0.0f;
float[] deltaRotationMatrix = new float[9];
SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);

// code here

// in my onDraw
// I'm trying to make the lookAt position proper
Matrix.setLookAtM(mViewMatrix, 0,
        eyeX, eyeY, eyeZ, lookX, lookY, lookZ, headupX , headupY, headupZ);

example of the result is below here:

A: I have finished my question
and this is my solution
first, I need to made this 3 matrix to get result of x, y, z position
private float[] mRotXMatrix = new float[] {
 1, 0, 0, 0,
 0, 0, 1, 0,
 0, 1, 0, 0,
 0, 0, 0, 1 };
private float[] mRotYMatrix = new float[] {
 0, 0, 1, 0,
 0, 1, 0, 0,
 1, 0, 0, 0,
 0, 0, 0, 1 };
private float[] mRotZMatrix = new float[] {
 0, 1, 0, 0,
 1, 0, 0, 0,
 0, 0, 1, 0,
 0, 0, 0, 1 };

Then in onSensorChanged(SensorEvent e) method I rotate all these 3 matrix together with my camera view like this
Matrix.multiplyMM(mViewMatrix, 0, deltaRotationMatrix, 0, mViewMatrix, 0);
Matrix.multiplyMM(mRotXMatrix, 0, deltaRotationMatrix, 0, mRotXMatrix, 0);
Matrix.multiplyMM(mRotYMatrix, 0, deltaRotationMatrix, 0, mRotYMatrix, 0);
Matrix.multiplyMM(mRotZMatrix, 0, deltaRotationMatrix, 0, mRotZMatrix, 0);

And to get the X, Y, Z of my camera view, just get it from these matrix
viewX = mRotXMatrix[2];
viewY = -mRotYMatrix[6]; // +/- up to your initial camera view
viewZ = mRotZMatrix[10];


text:
Q: Filesize calculation in command line I'm trying to write a one line bash command that will show me filesize1 divided by filesize2.
What I have so far is
expr `du wednesday | cut -f1` / `du tuesday | cut -f1`

But it's showing 0
These work, however
$ expr `du wednesday | cut -f1` / 1
13066388
$ expr `du wednesday | cut -f1` / 2
6533194

Can someone help me with this?

A: expr(1) only does integer division.  From the man page:
 expr1 {*, /, %} expr2
         Return the results of multiplication, integer division, or
         remainder of integer-valued arguments.

You'll need to use a different tool; bc(1) could do it, for example:
bc <<< "scale=2; $(du wednesday | cut -f1) / $(du tuesday | cut -f1)"

A: expr $(du -b wednesday | cut -f1) / $(du -b tuesday | cut -f1)
Back-ticks don't work with this command for some reason.
Because this works. one file is 7 bytes the other is 1295 bytes and the output is 185 bytes


text:
Q: Squish Axes Plot Is there a way to squish the axes plots at the start of a 2d data plot. For example, imagine a signal from a wave has a continuous signal when $x\in [0,L]$ and out-with $L$ the plot becomes noisy.
I am looking for a way to shrink the region $[0,L]$ then return to a normal scale out-with this.

A: You can use the ScalingFunctions option of most Plot functions.
A simple Example made by myself:
Plot[x, {x, -1, 1}, ScalingFunctions -> {Function[If[# < 0.0, # 0.1, #]], Function[If[# < 0.0, # 10, #]]} ]

The first Function is the one scaling the axis. You also need to provide it's inverse. Otherwise ticks will not work properly. Compare:
Plot[x, {x, -1, 1}, ScalingFunctions -> {Function[If[# < 0.0, # 0.1, #]], Function[#]} ]


text:
Q: Injecting app level setting into project level setting in Django I am trying to setup a cron job for celery beat, but I don't want to put the schedule information in the project level settings.py , is there a way to inject app level settings into project level setting such that it will play nicely with the entire project?
celery_config.py in celery_task app
CELERYBEAT_SCHEDULE = {
    'name_of_job': {
        'task': 'task.add',
        'schedule': timedelta(seconds=5),
        'args': (16, 0)
},
}

settings.py
    INSTALLED_APPS = (
    'djcelery',
    'celery_task'
)

A: The first option would be to specify the location of the configuration file via the Celery command line argument --config
The second option is to do something similar to what I do when I need to have settings that are environment/deployment specific:
Include a section at the bottom of your settings.py file that imports the settings from your app wrapped in a try statement to avoid breaking the site if the app settings file isn't available.
Example:
/* bottom of settings.py */
try:
    from celery_app.celery_config import *
except:
    print 'Did not find celery_config'

This will try to load the settings file from your app but will avoid any errors if the app isn't present in the project folder.
IMPORTANT: Use only unique celery related configuration variables as this will override any previously defined settings in your settings.py file


text:
Q: Best way to solve $24^{100} \times 1.5^{50} \times 12^{-149}$ I think I could solve this but I would like to know the best way to do it with the least amount of calculations

A: $$ 24^{100} \times 1.5^{50} \times 12^{-149} = (3\cdot 2^3)^{100} \times (3\cdot 2^{-1})^{50} \times (3 \cdot 2^2)^{-149} \\ =  3^{100} \cdot 2^{300}\cdot 3^{50}\cdot 2^{-50}\cdot 2^{-298}\cdot 3^{-149} = ...$$
You can add exponents to get the final answer

A: As suggested by Mufasa in comments, expand in powers of $2$ and $3$:
$$
\overbrace{2^{300}3^{100}}^{24^{100}}\overbrace{3^{50}2^{-50}}^{1.5^{50}}\overbrace{2^{-298}3^{-149}}^{12^{-149}}=3\cdot2^{-48}
$$
We can also reduce computation with $2^{-48}=\left(\left(\left(\left(\frac18\right)^2\right)^2\right)^2\right)^2$


text:
Q: What is the difference between a CLR Worker Thread and a Worker Thread? Looking at the Concurrency Analyzer, Threads view it appears my application produces far, far more threads than I would have thought.  Most of these are either a "CLR Worker Thread" or a "Worker Thread".
What are the differences?  Under what circumstances are each created?

A: Concurrency Visualizer is a pretty new but really cool! feature so there are a bit (I believe yet) of information regarding it, below what I've found in official information sources like MSDN:

*

*Worker thread - A thread that was created by the application main thread (Main Thread entry in the table)

*CLR Worker Thread - A worker thread that was created by the Common Language Runtime
Useful links:

*

*Concurrency Visualizer

*Channels (Threads View)

*Parallel Development in Visual Studio blog

*Using the Concurrency Visualizer to Understand and Optimize UI Responsiveness


text:
Q: Dynamically modifying serializer fields in Django Rest Framework I'm trying to use the Advanced serializer usage described in the django rest framework documentation. http://django-rest-framework.org/api-guide/serializers.html#advanced-serializer-usage to dynamically modifying serializer field
Here is my serializer class:
class MovieSerializer(serializers.ModelSerializer):
    moviework_work = MovieWorkSerializer(many=True)

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        dropfields = kwargs.pop('dropfields', None)

        # Instantiate the superclass normally
        super(MovieSerializer, self).__init__(*args, **kwargs)

        if dropfields:
            # Drop fields specified in the `fields` argument.
            banished = set(dropfields)
            for field_name in banished:
                self.fields.pop(field_name)
    class Meta:
        model = Movie
        fields = ('field1','field2','moviework_work')

Here is my viewset
class MovieFromInterpreterViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer(dropfields=('moviework_work',))

I get this error:
TypeError: 'MovieSerializer' object is not callable

A: Note that you are setting serializer_class not to a class, but to an instance of the class. You either need to set dropfields as an attribute on the class, (just like it does for fields in the documented example you link to) or you need to look at overriding the get_serializer method of the viewset (docs).


text:
Q: LDA topic models for various and unknown domains We have a large collection (1-2M) of documents of various domains (politics, design, programming, etc.). And lets assume that we don't know the exact number of domains. And our goal is to build relevant topic models for these domains. For example I want to find N topics in each domain. For politics it could be: foreign policy, government, economic policy, etc. For design domain: web design, architecture, etc. And so on.
If I understand correctly, when using a LDA it is necessary to form a training set for specified domain (e.g. politics). But problem arises if there is no information about domain. How can I form a training set in that case? I was thinking about building index, extracting documents, that contain significant words (defined by TF-IDF). But it seems that it is not the best solution.
If instead of LDA we can use HDP and handle training set compiled with random documents. But there arises another problem - a huge vocabulary, which may not fit in the memory (we need much more words to describe several domains, than one).
So the problem is: what is the best way to build topic models (or one topic model?) of various (and unknown) domains? And them apply this models to new (unseen) documents.

A: Hierarchical topic models are designed precisely for this task. These models infer topic hierarchies where high level topics (poltics, sports) have subtopics beneath them (foreign policy, baseball).
The original formulation is from this paper

*

*Hierarchical Topic Models and
the Nested Chinese Restaurant Process
And this very recent formulation, which is able to infer more accurate hierarchical structures

*

*Nested Hierarchical Dirichlet Processes


text:
Q: How to complete parenthesis of function with cursor between them (Visual Studio Code) I'm coding C in VS Code, when I type "sin" and then Tab, it auto completes to "sin()" with the cursor after the last parenthesis, same thing for cos(). Rather, I'd like the cursor to be placed in between them. For example, when I type "print" and then Tab, it goes "print()" with the cursor between the parenthesis, same thing for memset() and the majority of functions.
Note: Is it because sin() and cos() should have no parameters?


text:
Q: Getting page not found trying to navigate to my asp.net core 5.0 web service I create a new ASP.NET Core Razor Project using .Net 5.0, I have created a simple Web service API page which is below. The issue is when I run it and then in the browser I call http://localhost:50050/api/test I get "HTTP ERROR 404*" meaning my web service cannot be found. I have a similar application just done in older version of .net core and that works just fine.  Does anyone know what I am doing wrong?
using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public int GetTest()
        {
            return 21;
        }

        [HttpGet("{id}")]
        public int GetTest([FromRoute] int id)
        {
            return 22;
        }
    }
}

The start up page is shown below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication2
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

Below is my project layout

A: You only have an endpoint to your RazorPages, not with your Controllers.
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });

what you need to do is to register your Controllers in the Startup ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
     services.AddControllers();
}

then add those Controllers in your Endpoint Middleware like so:
public void Configure(IApplicationBuilder app){
   // other middlewares
   app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
}


text:
Q: What should I write in standalone.xml to have slf4j? I am developing an app and I must put slf4j logging into my standalone.xml file. I have dependencies in my pom for this but I don't know what should I write in standalone.xml. This is the log part of my standalone.xml:
<logger category="com.arjuna">
            <level name="WARN"/>
        </logger>
        <logger category="org.jboss.as.config">
            <level name="DEBUG"/>
        </logger>
        <logger category="sun.rmi">
            <level name="WARN"/>
        </logger>
        <root-logger>
            <level name="INFO"/>
            <handlers>
                <handler name="CONSOLE"/>
                <handler name="FILE"/>
            </handlers>
        </root-logger>

Could anybody say what should I write into this file?

A: You don't have to do anything. slf4j is a logging facade. You only need a dependency on the org.slf4j:slf4j-api and it should be marked with <scope>provided</scope> in your pom. WildFly will add the slf4j API and an implementation to your deployments class path.


text:
Q: Can I assign key strokes to KeyboardState? I capture pressed keys by following code:
KeyboardState keyState = Keyboard.GetState();
Can I set key strokes to keyState so I can simulate user input?

A: Do you mean something like this?
With KeyboardState constructor you can initialize a new instance of the KeyboardState class with an array or parameter list of Keys to initialize as pressed.

A: Keys[] keys = new Keys[] {Keys.A, Keys.B};
KeyboardState keystate = new KeyboardState(keys);
if (keystate.isKeyDown(Keys.A))
    //true

Try that, I'm not 100% sure that is what you want but it should be put you on the right track.


text:
Q: Disambiguate functional interface in lambda Suppose this:
ExecutorService service = ...;

// somewhere in the code the executorService is used this way:
service.submit(() -> { ... });

The lambda expression would default to Callable.

Is there a way to make it instantiate a Runnable instead?
Thanks for your help.

A: You can declare it as a Runnable, or use a cast:
Runnable r = () -> { ... };
executorService.submit(r);

or
executorService.submit((Runnable) () -> { ... });

A: Your premise is wrong. This invocation does not default to Callable. The selection is made via the shape of the lambda expression, i.e. whether it returns a value:
ExecutorService service = null;

// somewhere in the code the executorService is used this way:

// invokes submit(Runnable)
service.submit(() -> {  });
// invokes submit(Runnable)
service.submit(() -> { return; });
// invokes submit(Callable)
service.submit(() -> "foo");
// invokes submit(Callable)
service.submit(() -> { return "foo"; });

// in case you really need disambiguation: invokes submit(Runnable,null)
service.submit(() -> { throw new RuntimeException(); }, null);
// dito (ignoring the returned value)
service.submit(this::toString, null);

Note that if you don't need the returned Future, you can simply use execute(Runnable) to directly enqueue a Runnable, rather than having it wrapped in a FutureTask.

A:    service.submit((Runnable) () -> {
      ...
   });

A: The difference between Callable and Runnable in terms of their signature is that Callable is returning a value, while Runnable doesn't.
So () -> { } is a Runnable while e.g. () -> "" is a Callable.


text:
Q: How to extract unique values within each row in dataframe? I am trying to extract unique values within each rows of dataframe in R without using for loop.
df <- data.frame(customer = c('joe','jane','john','mary'), fruit = c('orange, apple, orange', NA, 'apple', 'orange, orange'))

df

  customer                 fruit
1      joe orange, apple, orange
2     jane                  <NA>
3     john                 apple
4     mary        orange, orange

What I want for the fruit column is:
'orange, apple', NA, 'apple', 'orange'
  customer                 fruit
1      joe         orange, apple
2     jane                  <NA>
3     john                 apple
4     mary                orange

I tried something along the lines of
apply(df, 1, function(x) unique(unlist(str_split(x[, "fruit"], ", "))))

and it is not working.
How can I get unique values within each row in the dataframe?

A: Base R option :
Split the string on comma, keep unique values and paste the values into comma-separated string.
df$fruit <- sapply(strsplit(df$fruit, ',\\s+'), function(x) toString(unique(x)))
df

#  customer         fruit
#1      joe orange, apple
#2     jane            NA
#3     john         apple
#4     mary        orange

A: A simple pipe syntax using dplyr and purrr::map
df %>% mutate(fruit = str_split(fruit, ", "),
              fruit = map(fruit, ~ unique(.x)))
  customer         fruit
1      joe orange, apple
2     jane            NA
3     john         apple
4     mary        orange

or BaseR only
df$fruit <- Map(unique, strsplit(df$fruit, ", "))
df

> df
  customer         fruit
1      joe orange, apple
2     jane            NA
3     john         apple
4     mary        orange

Note: Assumption that every string is separated by a comma and a space as shown in sample

A: Updated Solution
I just modified my code to match what you would like your output to be.
library(dplyr)
library(tidyr)

df %>%
  separate_rows(fruit) %>%
  distinct(customer, fruit) %>%
  group_by(customer) %>%
  summarise(fruit = paste(sort(fruit, na.last = FALSE), collapse = ", "))

# A tibble: 4 x 2
  customer fruit
  <chr>    <chr>
1 jane     NA
2 joe      apple, orange
3 john     apple
4 mary     orange

A: here is a potential solution using base R, no libraries. Lots of ugly brackets but I think it works..
df$fruit <-lapply(1:nrow(df),function(n)unique(trimws(unlist(strsplit(df$fruit[n],",")))))

output as follows
> df
  customer         fruit
1      joe orange, apple
2     jane            NA
3     john         apple
4     mary        orange


text:
Q: How to properly divide numbers in HLA assembly I got Integer overflow in HLA nasm. I would like to write simple program that divide provided Distance variable by 15000 and display evaluation of it, but I faced that problem. I simply don't understand an idea of division in HLA. Thank you in advance for your help.
program zad2;
#include( "stdlib.hhf");

static
    f    :  int32   := 15000;
    s    :  int32   := 300000;
    Distance: int32;

begin zad2;

        stdout.put("Give car distance", nl);
        stdin.get(Distance);
        if (Distance<150000) then
            MOV(15000, eax);
            div(Distance, EDX:EAX );
                stdout.put("div evaluation:",eax ,nl);
                    jmp menu0;
            endif
end zad2;

A: mov(0, edx)
mov(15000, eax);
div(distance, edx:eax);

You need to zero extend into edx because it's the register that holds your remainder.

A: I found my resolution of it. Please have a look on it. All stuff with hla div are not working correctly on Windows version of hla compiler. It should look like this. I hope it might by somehow helpful for sb ;)
mov(Distance, eax);
mov(15000, ebx);
div(ebx);
mov(eax, age);

A: I have also been researching Div use with HLA (High Level Assembly). I wanted to share what I found also to help others. This program was not a class assignment, for that we had to do everything by hand and show our work. I just wrote this short program for some extra practice, so I thought why not share it, it worked great for checking my work, plus it has division use in it. This program will take a char convert it to Hex to Decimal and after convert it to binary, to do the binary conversions is uses idiv inside of a while loop and goes from 64 to 32 to 16 to 8 to 4 to 2 to 1 each while loop iteration divides the cl in half.
    //Jonathan Lee Sacramento State University
    //CSC35
    //Professor Devin Cook
    //Feb 11 2023
    //Non-Credit Practice program with Asci/hex/decimal

    //Program: This is a HLA program that converts ASCII/HEX/DECIMAL/BINARY
    based off one letter input

    program binarydiv;
    #include( "C:\hla\include\stdlib.hhf");

    static
        UserChar: char;
        i8:  int8 :=0; //value

    begin binarydiv;
        stdout.put("---> Please enter one character: ");
        stdin.get(UserChar); //store as char
        stdout.put("You Entered: ",UserChar);
        mov(UserChar,al); // store hex value of char into al reg
        stdout.put(nl,"(",UserChar,") In Hex is: ", al); //show hex value
        mov(al,i8); //move hex into int8
        stdout.put(nl,"(",UserChar,") In Decimal is: ",i8); //show decimal value
        stdout.put(nl,"(",UserChar,") In Binary is: 0"); //start of binary not using 128
        mov(64,cl); //use cl with operators 2nd binary
        while(cl>0) do
            if(i8>=cl) then
                stdout.put("1");
                sub(cl,i8);
            elseif(i8<cl) then
                stdout.put("0");
            endif;
    //div block
            mov(cl,al);
            cbw();
            mov(2,bl);
            idiv(bl);
            mov(al,cl);
    //end div block
        endwhile;
        stdout.put(nl);
    end binarydiv;


text:
Q: Variable Timesteps and Gravity/Friction I'm trying to copy the logic of the Sonic physics engine, which was written for a fixed-timestep system (60 FPS), in a variable timestep age (Slick2D, to be precise).
In the original upon pressing the jump button, the player's velocity.y is set to -6.5, and each tick 0.21875 is added to velocity.y to model gravity.
Each time my logic update is called, a time delta parameter is passed specifying how many millis have passed. If more millis have passed than I was expecting, then I repeat the update logic, passing an 'inner delta' that is at most 1, or less if we're dealing with the 'remainder' of a target frame.
E.g. if we expect a frame to take 16ms, and it does take 16 ms, the loop will iterate once and pass thisMiniTick as 1. If the delta was not 16ms but 40ms, the loop will execute three times, passing 1, 1, and finally 0.5.
I mistakenly thought that in each of these inner update loops I could do velocity.y += (gravity * thisMiniTickRelative), but this doesn't work. On faster framerates not enough gravity is applied causing a higher jump, and on slower framerates the jump is lower (although not anywhere near as noticeably).
Is there a way of doing this that will work for virtually all framerates, or must I resort to setting an upper and lower bound for delta?
The 'inner update' loop:
    float timeRemaining = delta/1000f;
    while(timeRemaining > 0)
    {
        float thisMiniTick = Math.min(timeRemaining, 1f / FRAMES_PER_SECOND);
        float thisMiniTickRelative = thisMiniTick / (1f / FRAMES_PER_SECOND);

        updateInput(container, game, thisMiniTickRelative);
        if (playerAirState)
        {
            playerVelocity.y += (GRAVITY * thisMiniTickRelative);
        }
        clampPlayerVelocity();
        playerPosition.add(playerVelocity);
        doCollisions();
        timeRemaining -= thisMiniTick;
    }

A: Don't think of it as "resorting to setting an upper and lower bound for delta". Your application and threads are subject to the OS scheduling time for your app, among all the other demands on the system, and something you just need to be aware of. This challenge is as old in PC gaming as the day we moved from single-tasking operating systems to multi-tasking operating systems.
With Slick, you can (and should) disconnect your logic updates from your rendering updates, which is why the delta value gets passed around your application. Do this by using the .setMinimumLogicUpdateInterval and .setMaximumUpdateInterval methods.
On projects that I've worked on, including one in Slick, I find that anything in the 30-60 logic updates per second (30.3 milliseconds to 16.6 milliseconds between updates) works great, and gives you the smoothness you need from your movement, physics, and collision calculations.
Literally what that means is, for a 30-60 logic updates per second range, you want to do the following:
container.setMinimumLogicUpdateInterval(16);  // max 60 logic updates per second
container.setMaximumLogicUpdateInterval(31);  // min 30 logic updates per second

Also, it's a common mistake to try to calculate the timeRemaing value, but you don't want to do this. You simply want to multiply how much you move, by how much time has passed. If 30 milliseconds have passed, that's about 1/33rd of a second, so you should move your game object by 1/33rd of the amount it would move in 1 second.
float timeElapsed = delta/1000f;

playerVelocity.y += (GRAVITY * timeElapsed);

With the upper/lower bounds set as specified above, you're sure that timeElapsed will always be a value between 0.03 and 0.06. If your game gets bogged down and your frame rate slows down, your logic updates still won't go outside these bounds. What will happen instead is the whole game will appear to slow down (as it should, just like on the old Sega days when there was too much on the screen), but collisions and physics calculations will still work as expected.


text:
Q: SQL DROP TABLE foreign key constraint If I want to delete all the tables in my database like this, will it take care of the foreign key constraint? If not, how do I take care of that first?
GO
IF OBJECT_ID('dbo.[Course]','U') IS NOT NULL
    DROP TABLE dbo.[Course]
GO
IF OBJECT_ID('dbo.[Student]','U') IS NOT NULL
    DROP TABLE dbo.[Student]

A: In SQL Server Management Studio 2008 (R2)  and newer, you can Right Click on the

DB -> Tasks -> Generate Scripts

*

*Select the tables you want to DROP.

*Select "Save to new query window".

*Click on the Advanced button.

*Set Script DROP and CREATE to Script DROP.

*Set Script Foreign Keys to True.

*Click OK.

*Click Next -> Next -> Finish.

*View the script and then Execute.

A: No, this will not drop your table if there are indeed foreign keys referencing it.
To get all foreign key relationships referencing your table, you could use this SQL (if you're on SQL Server 2005 and up):
SELECT *
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

and if there are any, with this statement here, you could create SQL statements to actually drop those FK relations:
SELECT
    'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '].[' + OBJECT_NAME(parent_object_id) +
    '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

A: If you drop the "child" table first, the foreign key will be dropped as well. If you attempt to drop the "parent" table first, you will get an "Could not drop object 'a' because it is referenced by a FOREIGN KEY constraint." error.

A: Here is another way to drop all tables correctly, using sp_MSdropconstraints procedure. The shortest code I could think of:
exec sp_MSforeachtable "declare @name nvarchar(max); set @name = parsename('?', 1); exec sp_MSdropconstraints @name";
exec sp_MSforeachtable "drop table ?";

A: If it is SQL Server you must drop the constraint before you can drop the table.

A: Slightly more generic version of what @mark_s posted, this helped me
SELECT
'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(k.parent_object_id) +
'.[' + OBJECT_NAME(k.parent_object_id) +
'] DROP CONSTRAINT ' + k.name
FROM sys.foreign_keys k
WHERE referenced_object_id = object_id('your table')

just plug your table name, and execute the result of it.

A: Here's another way to do delete all the constraints followed by the tables themselves, using a concatenation trick involving FOR XML PATH('') which allows merging multiple input rows into a single output row.   Should work on anything SQL 2005 & later.
I've left the EXECUTE commands commented out for safety.
DECLARE @SQL NVARCHAR(max)
;WITH fkeys AS (
    SELECT quotename(s.name) + '.' + quotename(o.name) tablename, quotename(fk.name) constraintname
    FROM sys.foreign_keys fk
    JOIN sys.objects o ON fk.parent_object_id = o.object_id
    JOIN sys.schemas s ON o.schema_id = s.schema_id
)
SELECT @SQL = STUFF((SELECT '; ALTER TABLE ' + tablename + ' DROP CONSTRAINT ' + constraintname
FROM fkeys
FOR XML PATH('')),1,2,'')

-- EXECUTE(@sql)

SELECT @SQL = STUFF((SELECT '; DROP TABLE ' + quotename(TABLE_SCHEMA) + '.' + quotename(TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
FOR XML PATH('')),1,2,'')

-- EXECUTE(@sql)

A: Here is a complete script to implement a solution:
create Procedure [dev].DeleteTablesFromSchema
(
    @schemaName varchar(500)
)
As
begin
    declare @constraintSchemaName nvarchar(128), @constraintTableName nvarchar(128),  @constraintName nvarchar(128)
    declare @sql nvarchar(max)
    -- delete FK first
    declare cur1 cursor for
    select distinct
    CASE WHEN t2.[object_id] is NOT NULL  THEN  s2.name ELSE s.name END as SchemaName,
    CASE WHEN t2.[object_id] is NOT NULL  THEN  t2.name ELSE t.name END as TableName,
    CASE WHEN t2.[object_id] is NOT NULL  THEN  OBJECT_NAME(d2.constraint_object_id) ELSE OBJECT_NAME(d.constraint_object_id) END as ConstraintName
    from sys.objects t
        inner join sys.schemas s
            on t.[schema_id] = s.[schema_id]
        left join sys.foreign_key_columns d
            on  d.parent_object_id = t.[object_id]
        left join sys.foreign_key_columns d2
            on  d2.referenced_object_id = t.[object_id]
        inner join sys.objects t2
            on  d2.parent_object_id = t2.[object_id]
        inner join sys.schemas s2
            on  t2.[schema_id] = s2.[schema_id]
    WHERE t.[type]='U'
        AND t2.[type]='U'
        AND t.is_ms_shipped = 0
        AND t2.is_ms_shipped = 0
        AND s.Name=@schemaName
    open cur1
    fetch next from cur1 into @constraintSchemaName, @constraintTableName, @constraintName
    while @@fetch_status = 0
    BEGIN
        set @sql ='ALTER TABLE ' + @constraintSchemaName + '.' + @constraintTableName+' DROP CONSTRAINT '+@constraintName+';'
        exec(@sql)
        fetch next from cur1 into @constraintSchemaName, @constraintTableName, @constraintName
    END
    close cur1
    deallocate cur1

    DECLARE @tableName nvarchar(128)
    declare cur2 cursor for
    select s.Name, p.Name
    from sys.objects p
        INNER JOIN sys.schemas s ON p.[schema_id] = s.[schema_id]
    WHERE p.[type]='U' and is_ms_shipped = 0
    AND s.Name=@schemaName
    ORDER BY s.Name, p.Name
    open cur2

    fetch next from cur2 into @schemaName,@tableName
    while @@fetch_status = 0
    begin
        set @sql ='DROP TABLE ' + @schemaName + '.' + @tableName
        exec(@sql)
        fetch next from cur2 into @schemaName,@tableName
    end

    close cur2
    deallocate cur2

end
go

A: Removing Referenced FOREIGN KEY Constraints
Assuming there is a parent and child table Relationship in SQL Server:

--First find the name of the Foreign Key Constraint:
  SELECT *
  FROM sys.foreign_keys
  WHERE referenced_object_id = object_id('States')

--Then Find foreign keys referencing to dbo.Parent(States) table:
   SELECT name AS 'Foreign Key Constraint Name',
           OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) AS 'Child Table'
   FROM sys.foreign_keys
   WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND
              OBJECT_NAME(referenced_object_id) = 'dbo.State'

 -- Drop the foreign key constraint by its name
   ALTER TABLE dbo.cities DROP CONSTRAINT FK__cities__state__6442E2C9;

 -- You can also use the following T-SQL script to automatically find
 --and drop all foreign key constraints referencing to the specified parent
 -- table:

 BEGIN

DECLARE @stmt VARCHAR(300);

-- Cursor to generate ALTER TABLE DROP CONSTRAINT statements
 DECLARE cur CURSOR FOR
 SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' +
 OBJECT_NAME(parent_object_id) +
                ' DROP CONSTRAINT ' + name
 FROM sys.foreign_keys
 WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND
            OBJECT_NAME(referenced_object_id) = 'states';

 OPEN cur;
 FETCH cur INTO @stmt;

 -- Drop each found foreign key constraint
  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXEC (@stmt);
    FETCH cur INTO @stmt;
  END

  CLOSE cur;
  DEALLOCATE cur;

  END
  GO

--Now you can drop the parent table:

 DROP TABLE states;
--# Command(s) completed successfully.

A: everything is much simpler. There is a configuration to turn off the check and turn it on.
For example, if you are using MySQL, then to turn it off, you must write SET foreign_key_checks = 0;
Then delete or clear the table, and re-enable the check SET foreign_key_checks = 1;

A: If you are on a mysql server  (not MSSQL) and if you don't mind loosing your tables, you can use a simple query to delete multiple tables at once:
SET foreign_key_checks = 0;
DROP TABLE IF EXISTS table_a,table_b,table_c,table_etc;
SET foreign_key_checks = 1;

In this way it doesn't matter in what order you use the table in you query.
If anybody is going to say something about the fact that this is not a good solution if you have a database with many tables: I agree!

A: Using SQL Server Manager you can drop foreign key constraints from the UI. If you want to delete the table Diary but the User table has a foreign key DiaryId pointing to the Diary table, you can expand (using the plus symbol) the User table and then expand the Foreign Keys section. Right click on the foreign key that points to the diary table then select Delete. You can then expand the Columns section, right click and delete the column DiaryId too. Then you can just run:
drop table Diary

I know your actual question is about deleting all tables, so this may not be a useful for that case. However, if you just want to delete a few tables this is useful I believe (the title does not explicitly mention deleting all tables).

A: execute the below code to get the foreign key constraint name which blocks your drop. For example, I take the roles table.
      SELECT *
      FROM sys.foreign_keys
      WHERE referenced_object_id = object_id('roles');

      SELECT name AS 'Foreign Key Constraint Name',
      OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id)
      AS 'Child Table' FROM sys.foreign_keys
      WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo'
      AND OBJECT_NAME(referenced_object_id) = 'dbo.roles'

you will get the FK name something as below : FK__Table1__roleId__1X1H55C1
now run the below code to remove the FK reference got from above.
ALTER TABLE dbo.users drop CONSTRAINT FK__Table1__roleId__1X1H55C1;

Done!

A: Find all foreign key.. script them
SELECT *  FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

and then delete foreign keys from child table.
now you can drop parent table .
if you want to recreate the parent table make sure to run the script you have created earlier.

A: This script will let you delete all Foreign Key Contrainsts using a string match on the Contraint name
    DECLARE @constraintMatchString nvarchar(max) = N'FK_<SOME-MATCH-STRING>%';
    DECLARE @sql nvarchar(max) = N'';

    ;WITH x (schemaAndTableName, constraintName) AS
    (
      SELECT
        schemaAndTableName = QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)),
        constraintName = name
      FROM sys.foreign_keys
      where name like @constraintMatchString
      group by QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)), name
    )
    SELECT @sql += N'ALTER TABLE ' + schemaAndTableName + N' DROP CONSTRAINT [' +constraintName +N'];
    ' FROM x;

    EXEC sys.sp_executesql @sql;

Just replace the FK_<SOME-MATCH-STRING>% value as needed (and note, the % is a wildcard match)

A: If you want to DROP a table which has been referenced by other table using the foreign key use
DROP TABLE *table_name* CASCADE CONSTRAINTS;
I think it should work for you.

A:
If I want to delete all the tables in
  my database

Then it's a lot easier to drop the entire database:
DROP DATABASE WorkerPensions


text:
Q: postgis reformat string coordinates into format for st_PointFromText() I have a single column loc_coords in postgresql table with combined latitude, longitude data. The data in that column looks like this:
(34.0539, -118.463)

In order to use the Postgis function ST_PointFromText() I have to reformat this text to remove the comma and parens, meaning:
34.0539 -118.463

I have been trying to find a way to do these replacements in one shot, but keep getting errors. Here is what I have been trying to do in SQL:
WITH comma_repl as (
SELECT replace(loc_coords,',', '') FROM t_active_bus),
rparen as (
SELECT replace(loc_coords, '(','') FROM comma_repl),
lparen as (
SELECT replace(loc_coords, ')', '') FROM rparen)

UPDATE t_active_bus
SET st_loc = st_pointfromtext('POINT(||lparen||)',4326);

But I keep getting an error that the loc_coords does not exit. I imagine the error is about loc_coords not existing in one of the subqueries for rparen and lparen.
Any suggestions on how to fix this even a better way to do it?

A: Have you tried to create a function to achieve this?
create or replace function process_coords() returns text as $$
begin;
return replace(replace(replace($1,'(',''),')',''),',','');
end;
$$ language 'plpgsql';

UPDATE t_active_bus
SET st_loc = st_pointfromtext('POINT(' || process_coords(loc_coords) || ')',4326);


text:
Q: Two non-comparable metrics on $X=C[0,\pi]$ Problem:

Show that the two metrics$$d_1(x,y)=\sup_{[0,\pi]}t^2\lvert {x(t)-y(t)}\rvert\text{ and }d_2(x,y)=\sup_{[0,\pi]}\sin(t)\lvert {x(t)-y(t)}\rvert$$are not comparable on the set $X=C[0,\pi]$ of real valued continuous function defined on $[0,\pi]$. In particular, find a set $A\subset{X}$ that is open with the metric $d_1$ but not open with $d_2$.

Here, comparable means convergence of a sequence in one metric implies the convergence of it in the other with the same limit. Since this convergence relation can be characterized by means of being open, problem asks me to show it using open sets.
Now, I find it very difficult to construct such a set $A\subset{X}$. I believe it must be about the relation between the functions $sin(t)$ and $t^2$. For instance, I tried $A=\{x(t)\in{X} \lvert x(\pi)\gt{0}\}$ and showed that this set is open with respect to $d_1$. However, I do not know whether it is also open with respect to $d_2$ or not, and even if it is not open, it confuses me a lot, how to show it? Any comment/idea is highly appreciated.

A: Your guess seems correct, the set $A$ indeed is not open w.r.t. the metric $d_2$. To prove this, consider the constant function $f \equiv C$ for some constant $C > 0$. Then $f(\pi) = C > 0$ so $f \in A$. We will show that there is no open ball in the $d_2$ metric centered at $f$ which is contained in $A$.
Let $\varepsilon > 0$ be arbitrary. Since $\sin$ is continuous at $\pi$ and $\sin \pi = 0$, there exists $\delta \in \langle 0,\pi\rangle$ such that $\sin([\pi-\delta,\pi]) \subseteq \left[0,\frac\varepsilon{2C}\right].$ Define $g_\varepsilon \in C[0,\pi]$ as
$$g_\varepsilon(t) = \begin{cases} C, &\text{ if }t \in [0,\pi-\delta], \\
\frac{C}{\delta}(\pi-t), &\text{ if }t \in [\pi-\delta,\pi].
\end{cases}$$
Then since $g_\varepsilon =f$ on $[0,\pi-\delta]$, we have
\begin{align}
d_2(f,g_\varepsilon) &= \sup_{t \in [0,\pi]} (\sin t)|f(t)-g_\varepsilon(t)| = \sup_{t \in [\pi-\delta, \pi]} (\sin t)\left|C-\frac{C}{\delta}(\pi-t)\right| \\
&= C \sup_{t \in [\pi-\delta, \pi]} \underbrace{(\sin t)}_{\le \frac\varepsilon{2C}}\underbrace{\left|1-\frac{1}{\delta}(\pi-t)\right|}_{\le 1}\le C \cdot \frac{\varepsilon}{2C}= \frac{\varepsilon}2< \varepsilon
\end{align}
so $g_\varepsilon \in B_{d_2}(f,\varepsilon)$. However, $g_\varepsilon(\pi) = 0$ so $g_\varepsilon\notin A$ which implies $B_{d_2}(f,\varepsilon) \not\subseteq A$.

A: Actually the inequivalence follows also from the fact that at $t=0$ the behaviours  of the  metrics $d_1$ and $d_2$ are different.
A result below is complementary  to the one given in the answer of @mechanodroid.
The set $$A=\{x\in C[0,\pi]\,:\, d_2(x,0)<1\}$$ is open with respect to the metric $d_2$ (that's a general fact for every metric).
On the other hand the set $A$ is not open with respect to the metric $d_1.$ To this end we will show that the function $0\in A$ can be approximated with respect to the metric $d_1$ by functions $x_n\notin A.$ For any fixed positive integer $n\ge 4$ let
$$x_n(t) =\begin{cases}
2n^2t(2-nt) &  0\le t\le {2\over n}\\
0 & {2\over n}<t\le \pi
\end{cases}
$$ The maximal value of  $x_n$  is attained at    $t={1\over n}$ and is equal $2n.$
Therefore $$d_2(x_n,0)\ge \max_{0\le t\le {1\over 2}}\sin( t )x_n(t)\ge  {2\over \pi}\max_{0\le t\le {1\over 2}} t x_n(t)\ge {2\over \pi}[tx(t)]_{t={1\over n}}={4\over \pi}>1$$
On the other hand
$$d_1(x_n,0)=\max_{0\le t\le \pi}t^2x_n(t)\le {4\over n^2}\max_{0\le t\le \pi}x_n(t)={4\over n^2}2n={8\over n}$$
Thus $x_n\notin A$ but $d_1(x_n,0)\underset{n\to \infty}{\longrightarrow} 0.$
Remark Concerning the original question in OP it can be shown that the set $$B=\{x\,:\, d_1(x,0)<1\}$$ which is open with respect to the metric $d_1,$ is not open with respect to the metric $d_2.$


text:
Q: Kept getting Index Errors with pandas data frame, now can't get correct values I am having trouble with pandas dataframe. I not able to get my values to appear correctly. I kept getting index errors but now I got my table to show and the inputs are incorrect.
This is what I am getting:
I would like the second line showing 15,0,0 for Andy.
Expected output:

customers = [u'Becky Buyer - Address Two', u'Andy Buyer - Andy nguyen']
plu_parts = [12834L, 11521L, 11164L]
cases = numpy.zeros(shape=(len(plu_parts),len(customers)))

Here I wrote:
 for i in range(len(plu_parts)):
        for j in range(len(customers)):
            plu_sets = [x for x in obs_plu_code_buyer if x['seller_inventory__plu_code_id'] == plu_parts[i] and x['purchase_order_line__purchase_order__buyer__company_name'] + str(" - ") + x['purchase_order_line__purchase_order__delivery_address__contact'] == customers[j]]
            print(plu_sets)
            if len(plu_sets) > 0:
                cases[i][j] = int(plu_sets[0]['num_cases'])

Which gives me
cases =  [[ 100.   10.]
 [  13.    0.]
 [  50.    0.]]

veggies = [u'Conventional Any Custom Mix , 90% Iceberg w/ carrot and red cabbage , 4/5#', u'Conventional Cabbage , Green , 45#', u'Conventional Cabbage , Napa , 15#']

dd  = 'Delivery Dated ' + delivery_date.strftime('%m/%d/%Y')
py = pd.DataFrame({dd :customers})
for k in range(0,len(veggies)):
    d = [int(row) for row in cases[:,0]]
    py.insert(k+1,veggies[k],d[k])

All help is appreciated.
EDIT: Included reprex code

A: Use .T to transpose the numpy array cases upon creation of your dataframe:

customers = [u'Becky Buyer - Address Two', u'Andy Buyer - Andy nguyen']
plu_parts = ['12834L', '11521L', '11164L']
cases = np.array([[100., 10.],
       [13., 0.],
       [50., 0.]])
veggies = [u'Conventional Any Custom Mix , 90% Iceberg w/ carrot and red cabbage , 4/5#', u'Conventional Cabbage , Green , 45#', u'Conventional Cabbage , Napa , 15#']
dd  = 'Delivery Dated 10/01/2020'
df = pd.DataFrame(cases.T, columns=veggies, index=customers)
df.index.name = dd
df


text:
Q: Calling a delphi DLL method from C# Code I am trying to call a Delphi function from C# ASP.NET code. The function's declaration looks like this:
function SomeFunction(const someString, SomeOtherString: string): OleVariant;

From my C# code I have this code:
[DLLImport(MyDLL.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern object SomeFunction(string someString, string SomeOtherString);

Every time I call this Method and store it as an object, I get a P/Invoke error.  I've never called unmanaged code from my C# before, so I'm kind of at a loss.

A: You cannot call that DLL function because it uses the Delphi-specific string data type, which has no equivalent in non-Embarcadero products. (Even if your C# code can match the structure of Delphi's string type, you would also need to allocate the memory using the DLL's memory manager, which it almost certainly doesn't export.)
If you have the ability to change the DLL, then make the parameters have type PAnsiChar or PWideChar. (From your C# declaration, it looks like you want PAnsiChar.) That's what the DLL should have used all along.
If you can't change the DLL, then write a wrapper DLL in Delphi or C++ Builder that uses PAnsiChar or PWideChar and then forwards those parameters to the original Delphi DLL. Or complain loudly to the DLL vendor and request a new version that uses types that are more friendly to other languages.

A: Try
[DLLImport(MyDLL.dll, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern IntPtr SomeFunction(string someString, string SomeOtherString);

and use Marshal.GetObjectForNativeVariant with the return value to get a .NET object.