text:
Q: Getting original line number for exception in concurrent.futures Example of using concurrent.futures (backport for 2.7):
import concurrent.futures  # line 01
def f(x):  # line 02
    return x * x  # line 03
data = [1, 2, 3, None, 5]  # line 04
with concurrent.futures.ThreadPoolExecutor(len(data)) as executor:  # line 05
    futures = [executor.submit(f, n) for n in data]  # line 06
    for future in futures:  # line 07
        print(future.result())  # line 08

Output:
1
4
9
Traceback (most recent call last):
  File "C:\test.py", line 8, in <module>
    print future.result()  # line 08
  File "C:\dev\Python27\lib\site-packages\futures-2.1.4-py2.7.egg\concurrent\futures\_base.py", line 397, in result
    return self.__get_result()
  File "C:\dev\Python27\lib\site-packages\futures-2.1.4-py2.7.egg\concurrent\futures\_base.py", line 356, in __get_result
    raise self._exception
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

String "...\_base.py", line 356, in __get_result" is not endpoint I expected to see. Is it possible to get real line where exception was thrown? Something like:
  File "C:\test.py", line 3, in f
    return x * x  # line 03

Python3 seems to show correct line number in this case. Why can't python2.7? And is there any workaround?

A: Taking inspiration from the first answer, here it is as a decorator:
import functools
import traceback

def reraise_with_stack(func):

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            traceback_str = traceback.format_exc(e)
            raise StandardError("Error occurred. Original traceback "
                                "is\n%s\n" % traceback_str)

    return wrapped

Just apply the decorator on the executed function:
@reraise_with_stack
def f():
    pass

A: I was in your same situation and I really needed to have the traceback of the raised exceptions.
I was able to develop this workaround which consists in using the following subclass of the
ThreadPoolExecutor.
import sys
import traceback
from concurrent.futures import ThreadPoolExecutor

class ThreadPoolExecutorStackTraced(ThreadPoolExecutor):

    def submit(self, fn, *args, **kwargs):
        """Submits the wrapped function instead of `fn`"""

        return super(ThreadPoolExecutorStackTraced, self).submit(
            self._function_wrapper, fn, *args, **kwargs)

    def _function_wrapper(self, fn, *args, **kwargs):
        """Wraps `fn` in order to preserve the traceback of any kind of
        raised exception

        """
        try:
            return fn(*args, **kwargs)
        except Exception:
            raise sys.exc_info()[0](traceback.format_exc())  # Creates an
                                                             # exception of the
                                                             # same type with the
                                                             # traceback as
                                                             # message

If you use this subclass and run the following snippet:
def f(x):
    return x * x

data = [1, 2, 3, None, 5]
with ThreadPoolExecutorStackTraced(max_workers=len(data)) as executor:
    futures = [executor.submit(f, n) for n in data]
    for future in futures:
        try:
            print future.result()
        except TypeError as e:
            print e

the output will be something like:
1
4
9
Traceback (most recent call last):
  File "future_traceback.py", line 17, in _function_wrapper
    return fn(*args, **kwargs)
  File "future_traceback.py", line 24, in f
    return x * x
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

25

The problem is in the usage of sys.exc_info() by the futures library. From the
documentation:

This function returns a tuple of three values that give information about the exception that is
  currently being handled. [...]
  If no exception is being handled anywhere on the stack, a tuple containing three None values is
  returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets
  the exception type of the exception being handled (a class object); value gets the exception
  parameter (its associated value or the second argument to raise, which is always a class instance
  if the exception type is a class object); traceback gets a traceback object which encapsulates the
  call stack at the point where the exception originally occurred.

Now, if you look at the source code of futures you can see by yourself why the traceback is
lost: when an exception raises and it is to be set to the Future object only
sys.exc_info()[1] is passed. See:
https://code.google.com/p/pythonfutures/source/browse/concurrent/futures/thread.py (L:63)
https://code.google.com/p/pythonfutures/source/browse/concurrent/futures/_base.py (L:356)
So, to avoid losing the traceback, you have to save it somewhere. My workaround is to wrap
the function to submit into a wrapper whose only task is to catch every kind of exception and
to raise an exception of the same type whose message is the traceback. By doing this, when an
exception is raised it is captured and reraised by the wrapper, then when sys.exc_info()[1]
is assigned to the exception of the Future object, the traceback is not lost.

A: I think the original exception traceback gets lost in the ThreadPoolExecutor code. It stores the exception and then re-raises it later. Here is one solution. You can use the traceback module to store the original exception message and traceback from your function f into a string. Then raise an exception with this error message, which now contains the line number etc of f. The code that runs f can be wrapped in a try...except block, which catches the exception raised from ThreadPoolExecutor, and prints the message, which contains the original traceback.
The code below works for me. I think this solution is a little hacky, and would prefer to be able to recover the original traceback, but I'm not sure if that is possible.
import concurrent.futures
import sys,traceback

def f(x):
    try:
        return x * x
    except Exception, e:
        tracebackString = traceback.format_exc(e)
        raise StandardError, "\n\nError occurred. Original traceback is\n%s\n" %(tracebackString)

data = [1, 2, 3, None, 5]  # line 10

with concurrent.futures.ThreadPoolExecutor(len(data)) as executor:  # line 12
    try:
        futures = [executor.submit(f, n) for n in data]  # line 13
        for future in futures:  # line 14
           print(future.result())  # line 15
    except StandardError, e:
        print "\n"
        print e.message
        print "\n"

This gives the following output in python2.7:
1
4
9

Error occurred. Original traceback is
Traceback (most recent call last):
File "thread.py", line 8, in f
   return x * x
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

The reason your original code gives the right location when run in Python 3 and not 2.7 is that in Python 3 exceptions carry the traceback as an attribute, and when re-raising an exception, the traceback is extended rather than replaced. The example below illustrates this:
def A():
    raise BaseException("Fish")

def B():
    try:
        A()
    except BaseException as e:
        raise e

B()

I ran this in python 2.7 and python 3.1. In 2.7 the output is as follows:
Traceback (most recent call last):
  File "exceptions.py", line 11, in <module>
    B()
  File "exceptions.py", line 9, in B
    raise e
BaseException: Fish

i.e. the fact that the exception was originally thrown from A is not recorded in the eventual output. When I run with python 3.1 I get this:
Traceback (most recent call last):
  File "exceptions.py", line 11, in <module>
    B()
  File "exceptions.py", line 9, in B
    raise e
  File "exceptions.py", line 7, in B
    A()
  File "exceptions.py", line 3, in A
    raise BaseException("Fish")
BaseException: Fish

which is better. If I replace raise e with just raise in the except block in B, then python2.7 gives the complete traceback. My guess is that when back-porting this module for python2.7 the differences in exception propagating were overlooked.


text:
Q: Cubemapping in opengl using fixed function pipeline I am trying to get a skybox effect using cubemapping. The skybox is drawn as a single batch of six GL_QUADS. Each face is then manually textured using glTexCoord3f.
But for each vertex, a vector has to be specified that points to that corner of the sky box. Here is where I am stuck. How do I specify this vector?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doxygen: How to avoid including C++ class source code in the generated html files? I've created the doxygen project with doxygen wizard for my C++ project. I've found that my header class source code is included in the html documentation. I'd like to avoid this. These files are *_8h_source.html . I can remove the references to the Files section but I'd like remove these files also.
I tried to play with the following options but these files are still there.
EXTRACT_LOCAL_CLASSES=xx
EXTRACT_ALL=xx

Doxygen version: 1.9.3

A: The display of the header files is a complicated issue and depending on a.o. the setting of SOURCE_BROWSER and VERBATIM_HEADERS.
The documentation of:

SOURCE_BROWSER
If the SOURCE_BROWSER tag is set to YES then a list of source files will be generated. Documented entities will be cross-referenced with these sources.
Note: To get rid of all source code in the generated output, make sure that also VERBATIM_HEADERS is set to NO.
The default value is: NO.

and

VERBATIM_HEADERS
If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a verbatim copy of the header file for each class for which an include is specified. Set to NO to disable this.
See also
Section \class.
The default value is: YES.

See: https://www.doxygen.nl/manual/config.html
Setting both SOURCE_BROWSER and VERBATIM_HEADERS to NO will result in the required output.


text:
Q: im grtting an error called (send_login_otp failure - module 'requests' has no attribute 'post4') first i taut i have multiple file usig same name but i anable to find the file so,  i tried using create new virtual env but i got same error .even i tried to upgrade the package but noting works .
here is my code
import requests
 def verify_totp(request_key, totp):

     try:

payload = {

  "request_key": request_key,

  "otp": totp

}

result_string = requests.post4(url=URL_VERIFY_TOTP, json=payload)

if result_string.status_code != 200:

  return [ERROR, result_string.text]

result = json.loads(result_string.text)

request_key = result["request_key"]

return [SUCCESS, request_key]

A: It should be requests.post not requests.post4
Also check your try block and indentation.

 def verify_totp(request_key, totp):
    # you can avoid the use of a `try except`block if you don't use it

    payload = {

        "request_key": request_key,
        "otp": totp
    }

    result_string = requests.post(url=URL_VERIFY_TOTP, json=payload)

    if result_string.status_code != 200:
        return ["ERROR", result_string.text]

    result = json.loads(result_string.text)
    request_key = result["request_key"]

    return ["SUCCESS", request_key]

request_key = "<INSERT YOUR REQUEST KEY HERE>"
totp = "<INSERT YOUR TOTP HERE>"

request_status, request_key = verify_totp(request_key, totp)

print(request_status, request_key)


text:
Q: Notes regarding Real analysis I recently came across professor Alan Sokal page , which contains beautiful handout notes for functional analysis. These notes are very helpful to work with functional analysis. The interesting and challenging fact is to fill the gaps in these notes.  Especially Sokal asks "Why" in most of the lines in the proof of every theorems and filling these details is very interesting. Now I want these type of notes in Real analysis.  I already found COMPANION NOTES: A Working Excursion to Accompany BabyRudin by Evelyn M. Silvia  in online and this notes has also an interesting gaps to work.
Is there any other such type of notes ? Any suggessions ?


text:
Q: Html css number keypad align issue Codepen link
I have this number keypad using html and css. Now im facing some alignment issue from 3rd row and ok button. I tried with all the row as new tables, so i can do ok button on the number pad.

                    +5
                    +10
                    +20
                    +50

                    1
                    2
                    3
                    X

                    OK

                    4
                    5
                    6

                    7
                    8
                    9

                    0
                    .

A: As i said into comment one table is pretty simple to do

.keyboard {
  display: flex;
  flex-shrink: 0;
  padding: 3px;
  background: #000000;
  flex-direction: column;
  /*touch-action: none;*/
}

.numbersButtons {
  width: calc(100% - 1px);
}

.quickPickButtons {
  width: 25%;
}

.row {}

.keyboard td {
  padding: 0;
  margin: 0;
}

.button {
  position: relative;
  height: 25px;
  width: 25%;
  line-height: 25px;
  text-align: center;
  color: #ffffff;
  background: #333333;
  margin: 1px;
  font-size: 22px;
  /*touch-action: none;*/
}

.numbersButtons .row:first-child .button:first-child {
  border-radius: 5px 0 0 0;
}

.numbersButtons .row:first-child .button:last-child {
  border-radius: 0 5px 0 0;
}

/*.numbersButtons .row:last-child .button:first-child { border-radius: 0 0 0 5px; } .numbersButtons .row:last-child .button:last-child { border-radius: 0 0 5px 0; }*/

.numbersButtons .row:third-child .button:last-child {
  height: 50px;
  background: red;
}

.numbersButtons2 {
  width: 75%;
  -webkit-border-vertical-spacing: 0;
}

.numbersButtons3 {
  width: 25.1%;
  height: 75px;
  margin-left: 75%;
  -webkit-border-vertical-spacing: 0;
}

.numbersButtons4 {
  width: 75%;
  margin-top: -76px;
}

.lastRow {}

.zero {
  width: 66.65%;
}

.dot {
  width: 33.35%;
}

.numbersButtons2 .lastRow:last-child .button:first-child {
  border-radius: 0 0 0 5px;
}

.numbersButtons2 .lastRow:last-child .button:last-child {
  border-radius: 0 0 5px 0;
}

.quickPickButtons .button {
  background: #4caf50;
  color: #ffffff;
}

.quickPickButtons .row:first-child .button {
  border-radius: 5px 5px 0 0;
}

.quickPickButtons .row:last-child .button {
  border-radius: 0 0 5px 5px;
}

.button.pressed {
  background: #000000;
  color: #ffffff;
}

.deleteIcon {
  height: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

        +5
        +10
        +20
        +50

        1
        2
        3
        X

        4
        5
        6
        OK

        7
        8
        9

        0
        .

Good resource:

*

*How do you use colspan and rowspan in HTML tables?

A: Simplest solution: use grid !

/* -- Layout -- */

.keyboard {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(5, auto);
  grid-template-areas:
    "q1 q2 q3 q4"
    "d1 d2 d3 X"
    "d4 d5 d6 ok"
    "d7 d8 d9 ok"
    "o  o  dt ok";
  gap: 2px;
  padding: 4px;
}

#ok {
  grid-area: ok;
}

#d0 {
  grid-area: o;
}

/* -- Layout DONE. The rest is decoration -- */

/* colors and fonts */

.keyboard {
  background: black;
  border-radius: 7px;
  font-size: 22px;
}

.keyboard button {
  color: #ffffff;
  background: #333333;
  border: none;
  font-size: inherit;
}

.keyboard button.quickpick {
  background: #4caf50;
  color: #ffffff;
}

/* button hover/focus/active */

.keyboard button:hover {
  filter: brightness(120%);
}

.keyboard button:focus {
  outline: 1.5px solid rgba(255, 255, 255, .5);
}

.keyboard button:active {
  filter: brightness(60%);
}

/* border radii for buttons */

.keyboard button:first-child {  /* upper-left */
  border-radius: 5px 0 0 0;
}

.keyboard button:nth-child(4) { /* upper-right */
  border-radius: 0 5px 0 0;
}

.keyboard button:last-child {   /* lower-right */
  border-radius: 0 0 5px 0;
}

.keyboard button#d0 {           /* lower-left */
  border-radius: 0 0 0 5px;
}

  <button id="plus-5" class="quickpick">+5</button>
  <button id="plus-10" class="quickpick">+10</button>
  <button id="plus-20" class="quickpick">+20</button>
  <button id="plus-50" class="quickpick">+50</button>

  <button id="d1">1</button>
  <button id="d2">2</button>
  <button id="d3">3</button>
  <button id="multiply">X</button>

  <button id="ok">OK</button>

  <button id="d4">4</button>
  <button id="d5">5</button>
  <button id="d6">6</button>

  <button id="d7">7</button>
  <button id="d8">8</button>
  <button id="d9">9</button>

  <button id="d0">0</button>
  <button id="dot">.</button>


text:
Q: Is it possible to programmatically retrieve link clicks from iislogs? We have an app built by a vendor that gives our users the ability to see events and their dates.
A user can search for an event by searching by either specific date, date range, or by event name.
If found, the results are displayed as links and users can click these links to view details.
We are interested in capturing the number of clicks by visitors to the site.
Since the app is not built by us, we are unable to figure out a way to retrieve how many times a user or site visitor clicks on a particular link on a particular page.
We can, however, open an iislog in windows\system32 directory to grab information about click counts.
My question is whether there is a way to programmatically retrieve link click counts on a particular page from iislogs?
Thanks in advance.


text:
Q: Finding camera position without calibration I have to find the camera position using several images from a football field. Using these images I can find the homography that transforms the points in the 3D model (in meters) into the points in the image (pixels). Each picture can have a different focal lengths, hence the camera intrinsics can change. I'm using OpenCV in C++.
I've found solutions for similar problems but either you already have the camera calibrated, with a fixed focal length (in this case you only need one image) or you don't have the camera calibrated but you consider that its intrinsic doesn't change (in this case you need at least 3 images).
Is there anyway to find the camera position in the 3D model without knowing anything besides the homographies (with different focal lengths)?

A: Short answer: No.
If you don't have any additional information about the cameras, there is no way to uniquely position the cameras.  There would be multiple combinations of camera attributes & positions that would produce the same image.
You may be able to constrain the camera position along a certain 3D line, and reduce the problem to 1 degree of freedom, if that helps.


text:
Q: defining and chaining tasks separately I was hoping that I could somehow define and then chainem up in a nice way to get some code similar to this:
Task ShowLoadNotificationTask = new Task( () => ShowLoadNotification(frm) );
Task LoadAllWorkOrdersTask = new Task(() => LoadAllWorkOrders());
Task CloseLoadNotificationTask = new Task(() => CloseLoadNotificationTask(frm));

ShowLoadNotificationTask.ContinueWith( LoadAllWorkOrdersTask );
LoadAllWorkOrdersTask..ContinueWith(CloseLoadNotificationTask);

ShowLoadNotificationTask.Start();

Of course the above code is not correct, but how to get something working similar to above?

A: It sounds like you want to independently construct Task instances and then later combine them together into a single Task.  If so then what you are looking for is the Unwrap extension method defined in System.Core
Task parent = ShowLoadNotificationTask
  .ContinueWith(_ => LoadAllWorkOrdersTask)
  .Unwrap()
  .ContinueWith(_ => CloseLoadNotificationTask)
  .Unwrap();

The Unwrap method takes a Task<Task> and returns back a Task (the same goes for Task<Task<T>>.  This allows you to return a Task as the continuation of an existing Task and get back the original Task type you returned.


text:
Q: Compare list of files from a database using find to locate missing files I have a list of 2000 files from a database that looks like this:
./aa/0f/unique-string/IMG_0987.JPG
./ab/cf/unique-string/IMG_0987.JPG

I want to compare that list to the actual directory contents in order to identify missing files.
The following command works individually, but not when I script it...
find . -false -samefile ./ab/cf/unique-string/IMG_0987.JPG

The closest I have come is the following:
#!/bin/bash
TEST=`cat ./list.lst`
find . -false -samefile "$TEST"

I am doing it wrong. what is the right way?

A: Your find command is using the entire contents of list.lst because you aren't feeding it through 1 line at a time.
while read f; do
find . -false -samefile "$f"
done<./list.lst

This reads the file list.lst 1 line at a time.

A: By following your strategy, you will be making about 2000x2000 = 4,000,000 comparisons. You can do better than this.
Suppose the list is in file_t1; now we first generate a list of all files on the pc by means of
      find . -type f > file_t2

Then we sort both files:
      sort -n file_t1 > file1
      sort -n file_t2 > file2

Now we use comm to generate a list of differences:
      comm -X file1 file2

where:
      X = 12 -> lines that appear in **both** files
      X = 13 -> lines unique to file 2
      X = 23 -> lines unique to file1

This could be done with a one-liner, at the expense of clarity.
If you are interested: this is much faster because the files are already sorted (a strict requirement for comm), so they take of order N steps to compare, if the file size is N. Sorting requires N log N operations, which is thus the most expensive part of this solution, while the one you proposed requires N^2 operations, which is significantly longer for your file sizes.


text:
Q: can I send "SMS received intent" in android 4.1.2? This code doesn't work with android version 4.1.2,
private static void createFakeSms(Context context, String sender,String body)
{
  byte[] pdu = null;
  byte[] scBytes = PhoneNumberUtils.networkPortionToCalledPartyBCD("0000000000");
  byte[] senderBytes = PhoneNumberUtils.networkPortionToCalledPartyBCD(sender);
  int lsmcs = scBytes.length;
  byte[] dateBytes = new byte[7];
  Calendar calendar = new GregorianCalendar();
  dateBytes[0] = reverseByte((byte) (calendar.get(Calendar.YEAR)));
  dateBytes[1] = reverseByte((byte) (calendar.get(Calendar.MONTH) + 1));
  dateBytes[2] = reverseByte((byte) (calendar.get(Calendar.DAY_OF_MONTH)));
  dateBytes[3] = reverseByte((byte) (calendar.get(Calendar.HOUR_OF_DAY)));
  dateBytes[4] = reverseByte((byte) (calendar.get(Calendar.MINUTE)));
  dateBytes[5] = reverseByte((byte) (calendar.get(Calendar.SECOND)));
  dateBytes[6] = reverseByte((byte) ((calendar.get(Calendar.ZONE_OFFSET) + calendar
 .get(Calendar.DST_OFFSET)) / (60 * 1000 * 15)));
  try
  {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    bo.write(lsmcs);
    bo.write(scBytes);
    bo.write(0x04);
    bo.write((byte) sender.length());
    bo.write(senderBytes);
    bo.write(0x00);
    bo.write(0x00); // encoding: 0 for default 7bit
    bo.write(dateBytes);
    try
    {
      String sReflectedClassName = "com.android.internal.telephony.GsmAlphabet";
      Class cReflectedNFCExtras = Class.forName(sReflectedClassName);
      Method stringToGsm7BitPacked = cReflectedNFCExtras.getMethod(
      "stringToGsm7BitPacked", new Class[] { String.class });
      stringToGsm7BitPacked.setAccessible(true);
      byte[] bodybytes = (byte[]) stringToGsm7BitPacked.invoke(null,body);
      bo.write(bodybytes);
     }
     catch (Exception e)
     {
     }
     pdu = bo.toByteArray();
     }
     catch (IOException e)
     {
     }
    Intent intent = new Intent();
    intent.setClassName("com.android.mms",
            "com.android.mms.transaction.SmsReceiverService");
    intent.setAction("android.provider.Telephony.SMS_RECEIVED");
    intent.putExtra("pdus", new Object[] { pdu });
    intent.putExtra("format", "3gpp");
    context.startService(intent);
}

private static byte reverseByte(byte b) {
    return (byte) ((b & 0xF0) >> 4 | (b & 0x0F) << 4);
}

When I call context.startService(intent) I am getting this exception
java.lang.SecurityException: Not allowed to start service Intent { act=android.provider.Telephony.SMS_RECEIVED cmp=com.android.mms/.transaction.SmsReceiverService (has extras) } without permission not exported from uid 10046**

on virtual device 4.1.2 it works perfectly but not in my GS2 device.
Can anyone help me?

A: In newer versions of Android this is a protected broadcast which can only be sent by system apps for security reasons.
The only way to get your app to send it is to convince the OEM to make it a system app on their ROM


text:
Q: Jeknins pipeline Global Vars - return a variable from a shell script, then export it into a shell script I need to split a git tag by dashes.  Here is an example of the data:
DEVQA-10000000-6d26fa05def3fa94a2acd0ca12fcdd6a82fc46d7-SUCCESS
This should split as $1-$2-$3-$4
My idea was to use awk git tag -l | grep DEVQA |  awk -F '[ -]' '{print $1}' for instance.
I tried defining using withEnvs, i tried getting the values in another script and loading it into mine i.e. load 'env/file'
I cant seem to figure it out.  It prints the commands as the pipeline run s
stage('Build ') {
def buildRecordId = sh(script: "git tag -l | grep DEVQA | awk -F \'[ -]\' \'{print \$2}\'", returnStdout: true).trim() as Integer
def startRev = sh(script: "git tag -l | grep DEVQA | awk -F \'[ -]\' \'{print \$3}\'", returnStdout: true).trim()
def testlevel="noLocalTests"
sh """ export testlevel="${testlevel}";
export startrevision="${env.startRev}";
export buildrecordid="${env.buildRecordId}";
echo "I worked: $startrevision";
/tools/ant/apache-ant-1.9.4/bin/ant  -verbose -buildfile ./buildtool/build.xml -propertyfile ./buildtool/build.properties.hc.inc.dev startCICD
            """
                    }

And of course it doesnt find startrevision:
"groovy.lang.MissingPropertyException: No such property: startrevision for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264)

A: You used triple double quote string in sh step, which will do string interpolation before execute the bash inside sh step. Read detail at here
String interpolation will try to replace ${ABC} or $ABC with value of groovy variable ABC.
Your error says it fail to find groovy variable startrevision when doing interpolation.
If startrevision intend to be a bash environment variable, you need to escape the $ by \$, if a groovy variable, please define and assign value to it.
echo "I worked: \$startrevision";


text:
Q: How does one select some $i$ to prove $\exists i$ s.t. $s_i \leq A$ where $A$ is the average of real numbers $(s_1 + s_2 + . . . + s_n) / n$ How does one select some $i$ to prove $\exists i$ s.t. $s_i \leq A$ where $A$ is the average of real numbers $(s_1 + s_2 + . . . + s_n) / n$
It seems like a trivial proof, but writing a proof for such an existence conventionally does not seem obvious to me.
Perhaps I am reading it wrong, but I am sure it says something like: For any real number $A$ which is the average of a set, $S$, of real numbers, there exists a number $s \in S$ s.t. $s$ is less than or equal to $A$.
Is there a special way to choose $i$ to prove this existence? It seems I cannot trivially select a set of numbers and show there is a value that satisfies $s_i \leq A$ since it is some arbitrary set. How would you select $i$ for this proof?

A: If not, then $s_i> A $ for all $i$. So
$$A=\frac{s_1+s_2+\cdots+s_n}{n}>\frac{\overbrace{A+A+\cdots+A}^{n\text{ times}}}{n}=A$$
So derive a contradiction.


text:
Q: Show that $HB^2 + HC^2 + 5DM^2 = 2DB^2 + 2DC^2$ as follows. Edit
Let $ABC$ be triangle with the orthocenter $H$, the circumcenter $O$, and $M$ be the midpoint of $BC$. Let $D$ lies on $BC$ such that $AD \perp BC$. Let $\omega$ be the circle with diameter $OH$. If $BC$ is tangent to
$\omega$, then show that
\begin{equation*}
HB^2 + HC^2 + 5DM^2 = 2DB^2 + 2DC^2.
\end{equation*}
I have tried, but get stuck and always back to the start because only using the Pythagorean theorem and not using the given circle $\omega$. How to show it?

A:
Let the centre of the circle with diameter $OH$ be $P$ and let its point of tangency with $BC$ be $K$. Extend $AD$ to meet the circumcircle of $\triangle ABC$ at $L$. Draw $HK$,  $KO$, $PK$, $HB$, $HC$ & $BL$. $PK\perp BC$ & $HP=PK=PO$.
Since the parallel lines $HD$, $PK$ and $OM$ divide the transversal $HPO$ into two equal segments $HP$ and $PO$, they must divide $DKM$ in a similar way.
$\Rightarrow   DK=KM=\frac{DM}{2}$
The circle with diameter $OH$ touches $BC$ at $K$; Hence $\triangle HKO$ is right angled at $K$.
Observe that, $\triangle HDK\sim \triangle KMO$
$\Rightarrow   \frac{HD}{DK}=\frac{KM}{OM}$ $\Rightarrow   \left(\frac{DM}{2}\right)^2 = HD\cdot OM$
$DM=\frac{BC}{2}-BD=DC-\frac{BC}{2}$ $\Rightarrow  DM=\frac{\left(\frac{BC}{2}-BD\right)+\left(DC-\frac{BC}{2}\right)}{2} = \frac{1}{2}\left(DC-BD\right)$
Since $\angle HBD=90-\angle C=\angle DAC=\angle LAC=\angle LBC=\angle LBD$ and $BD\perp HL$, $HD=DL$.
$\Rightarrow AD\cdot HD=AD\cdot DL=BD\cdot DC$
Hence, $HB^2+HC^2+5DM^2$
$=\left(HD^2+BD^2\right)+(HD^2+DC^2)+20HD\cdot OM$
$=\left(BD^2+DC^2\right)+2HD^2+20HD\cdot OM$
$2HD^2+20(HD\cdot OM)$
$=2HD\left(HD+10OM\right)$
$=2HD\left(HD+2OM+8OM\right)$
Since, $O$,$G$ & $H$ lie on the Euler line and $\frac{AG}{GM}=2$, $AH=2OM$.
Thus, $2HD\left(HD+AH+8OM\right)$
$=2HD\left(AD+8OM\right)$
$=2HD\cdot AD+16HD\cdot OM$
$=2BD\cdot DC+\left(2DM\right)^2$
$=2BD\cdot DC+\left(DC-BD\right)^2 =BD^2+DC^2$
Therefore, $HB^2+HC^2+5DM^2$
$=(BD^2+DC^2)+2HD^2+20HD\cdot OM=\boxed {2(BD^2+DC^2)}$.


text:
Q: Unwind segue doesn't work in Swift 3 and iOS 10 I'm trying to test unwind segue in iOS 10 and Swift 3.
I made a simple app like this:

I add code for segue in TableViewController class and connect "Cancel" button and Exit on Table View Controller Scene:
@IBAction func unwindToRootViewController(segue: UIStoryboardSegue) {
    print("Unwind to Root View Controller")
}

but my simple segue doesn't work. What am I doing wrong?

A: As can be seen in the comments above the problem was this:

I add code for segue in TableViewController class

The unwind segue has to be in your "outer" ViewController, not the TableViewController.
This article gives a very nice introduction to unwind segues.


text:
Q: 301 redirect problem in ASP.NET I am developed web site with .NET,now i want to implement 301 redirect(non www to www).I have used theis code
RewriteEngine On
RewriteCond %{HTTP_HOST} ^xxx.com [NC]
RewriteRule ^(.*)$ http://www.xxx.com/$1 [L,R=301]

But i didn't redirect with www.
I have used following settings in File Zilla.
My site port NO:10021
Protocal:FTP
Encryption:Require explicity FTP over TLS
Thanks in advance.

A: That's an .htaccess file which is for Apache servers. See this blog post for URL writing with .Net.

A: If you are doing URL Routing.. I wrote this article to do it in .Net 4.0...
If you are wanting to do a 301 Permanent Change... At the end of this article you will see how to do it in .Net 4.0.  Otherwise you have to put a page out there and do a Response.Redirect (which does not update Search Engines - The new 4.0 method does).


text:
Q: How to inject a repository on another repository class in Laravel 5 (5.2) Let's say I have two repositories (UserRepository, RoleRepository) that implements a contract (UserRepositoryInterface, RoleRepositoryInterface).
What I wanted to do is to inject RoleRepository into UserRepository's constructor method and I've been trying to make this work but I'm getting this error:

Target [App\Contracts\UserRepositoryInterface] is not instantiable while building [App\Http\Controllers\UserController].

Here's what I got so far,
composer.json
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "tymon/jwt-auth": "^0.5.9",
    "zizaco/entrust": "dev-laravel-5"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "^0.9.4",
    "phpunit/phpunit": "~4.0",
    "symfony/css-selector": "2.8.*|3.0.*",
    "symfony/dom-crawler": "2.8.*|3.0.*"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/",
        "App\\Models\\": "app/Models/",
        "App\\Contracts\\": "app/Contracts/",
        "App\\Repositories\\": "app/Repositories/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php",
        "tests/MockData.php"
    ]
}

config/app.php
'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    ...

    /**
     * Third-party Service Providers
     */
    ...

    /*
     * Application Service Providers...
     */
    ...

    /**
     * Custom Service Providers...
     */
    App\Providers\RepositoryServiceProvider::class,

app/Providers/RepositoryServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $models = [
            'Role',
            'User',
        ];

        foreach ($models as $model) {
            $this->app->bind(
                "App\Contracts\\{$model}Interface",
                "App\Repositories\\{$model}Repository"
            );
        }
    }
}

app/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Contracts\UserRepositoryInterface as UserRepository;

class UserController extends Controller
{

    /**
     * @var UserRepository
     */
    private $repo;

    /**
     * Class constructor
     *
     * @param UserRepository $repo
     */
    public function __construct(
        UserRepository $repo
    ) {
        $this->repo = $repo;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $data = $request->all();

        $user = $this->repo->store($data);

        return response()->json($user, 201);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();

        $user = $this->repo->store($data, $id);

        return response()->json($data, 200);
    }

app/Contracts/RoleRepositoryInterface.php
<?php

namespace App\Contracts;

interface RoleRepositoryInterface
{
    /**
     * Attach role to user
     *
     * @param  static $user
     * @param  string $roleName
     *
     * @return static
     */
    public function role($user, $roleName);

}

app/Contracts/UserRepositoryInterface.php
<?php

namespace App\Contracts;

interface UserRepositoryInterface
{

    /**
     * Create new or update an existing user
     *
     * @param  array  $data
     * @param  int    $id
     *
     * @return bool|int|array
     */
    public function store(array $data, $id = null);
}

app/Repositories/RoleRepository.php
<?php

namespace App\Repositories;

use InvalidArgumentException;

use App\Contracts\RoleRepositoryInterface;
use App\Models\Role;

class RoleRepository extends Role implements RoleRepositoryInterface
{

    /**
     * Attach a role to user
     *
     * @param  static $user
     * @param  string $roleName
     *
     * @return static
     *
     * @throws \InvalidArgumentException
     */
    public function attachRole($user, $roleName)
    {
        if (!$user instanceof App\Models\User::class) {
            throw new InvalidArgumentException("{$user} must be an instance of App\Models\User");
        }

        // find role
        $role = $this->where('name', $roleName)->first();

        // attach role to user
        $user->attachRole($role);

        return $user;
    }
}

app/Repositories/UserRepository.php
<?php

namespace App\Repositories;

use App\Contracts\RoleRepositoryInterface as RoleRepository;
use App\Contracts\UserRepositoryInterface;
use App\Models\User;

class UserRepository extends User implements UserRepositoryInterface
{

    /**
     * @var RoleRepository
     */
    private $roleRepo;

    /**
     * Class constructor
     *
     * @param RoleRepository $roleRepo
     */
    public function __construct(RoleRepository $roleRepo)
    {
        $this->roleRepo = $roleRepo;
    }

    /**
     * Create new or update an existing user
     *
     * @param  array  $data
     * @param  int    $id
     *
     * @return bool|int|static
     */
    public function store(array $data, $id = null)
    {
        if (is_null($id)) {
            $user = $this->create($data);
            $userWithRole = $this->roleRepo->attachRole($user, $data['role']);

            return $user;
        } else {
            return $this->where('id', $id)
              ->update($data);
        }
    }
}

Any answers is greatly appreciated...

A: I think you have an error in your code, specifically in the RepositoryServiceProvider. It should be:
foreach ($models as $model) {
        $this->app->bind(
            "App\Contracts\\{$model}RepositoryInterface",
            "App\Repositories\\{$model}Repository"
        );
}

Note: the error is in the concatenation, you got "App\Contracts\\{$model}Interface", but it should be "App\Contracts\\{$model}RepositoryInterface"


text:
Q: Conditional formatting issue
Column C is just a helper column to see true and false. Trying to fill column B when its value is less than that of column A. However conditional formatting formula is not doing it. Anything I am missing? I also tried =B1<A1 it did not work either.


text:
Q: Update =NOW() -- before -- generating email with hyperlink Have a hyperlink in B7 generating email, which uses E7 with =NOW() that goes as part of email's subject line. Using below code updates only after generating email, need before:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("b7")) Is Nothing Then 'before email is generated to update =NOW in E7
Application.Calculate
End If
End Sub

A: If your are using the HYPERLINK-function you can put NOW in the subject part:
=HYPERLINK("mailto:xx@XXX.com?subject=Report FROM "  & TEXT(NOW(),"dd.MM.YYYY hh:nn"),"send mail")


text:
Q: Tower of Hanoi maximum counts of 100 allowed I've recently coded on python3 the famous Tower of Hanoi problem. I would like to ask how to add an additional condition: if there are more than 100 movements, then exit the program and print "Tedious computational power".
# Tower of Hanoi problem
print('Tower of Hanoi')

no_discs = int(input('Please input number of discs: '))

column_1 = 1
column_2 = 2
column_3 = 3

def thaphanoi(no_discs, column_1, column_2, column_3):
    if no_discs == 1:
        print("Disc in column {} -> column {}".format(column_1, column_2))
    else:
        thaphanoi(no_discs - 1, column_1, column_3, column_2)
        thaphanoi(1, column_1, column_2, column_3)
        thaphanoi(no_discs - 1, column_3, column_2, column_1)

thaphanoi(no_discs, column_1, column_3, column_2)
print('Program ended')

I expect this code to print 7.

A: Tower of Hanoi problem can be solved with minimum of (2^n)-1 moves.
That is
No of move required for 1 disk -->  1
No of move required for 2 disks -->  3
No of move required for 3 disks -->  7
No of move required for 4 disks -->  15
No of move required for 5 disks -->  31
No of move required for 6 disks -->  63
No of move required for 7 disks -->  127
and so on..

So you can calculate number of movements required after getting the number of required.
like,
min_moves = math.pow(2, no_discs) - 1
if min_moves > 100:
  print("Too many moves")
  sys.exit()


text:
Q: Is it mandatory to create a DNS Entry for every New Web application created in SharePoint I am new to sharepoint and trying to learn things
I have created a web application with name intranet and given in host header as intranet.testmachine.com
Created the web application successfully on port 80.
I want to understand is it mandatory to create the DNS Entry on Domain Controller now?
If so what is the purpose ?
Please forgive my ignorance.

A: It depends on the requirement and scope for the SharePoint environment.
1) If there are almost all users that will be using the site then you need to make an DNS entry to resolve the URL thoroughly.
2) If there are some users (like only developers) who would use the SharePoint, in this scenario you need to make a host file entry for URL instead of DNS entry.
So depending on the scope define the option which suites you.


text:
Q: Getting CUDA error when trying to train MBART Model from transformers import MBart50TokenizerFast
from transformers import MBartForConditionalGeneration
tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt",src_lang="", tgt_lang="")
model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt");
batch_size = 8

args = Seq2SeqTrainingArguments(
output_dir="./resultsMBart",
evaluation_strategy = "epoch",
learning_rate=3e-5,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
save_total_limit=3,
num_train_epochs=3,
predict_with_generate=True,
fp16=False,
report_to = "none")

trainer = Seq2SeqTrainer(
model,
args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["validation"],
data_collator=data_collator,
tokenizer=tokenizer,
compute_metrics=compute_metrics)
trainer.train()
RuntimeError: CUDA out of memory. Tried to allocate 978.00 MiB (GPU 0; 15.74 GiB total capacity; 13.76 GiB already allocated; 351.00 MiB free; 14.02 GiB reserved in total by PyTorch)
If reserved memory is >> allocated memory try setting max_split_size_mb to avoid    fragmentation.
See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

I have recently started working in NLP and was trying to train MBART Model using my data set but every time I set it for training,I get a CUDA error.I have tried decreasing batch size as well as killing all processes on the GPU to prevent this error but I cannot seem to figure out a solution.Would anyone have an idea on how I could fix this and train the model?
The data set I am using has approximately 2 million sentences but that didn't lead to a problem when I tried using other models,so I have no idea why this is occuring,any help would be well appreciated.
The GPU I am using is NVIDIA Quadro RTX 5000.

A: There are a few things that you can try in order to reduce the memory footprint and avoid OOM issues:

*

*Gradient accumulation: When using gradient accumulation, gradient calculation is done in smaller steps rather than all at once for a batch. In order to use this, all you have to do is set the gradient_accumulation_steps argument to a number that would fit into memory, and modify the per_device_train_batch_size to original_batch_size/gradient_accumulation_steps. For example, assuming your GPU can take up to a batch size of 2 (and ideally you want to max it out), and you intend to train with a batch size of 8, this is how you should set up your training arguments to ensure that it fits into memory:

batch_size = 8
gradient_accumulation_step = 2 #needs to be a batch size that can fit into memory

args = Seq2SeqTrainingArguments(
output_dir="./resultsMBart",
evaluation_strategy = "epoch",
learning_rate=3e-5,
gradient_accumulation_steps = gradient_accumulation_steps,
per_device_train_batch_size=batch_size/gradient_accumulation_step,
per_device_eval_batch_size=batch_size/gradient_accumulation_step,
save_total_limit=3,
num_train_epochs=3,
predict_with_generate=True,
fp16=False,
report_to = "none")

*

*Gradient checkpointing: This approach helps save memory by reducing the memory overhead by saving only selective activations as opposed to saving all of them. To use this, the gradient_checkpointing needs to be set to True
I highly recommend reading the Performance and scalability section of the transformers documentation to understand the pros and cons of the aforementioned approaches better, and to familiarize yourself with other techniques as well such as mixed precision training and optimizer usage.


text:
Q: Get touch point location I have UIWebView for display the articles. I have UIWebView for displays HTML articles. When user touch some area in UIWebView, UIMenuController will display. Then user select note button it displays UITextView. How to get touch location?
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    // Get the specific point that was touched
    CGPoint point = [touch locationInView:wbCont];
    NSLog(@"X location: %f", point.x);
    NSLog(@"Y Location: %f",point.y);

}

- (void)note:(id)sender  {

}

A: UIWebview is wrapped inside a UIScrollView. Therefore the touch events do not go through to the UIView where your method receives the touch events.
For your UIViewController it should implement UIGestureRecognizerDelegate
Then add a gesture to your webview:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTest:)];
[tap setDelegate:self];
[self.yourwebview.scrollView addGestureRecognizer:tap];

Next:
- (void)tapTest:(UITapGestureRecognizer *)sender {
    NSLog(@"%f %f", [sender locationInView:self.yourwebview].x,  [sender locationInView:self.yourwebview].y);
}

Edit:
shouldRecognizeSimultaneouslyWithGestureRecognizer should return YES as well.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

A: Try this :-
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    firstTouch = [touch locationInView:self.view];

    NSLog(@" CHECKING CGPOINT %@", NSStringFromCGPoint(firstTouch));

}

works fine for me ;-)

A: -(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event

{

     NSSet *touches = [event allTouches];

    UITouch *touch = [touches anyObject];

    //UITouch *touch = [[event touchesForView:textview] anyObject];
     CGPoint location = [touch locationInView: wbCont];

     CGPoint previousLocation = [touch previousLocationInView:textview];

}

A: There's only one truly fail-safe way to do this (that I know of):
@interface MyWebView : UIWebView
@end

@implementation MyWebView

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if ([self pointInside:point withEvent:event])
    {
        NSLog(@"Touched inside!");
    }

    return [super hitTest:point withEvent:event];
}

@end

Web views are extremely complex, so overriding those UIResponder methods or adding gesture recognisers won't work. Unfortunately, hitTest:withEvent: gets called 3 times on each touch, so you'll have to deal with that.

A: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

 UITouch *touch = [touches anyObject];
    NSLog(@"X location: %f",touch.view.position.x);
    NSLog(@"Y Location: %f",touch.position.y);
}


text:
Q: Call Controller Action from script in View I am trying to call the controller action from my script but the method is not being invoked.
This is my controller action:
 [HttpPost]
 public ActionResult EditQuantity(int? id, int quantity)
 {
     if (id == null)
     {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     Cart cart = db.Carts.Find(id);
     if (cart == null)
     {
         return HttpNotFound();
     }
     cart.Quantity = quantity;
     db.SaveChanges();
     string url = this.Request.UrlReferrer.AbsolutePath;
     return Redirect(url);
 }

This is my script:

And the script is being called as follows from HTML:

The solution is going in the script, from the script the call is not being made to the action.

A: I had a typo in 'productId' - should be 'ProductId'. It's working now :)

A: everything seems good in your provided code. Have you looked for any javascript error in browser console and your action is in right controller ?


text:
Q: Is it possible to update a reference in a method? I have asked this question here. I will try to make this one more specific.
class Example {

    public static void main(String[] args) {
        A a = null;
        load(a);
        System.out.println(a.toString());
        // outcome is null pointer exception
    }

    private static void load(A a) {
        a = new A();
    }

}

class A {
   public void String toString() {
       return "Hello, world!"
   }
}

So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.

A: Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {

    public static void main(String[] args) {
        A[] a = new A[1];
        a[0] = new A("outer");
        System.out.println(a[0].toString());
        load(a);
        System.out.println(a[0].toString());
    }

    private static void load(A[] a) {
        a[0] = new A("inner");
    }

}

class A {

    private String name;

    public A(String nm){
        name = nm;
    }

    public String toString() {
        return "My name is: " + name;
    }
}

EXAMPLE 2:
class Example {

    public static void main(String[] args) {
        A[] a = new A[1];
        a[0] = null; // not needed, it is null anyway
        load(a);
        System.out.println(a[0].toString());
    }

    private static void load(A[] a) {
        a[0] = new A("inner");
    }

}

class A {

    private String name;

    public A(String nm){
        name = nm;
    }

    public String toString() {
        return "My name is: " + name;
    }
}

NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.

A: As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {

    public static void main(String[] args) {

        A[] aArray=new A[1];

        load(aArray);
        System.out.println(aArray[0].toString());
        // outcome is Hello, world!
    }

    private static void load(A[] aArray2) {
        aArray2[0] = new A();
    }

}

class A {
   public String toString() {
       return "Hello, world!";
   }
}

A: You could just have:
public static void main(String[] args) {
    A a = load();
}

private static A load() {
    return new A();
}

A: No you can't.
In java everything is passed as value not as reference.

A: I came out with this. Perfectly satisfied my need and looks nice.
class A {

    private A reference;

    private String name;

    public A() {
        reference = this;
    }

    public void setReference(A ref) {
        reference = ref;
    }

    public void setName(String name) {
        reference.name = name;
    }

    public String getName() {
        return reference.name;
    }

}


text:
Q: Why do we have $\Vert y_n\Vert^2=\langle x;y_n\rangle$ I can't see why the following equalities are valid:

Let $X$ be an inner product space with an othonormal system $e_n, n\in\mathbb{N}$ and $x\in X$.
Define $y_n=\sum_{i=1}^n\langle x;e_i\rangle e_i$, in wich case $$\underline{\Vert y_n\Vert^2=\langle x;y_n\rangle=\langle y_n;x\rangle }=\sum_{i=1}^n\vert\langle x;e_i\rangle\vert^2$$

I get the last part, however I don't see the underlined  part.

A: $$ \langle y_n;y_n \rangle = \langle \sum_{i=1}^n\langle x;e_i \rangle e_i,\sum_{j=1}^n\langle x;e_j \rangle e_j\rangle
=\sum_{i=1}^n\sum_{j=1}^n\langle x;e_i \rangle\overline{\langle x;e_j \rangle} \underbrace{\langle e_i;e_j \rangle}_{=\delta_{i,j}}
= \sum_{k=1}^n \langle x;e_k\rangle\overline{\langle x;e_k\rangle}
= \langle x; \sum_{k=1}^n \langle x;e_k\rangle e_k\rangle
= \langle x;y_n\rangle$$
where I used the fact that the basis $e_1,\ldots,e_n$ is orthonormal and thus $\langle e_i;e_j\rangle = \delta_{i,j}$ where $\delta_{i,j}$ is the Kronecker delta. Finally since $\| y_n\|$ is real, it holds $$\langle x;y_n\rangle=\| y_n\|= \overline{\| y_n\|} = \overline{\langle x;y_n\rangle} = \langle y_n; x\rangle.$$


text:
Q: ASP.NET MVC Value cannot be null Parameter name: httpContext I have downloaded Storefront ASP.NET MVC application. When I try to run the application, I get the following exception:

ArgumentNullException - Value cannot be null. Parameter name:
  httpContext

A: This is sort of odd.  The HttpContext houses things such as request and response, cache, cookies, etc.  If you are running the project from the perspective of a web site it generally would not be null.  Is this error coming up when referencing it in the global?  It is possible that you are trying to get to it before it exists in the requests life cycle.  Can you post more of the error?

A: Make sure you're getting the latest source code Kona. PersonalizationController isn't part of the current codebase.


text:
Q: In the code::blocks compiler for linux, how can one add compilation flags like '-lrt' or '-lboost_thread'? Debugging in gdb is not convenient for me so I enjoy the nice debugging interface that code::blocks offers. Now that I have moved my project into an area where those flags are required (the ones in the title, of course), I find that I can't compile on code::blocks anymore :/.

A: Hi everyone I figured out how to add the -lrt. Since -lrt is passed to the linker and not the compiler you can go to Settings->Compiler and Debugger->linker options then press add and after doing a "locate lrt" I found this cute library "/usr/lib/libaticalrt.so." I added the library in the linker options and now those errors disappeared... Time to try boost!
EDIT: Boost was solved in a similar manner. The library represented by lboost_thread is libboost_thread.so. A locate found it at: "/usr/lib/libboost_thread.so." Adding it in the linker options solved the problem :D


text:
Q: Three.js detect click on an object with Raycaster don't work I tried to detect a click on a Three.js object with a raycaster but not any collision is detected.
I use Angular an here is my code :
@Component({
  selector: 'app-viewer-3d',
  templateUrl: './viewer3d.component.html',
  styleUrls: ['./viewer3d.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Viewer3dComponent implements OnInit, DoCheck {
  pickPosition = {x: 0, y: 0};
  scene = new THREE.Scene();
  pickedObject;
  raycaster = new THREE.Raycaster();

  ngDoCheck() {
    this.cameraState.emit(JSON.stringify(this.camera.matrix.toArray()));
    console.log(this.pickPosition);
    this.raycaster.setFromCamera(this.pickPosition, this.camera);
    const intersectedObjects = this.raycaster.intersectObjects(this.scene.children);
    if (intersectedObjects.length) {
      if (this.pickedObject !== intersectedObjects[0].object) {
        // console.log(this.pickedObject);
        this.pickedObject = intersectedObjects[0].object;
      }
      console.log(this.pickedObject);
    } else {
      this.pickedObject = null;
      console.log('NULL');
    }
  }

  @HostListener('window:mouseout')
  @HostListener('window:mouseleave')
  clearPickPosition() {
    this.pickPosition.x = -100000;
    this.pickPosition.y = -100000;
    // console.log(this.pickPosition);
  }

  @HostListener('window:mousemove', ['$event'])
  setPickPosition(event) {
    const pos = this.getCanvasRelativePosition(event);
    this.pickPosition.x = (pos.x / this.canvas.width) * 2 - 1;
    this.pickPosition.y = (pos.y / this.canvas.height) * -2 + 1;  // note we flip Y
    // console.log(this.pickPosition);
  }

  getCanvasRelativePosition(event) {
    const rect = this.canvas.getBoundingClientRect();
    return {
      x: (event.clientX - rect.left) * this.canvas.width / rect.width,
      y: (event.clientY - rect.top) * this.canvas.height / rect.height,
    };
  }
}

In my console, when I move my mouse, y and x go between -1 and 1 but it print always NULL. So, intersectedObjects.length  = 0.
Do you have any idea ?
Thank's in advance

A: raycaster.intersectObjects( this.scene.children, true );


text:
Q: How to access vuejs component properties from using cypress? Hi I want to access vuejs component properties from using cypress because am not able to locate elements uniquely form html/css.
our application UI developed in Vuejs so i tried to access vue component form dom object with cypress
for ex on console,
1.var a=document.querySelector('#action_items_list > div.fill-height.col > div > div > div.fill-height > div:nth-child(1)')
2.a.vue.props.kitItemId
now how i implement this thing in cypress to access the data for a component and get() will not take this as an argument coz it requried a DOM element to perform an action.

A: Try this:
cy.get('#action_items_list > div.fill-height.col > div > div > div.fill-height > div:nth-child(1)')
    .then($item => {
        console.log($item[0].__vue__.kitItemId)
    })


text:
Q: redirect cin to a string in c++
Possible Duplicate:
Redirect cin to a string

I saw this post on how to redirect cout to a string. But how to redirect the cin to a string, just like redirecting cin to a file using freopen, so that when I do cin>>a_int;, I will get an int from the string? Can I do similarly with setbuf (stdin , buffer);

A: I'm answering this with your end goal in mind...

when I do cin>>a_int;, I will get an int from the string?

You can do that without redirecting cin by using std::istringstream
Usage would look like this.
#include <sstream>

std::istringstream is(your_string);
is >> a_int;


text:
Q: Not getting different colors on Folium package I am trying to plot some points on the map, where the points are marked based on geo-coordinates and each point belongs to a category.
I am trying to set the color of the categories from the color array, and even converted that into a function, yet it is displaying all the categories in one color, as in the image:

Here's the code mentioned below. I am not exactly sure where am I going wrong, since this is from the documentation of Folium.
The variable 'c' here, is actually coming from the column C in dataframe, which has the number of the segment.
mapPlot = folium.Map(location=[latitude, longitude], zoom_start=2)

colors = [
    'red',
    'blue',
    'gray',
    'orange',
    'beige',
    'green',
    'purple',
    'cadetblue',
    'black',
    'pink'
]

def colorCall(val):
  val = int(val)
  return colors[val]

for lon, lat, c in zip(df1['long'], df1['lat'], df1['C']):
    folium.CircleMarker(
        [lat, lon],
        radius=2,

        #fill_color=colors[int(c)],
        fill_color = colorCall(c),
        fill=True,
        fill_opacity=0.7
        ).add_to(mapPlot)

mapPlot

A: What you are seeing as blue is the outline of the circle. Set color=False:
        ...
        fill_color = colorCall(c),
        fill=True,
        color=False,  # outline color
        ...

color=True:

color=False:


text:
Q: Is this partial derivative evaluated correctly? Let $w=f(x,y)$, $x=3k$, $y=kh^2+2k$.
I got the solution that $\dfrac{\partial^2 w}{\partial k\partial h} = \dfrac{\partial}{\partial h}(3\dfrac{\partial w}{\partial x} + (h^2+2)\dfrac{\partial w}{\partial y}) = 0 + 2h \dfrac{\partial w}{\partial y}$
Is there an alternative solution?
Is the expression below evaluated correctly?
$\dfrac{\partial^2 w}{\partial k\partial h}=\left(2hk\dfrac{\partial w}{\partial y}\right)\left[3\dfrac{\partial w}{\partial x}+(h^2+2)\dfrac{\partial w}{\partial y}\right]$

A: My solution is:
$$\frac{\partial w}{\partial k} \enspace = \enspace 3\frac{\partial w}{\partial x} + (h^2+2)\frac{\partial w}{\partial y} $$
And therefore,
$$ \frac{\partial^2 w}{\partial h \, \partial k} \enspace = \enspace 6hk \, \frac{\partial^2 w}{\partial x \,\partial y} + 2h \frac{\partial w}{\partial y} + 2kh(h^2+2) \frac{\partial^2 w}{\partial y^2}$$
Note that the derivative of $w$ with respect to $x$, i.e. $\tfrac{\partial w}{\partial x}$, can still be dependent on $y$. In other words $\tfrac{\partial w}{\partial x} = \tfrac{\partial w}{\partial x}(x,y)$ and thus $\tfrac{\partial}{\partial y} \tfrac{\partial w}{\partial x} = 0$ is NOT true in general. Note furthermore, that in general
$$ \frac{\partial w}{\partial y} \frac{\partial w}{\partial y} \enspace = \enspace \Big( \frac{\partial w}{\partial y} \Big)^2 \enspace \neq \enspace \frac{\partial^2 w}{\partial y^2}$$
One can always check if his solution is correct by calculating the inverse order, i.e. calculating $\tfrac{\partial^2 w}{\partial k \, \partial h}$ instead of $\tfrac{\partial w^2}{\partial h \, \partial k}$. The solutions should coincide.


text:
Q: Is physics rigorous in the mathematical sense? I am a student studying Mathematics with no prior knowledge of Physics whatsoever except for very simple equations. I would like to ask, due to my experience with Mathematics:
Is there a set of axioms to which it adheres? In Mathematics, we have given sets of axioms, and we build up equations from these sets.
How does one come up with seemingly simple equations that describe physical processes in nature? I mean, it's not like you can see an apple falling and intuitively come up with an equation for motion... Is there something to build up hypotheses from, and how are they proven, if the only way of verifying the truth is to do it experimentally? Is Physics rigorous?

A: Some parts of physics are rigorous in the sense of mathematics - i.e. they are treated as mathematics, with physically-motivated entities. And it is not that uncommon that for some papers to make it rigorously, explicitly stating assumptions and proving things.
However, most of the time physics in not mathematically rigorous. It stems from a few things:

*

*Physics, typically, work the other way around than mathematics. That is, knowing some effects you try to figure out assumptions so the effects can be explained.

*Physics is related to the real world. And many times it is tricky to relate a pure mathematical concept to (reasonably) objectively measurable quantities.

*In physics, there is not much difference if you fail at predicting because of error in mathematics, or using unphysical assumptions.

*Most of things in physics started as a hand waving arguments, which were mathematically dubious, but "they worked in most cases". In that way it was possible to explain or predict many phenomena. Their mathematical grounding often went later (a few years, decades or... is still an open problem); and more than often, in a utterly unpractical form for any physical calculations.
Think of things like Lebesgue integral (still to get the actual numerical value you need to do summation or Riemann integration), delta Dirac as a distribution (for physical calculations it is treated as "narrow enough" function), formalization of path integrals (well, not suitable for calculations), ...

How does one come up with seemingly simple equations that describe physical processes in nature?

It is a big question.
There are some answer in the spirit of emergency like:

"Physics is this part of the reality that is easily described with mathematics."

Or even more cynically (it's more-or-less a quotation, but I've forgotten the author):

"Physics is this part of the reality that can be approximated as coupled harmonic oscillators."

Also, it is highly recommendable to read a classical text on that issue: Eugene Wigner, The Unreasonable Effectiveness of Mathematics in the Natural Sciences.

A: No, physics is not rigorous in the sense of mathematics. There are standards of rigor for experiments, but that is a different kind of thing entirely. That is not to say that physicists just wave their hands in their arguments [only sometimes ;) ], but rather that it does not come even close to a formal axiomatized foundation like in mathematics.
Here's an excerpt from R.Feynman's lecture The Relation of Mathematics and Physics, available on youtube, which is also present in his book, Character of Physical Law (Ch. 2):

There are two kinds of ways of looking at mathematics, which for the purposes of this lecture, I will call the the Babylonian tradition and the Greek tradition. In Babylonian schools in mathematics, the student would learn something by doing a large number of examples until he caught on to the general rule. Also, a large amount of geometry was known... and some degree of argument was available to go from one thing to another. ... But Euclid discovered that there was a way in which all the theorems of geometry could be ordered from a set of axioms that were particularly simple... The Babylonian attitude... is that you have to know all the various theorems and many of the connections in between, but you never really realized that it could all come up from a bunch of axioms... [E]ven in mathematics, you can start in different places. ... The mathematical tradition of today is to start with some particular ones which are chosen by some kind of convention to be axioms and then to build up the structure from there. ... The method of starting from axioms is not efficient in obtaining the theorems. ... In physics we need the Babylonian methods, and not the Euclidean or Greek method.

The rest of the lecture is also interesting and I recommend it. He goes on (with an example of deriving conservation of angular momentum from Newton's law of gravitation and having it generalized):

We can deduce (often) from one part of physics, like the law of gravitation, a principle which turns out to be much more valid than the derivation. This doesn't happen in mathematics, that the theorems come out in places where they're not supposed to be.

A: Well, you generally have a few fundamental equations, and you try to build a theory upon them. For example, one can consider the gravity equation $F=\frac{Gm_1m_2}{r^2}$ to be a fundamental. How was it derived? It wasn't -- it was experimentally determined to a known accuracy. Newton's laws can be considered to be "axioms" as well, though the Lagrangian formulism of Physics is more pleasing to look at axiomatically (some very simple statements involving energy are taken as axioms, and the rest is pretty much mathematically derived).
More modern theories like the Standard Model assume entities behave according to some mathematical relation -- again, this is your axiom (I'm not too familiar with SM, so I'm not too clear about this).
In the end, the only way to check is via experiments. It's technically the same with mathematics-- you "test" your axioms against your logical facilities. The axioms are pretty simple and sometimes silly at first glance, so you never know that you're doing this. On the other hand, in Physics, the axioms are more complex and don't sound as "silly". The experiments required to verify/come up with these are correspondingly more complex, and they don't give a completely definite result -- we can only say that "equation X is valid to Y accuracy" or something like that.
If we call the fundamentals "axioms", then yes, Physics is rigorous. But these axioms are on pretty shaky ground themselves. For the past century we've been trying to tweak these axioms/postulates so that we get a system consistent with the real world.
Another way to look at it is that we just port over all axioms from Mathematics, postulate a few things (what a force is, what momentum is, etc), and everything else is a conjecture that's been verified to a certain degree. Like Goldbach's conjecture.
I think that the second interpretation is the one commonly accepted -- I've never seen anything labelled as "axioms of physics", though certain things like special relativity can be derived in an axiomatic fashion (start with space and time, then go on)

A: Physics is usually not rigorous. But there is a branch of physics, called mathematical physics, in which physics is treated with full mathematical rigor.
There everything begins with formally stated assumptions (axioms) from which everything else is rigorously deduced.
In particular, there are fully rigorous treatments of phenomenological thermodynamics (see, e.g., my paper http://arnold-neumaier.at/ms/phenTherm.pdf), of classical mechanics, of fluid mechanics, and of quantum mechanics.
A possible set of axioms for quantum mechanics is given in my ''Postulates for the formal core of quantum mechanics'' from Chapter A4: The interpretation of quantum mechanics of my theoretical physics FAQ at
http://arnold-neumaier.at/physfaq/physics-faq.html
This chapter also contains a discussion of ''What is the meaning of axioms for physics?''. See also ''Why bother about rigor in physics?'' in Chapter C2: Some philosophy of physics.

A: Not, always .. many times they used un mathematical models like 'dimensional regularization' or use some 'curve fitting' for some properties in several branches of physics or use 'conjectures' so the things fit

A: Since you are a student of mathematics with little knowledge of physics, I strongly urge you to take a few courses in modern physics before you finish your mathematics education (General Relativity and Quantum Mechanics the very least). This is a must if you are specializing in geometry/topology.
Having said that, the "axioms" of the two disciplines are not the same kind, and therefore the "rigor" of proofs is different.
Physical "axioms" are those that are invariant in every experiment. E.g., the "axiom" of conservation of energy; or that the speed of light cannot be exceeded, and so on. Newton's laws were once "axioms" but they had to be modified in extreme conditions. But that does not mean Newton's laws are false: they are still true to the world we normally experience.
Mathematical axioms can be "abstract" but not based on any experiment: parallel lines do not intersect is an ancient axiom. Whether that is true or not in our universe is not important to a mathematician.

A: First of all, whilst it is usually said that mathematics is a deductive science where deductions proceed from a given set of axioms, a little thought shows that this can't be completely true. For example, where do the axioms come from? We don't deduce these, they are rather induced from a set of examples. Hence, mathematics like all the other sciences is a mixture of induction and deduction.
This is just as true today as in Euclid day. For example, rigourously speaking, there is no field with one element yet people are looking for such a field. This is because they have a set of examples which has a pattern that would make sense if such a field existed. This means of course that the notion of a field has to be expanded and one of the possible candidates is a sheaf of multiplicative monoids a la Grothendieck.
Thus we see that there isn't such a clear cut division between mathematics and physics as far as methodology goes: there are experiments, induction and deduction.
Now, as far as rigorous physics goes, there is mathematical physics which riffs of a question that Hilbert suggested: to axiomatise physics. There are rigorous developments of classical field theory and of classical mechanics, this includes relativity and GR. These work in a similar way to mathematics, that is by deduction from a small set of accepted axioms. Likewise, there is an axiomatic development of quantum mechanics. Whilst for QFT, this is an ongoing research topic with AQFT (algebraic QFT), FQFT (functorial QFT), LCQFT (locally covariant QFT),  the Osterwalder-Schrader and Wightman axiomatics being amongst the contenders.

A: This answer of mine is relevant to this question also:
Ever since the time of Newton physics is about observing nature, quantifying observations with measurements and finding a mathematical model that not only describes/maps the measurements but, most important, it is predictive. To attain this, physics uses a rigorous self-consistent mathematical model, imposing extra postulates as axioms to relate the connection of measurements to the mathematics, thus picking a subset of the mathematical solutions for the model.
The mathematics is self-consistent and rigorous by the construction of a mathematical model. Its usefulness in physics is that it can predict new phenomena to be measured.
It is the demand for self-consistency that allows for falsification of a proposed mathematical model, by its predicting  numbers found to be false.
The consistent euclidean model of flat earth is falsified on the globe of the earth, for example. This lead to spherical geometry as the model of the globe.
The whole research effort of validating the standard model at LHC, is in the hope that it will be falsified and open a window for new theories.
In this sense physics as a discipline is as rigorous as mathematics.
The processes of designing experiments and getting real numbers to test the models introduces errors and statistical distributions,  which define the accuracy of the "rigor" expected when testing a model, so in this sense  physics is not absolutely rigorous.

A: While I do not necessarily disagree with most of the points addressed in the other answers here, I do not think they actually answer the OP's question, which was clearly stated in their comment to @Manishearth's answer:

Hi. I don't mind taking the gravity equation as an axiom. What I want to ask (perhaps different from what the OP would like to ask) is: Suppose we assume certain axioms to describe the universe and use them to derive a statement P. Is the derivation of P from the axioms rigorous ? This is like the question: Is physics axiomatic ?

The answer to this question requires a nuance that I think is not being apprecaited in the other posted answers. Namely, what do we actually mean by "axioms" and "is the derivation of P from the axioms 'rigorous'$\,$"? These notions THEMSELVES were being developed in their modern form in the 20th century, with the rise of Hilbert's (among others) axiomatic framework, and exploded until today (Goedel's theorems, Zermelo-Frankel set theory, modern topology and graph theory, matroid theory, etc....). At the same time in the 20th century, physics was utilizing these new sophisticated mathematical machineries: for example, various approaches to quantum theory emerged, which Dirac showed to be equivalent algebraically, and the theory of general relativity used tensor theory, differential geometry, and Minkowski's spacetime formulation.
This historical context is important, I think, because it gives better meaning to the comparison between mathematics and physics. The two work together to advance each other - pure mathematicians probably won't agree, but the history of progress in math proves otherwise.
Therefore, I would say that YES theoretical physics - the part of "physics" where people build conceptual models using math - is axiomatic sometimes, not always, but it has been like this since Newton (there are possibly others that preceded him, but thats a question for History of S&M SE).
Newton's Principia is axiomatic and mathematically rigorous. He begins from well defined axioms (e.g., law of universal gravitation and laws of motion) and derives theorems and lemmas using calculus. For example, he showed that Kepler's heuristic rules of the solar bodies (which were built on Copernicus') are consequences of his laws. Here, Newton's laws act as the "axioms" of the theory.
But sometimes "axioms" in physical models are not called laws, and instead are principles, or even postulates. For example, Einstein postulated the "axioms" of special relativity, and uncovered a very enlightening model of reality. He then extended the special theory to the general theory with the equivalence principle, which is the conceptual core of general relativistic physics.
The laws of quantum mechanics are "axioms" in the exact sense that they are assumed to be true and then one deduces logical conclusions from them (i.e. theorems, etc...). As you say, if P is the proposition that "an electron has spin state $|\psi\rangle$" then you can use the laws of quantum mechanics to derive all kinds of other logical implications (i.e. theorems).
As @anna v stated, the axiomatic approach found use in physics mainly due to its ability to predict new phenomena, as well as generalizing already known information. Newton's laws were used by many in the centuries following him to predict the existence of many moons and planets. This predictive utility is easily seen in modern theories such as relativity and quantum theory: e.g., theory of general relativity's predictions of gravitational radiation, gravitational lensing, light bending, black holes, etc...., and Dirac's prediction of antimatter, the prediction of other fundamental particles, etc....
I think it's worth responding to the Feynman quote by @Stan Liou. This quote is being taken out of context, since Feynman is talking about the ways he views $mathematics$, which do not necessarily apply to physics. Indeed math and physics are related, but that does not mean they are classifiable identically! As others have noted here, physics is driven by empirical consensus, and people who make theories of physics try to stay ahead of the empirical/experimental progress by speculating and sometimes by generalizing. IT is in this generalizing vein that physics is axiomatic. But, lots of iterative, provisional progress is usually required in a field of physics before reliable generalizations are available to make axiomatic theories. For example, renormalization and regularization were ad-hoc fixes to issues in physics theories, but over time they have been made mathematically rigorous and there exist axiomatic approaches to these now, too. I hope my answer helps to clarify the nuances in the, seemingly simple, question "is physics axiomatic and rigorous?"

A: Pythagoras theorem was true once upon a time when the great philosopher discovered it. It is still true, and will always be, as far as Euclidean geometry is concerned. The laws of motion, too, were considered perfectly valid in the times of Newton. But, now we know that Relativity is far more general, and in a sense, much more truthful. So the basic difference lies here: mathematics, an abstract science built upon axioms laid down by former mathematicians, seems to describe reality in an elegant and all the more rigorous way; whereas, physics, a natural science built upon the axioms laid down by God himself, is itself a manifestation of the reality we live in. The difference lies in that, one is abstract, and the other real; but only scientists can understand why we cannot dispense with either of them, both being fundamental to the understanding of the world we live in.


text:
Q: How to collect variables from a tree formula The question title might be poorly expressed, so I'm sorry for that. I am representing a propositional logic formula as a tree in Java, like so:
abstract class Formula { }

final class AndFormula extends Formula {
  private Formula leftChild, rightChild;

  public AndFormula(Formula leftChild, Formula rightChild) {
    this.leftChild = leftChild;
    this.rightChild = rightChild;
  }

  // add some getters...

}

final class OrFormula extends Formula {
  private Formula leftChild, rightChild;

  public OrFormula(Formula leftChild, Formula rightChild) {
    this.leftChild = leftChild;
    this.rightChild = rightChild;
  }

  // add some getters...

}

final class AtomicFormula extends Formula {
  private String name;

  public AtomicFormula(String name) {
    this.name = name;
  }

  // add some getters...

}

Now let's say I want to collect the names of atomic formulas in a very particular way: I only want names of atomic formulas which never appear on the right hand side of an OrFormula. I have the following:
public static Set<String> specialVars(Formula f) {

  Set<String> ans = new HashSet<String>();

  if( f.getClass() == AndFormula.class ) {
    // Recursively add all special vars from the left child:
    ans.addAll( specialsVar( f.leftChild ) );

    // Recursively add all special vars from the right child:
    ans.addAll( specialsVar( f.rightChild ) );
  } else if( f.getClass() == OrFormula.class ) {
    // Recursively add all special vars from the left child:
    ans.addAll( specialsVar( f.leftChild ) );

    // Don't add anything from the right child!
  } else if( f.getClass() === AtomicFormula.class ) {
    // The base case:
    ans.add( f.getName() );
  }

  return ans;
}

This code seems to work, so my question is: is this idiomatic Java? If not, what would be the idiomatic way to write this code? Is there any unexpected behaviour I should be aware of?
Thanks!


text:
Q: Uniform Cost Search in Fully Connected Weighed Graph with a Specified Number Of Customers to Visit The problem: you are a salesman. You have customers in an area. Also, you have office S as a starting point and office F as the target point. Before you arrive at the target point you need to visit a specified number of customers. You need to find an optimal solution with the least distance you walk. To do that you will use uniform cost search.
Input Grid is that:

In this grid, you gave each node a coordinate starting from left top point as (0,0). Then you create a fully connected graph because you can go to any node from any node. As you create the graph, you also calculate their manhattan distance and add it to the edges.
I used this approach when implementing my UCS algorithm : Uniform COst Search
Here is my implementation
def ucs(graph, node):
    global number_of_steps
    global nodes
    global count
    global opened
    global closed

    resPaths = []

    while True:
        if len(opened) == 0:
            return resPaths #C6 PARENTS STAY ONE

        if getFromOpened('F') is not None:
            newpaths = paths(getFromOpened('F'))
            resPaths += newpaths

        selected_node = min(opened)

        selected_node.visitedNumber += 1

        opened.remove(selected_node)
        if not InClosed(selected_node):
            closed.append(selected_node)
        else:
            old_node = getFromClosed(selected_node.type)
            closed.remove(old_node)
            closed.append(selected_node)

        new_nodes = extendNode(selected_node) #parent meselesi çözülmeli

        if len(new_nodes) > 0:
            for new_node in new_nodes:
                oldValue = new_node.value
                new_node.value = calculateDistance(selected_node, new_node)
                if(new_node.type == 'F' and InOpened(new_node)):
                   old_node = getFromOpened(new_node.type)
                   opened.remove(old_node)
                   new_node.addParent(old_node.parent)
                   opened.append(new_node)
                elif not InClosed(new_node) and  not InOpened(new_node): ## if not in the lists
                    opened.append(new_node)
                    continue
                elif InOpened(new_node):  # if reexplored
                    old_node = getFromOpened(new_node.type)
                    if new_node.value < old_node.value:
                        opened.remove(old_node)
                        new_node.addParent(old_node.parent)
                        new_node.visitedNumber = old_node.visitedNumber
                        opened.append(new_node)
                    else:
                        old_node.addParent(new_node.parent) #it solved it almost
                elif InClosed(new_node): #THIS IS WHERE THINGS GET MESSY
                    old_node = getFromClosed(new_node.type)
                    if old_node.visitedNumber < 4:#minCustomerNo:
                        new_node.addParent(old_node.parent)
                        new_node.visitedNumber = old_node.visitedNumber
                        opened.append(new_node)
                        closed.remove(old_node)

The problem here is that for the input :
{'min': 7,'env': [
'....C1...',
'.F......',
'.....C2..',
'.......C3',
'........',
'C4.......',
'.C5......',
'C6...S.C7.']}

The true answer is that:
[[7, 4], [6, 1], [5, 0], [7, 0], [7, 6], [3, 7], [2, 5], [0, 4], [1, 1]]
S,C4,C3,C5,C6,C2,C1,C0,F

What I found is that:
[7, 4],[7, 6], [6, 1], [5, 0], [7, 0], [3, 7], [2, 5], [0, 4],[1, 1]
S,C6,C4,C3,C5,C2,C1,C0,F

As you can see this is the answer I found before I added the InClosed(new_node) check at the end of my implementation.
Here is the real problem
After we start from the S, the closest is C6. In the second pass, it is chosen and it is thrown to the closed array which is like the visited arrays. But since the graph is fully connected, in the third pass when C4 is selected, I also need to visit C6 again. But it is in the closed list. So the real answer is never created because in the true answer C6 is in the 5th order even though it is visited first.
First I tried putting it back from closed to opened again but it creates an infinite loop.
Second I tried adding an attribute 'visitedNumber' to the node class. So I can limit the number of times it is put back to opened array. The limit should be the minimum number of customers to visit because it is the depth we need. When I tried it with minCustomerNo = 2, everything fine and gives the correct solution. But as the number grows it started to be a program never ends.
So what should I do exactly to both visit nodes again but also create a visited system?

A: Your answer is just as good as the "true answer" -- same cost and same customers visited, so no problem there.
Your program is not correct, though, because the optimal solution won't always reach every customer by the shortest path to that customer.
You should be doing UCS on a much larger implicit graph, where each node captures not just where you are, but also which customers you've already visited.


text:
Q: Navigate & finish multiple instances of same activity on button click This one is weird. I'm implementing breadcrumb navigation on a older app and I'm not at the point where it's ready to refactor the views. Unfortunately every new navigation opens a new activity and sometimes the new instances of the same activity. So my breadcrumb navigations basically look like this:
Activity A > Activity B > Activity C > Activity C > Activity C > Activity C > Activity D
So if I'm on Activity C and I need to go back to Activity B I can just set the Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP for the intent and navigate back no problem. But if I need to navigation from the 4 instance of Activity C to the 2nd instance of Activity C I'm not able to use any intent flags to make that happen. My app is already making use of the back button so I cannot override that to utilize here. Does anyone have any ideas as to navigation among the multiple instance of Activity C?
Fortunately all these app do inherit from the same parent app which extends FragmentActivity if that is helpful.

A: To go back one item in your breadcrumb you don't have to use the BACK button, you can just call finish(), which will finish the current Activity and go back to the previous one in the stack.
To go back to a specific Activity, you can use startActivity() with flags Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_SINGLE_TOP, as you have already indicated in your question.
Anything else is not possible. See my answer to a related question here:
https://stackoverflow.com/a/39104837/769265


text:
Q: using quasiquotation in functions with formula interface I want to write a custom function that can take bare and "string" inputs, and can handle both functions with and without the formula interface.
custom function example
# setup
set.seed(123)
library(tidyverse)

# custom function
foo <- function(data, x, y) {
  # function without formula
  print(table(data %>% dplyr::pull({{ x }}), data %>% dplyr::pull({{ y }})))

  # function with formula
  print(
    broom::tidy(stats::t.test(
      formula = rlang::new_formula({{ rlang::ensym(y) }}, {{ rlang::ensym(x) }}),
      data = data
    ))
  )
}

bare
works for both functions with and without formula interface
foo(mtcars, am, cyl)
#>
#>      4  6  8
#>   0  3  4 12
#>   1  8  3  2

#> # A tibble: 1 x 10
#>   estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high
#>      <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl>
#> 1     1.87      6.95      5.08      3.35 0.00246      25.9    0.724      3.02
#> # ... with 2 more variables: method <chr>, alternative <chr>

string
works for both functions with and without formula interface
foo(mtcars, "am", "cyl")
#>
#>      4  6  8
#>   0  3  4 12
#>   1  8  3  2

#> # A tibble: 1 x 10
#>   estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high
#>      <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl>
#> 1     1.87      6.95      5.08      3.35 0.00246      25.9    0.724      3.02
#> # ... with 2 more variables: method <chr>, alternative <chr>

as colnames
works only for functions without the formula interface
foo(mtcars, colnames(mtcars)[9], colnames(mtcars)[2])
#>
#>      4  6  8
#>   0  3  4 12
#>   1  8  3  2

#> Error: Only strings can be converted to symbols
#> Backtrace:
#>     x
#>  1. \-global::foo(mtcars, colnames(mtcars)[9], colnames(mtcars)[2])
#>  2.   +-base::print(...)
#>  3.   +-broom::tidy(...)
#>  4.   +-stats::t.test(...)
#>  5.   +-rlang::new_formula(...)
#>  6.   \-rlang::ensym(y)

How can I modify the original function so that it will work with all the above-mentioned ways of entering the inputs and for both kinds of functions used?

A: The nice philosophy of rlang is that you get to control when you want values to be evaluated via the !! and {{}} operators. You seem to want to make a function that takes strings, symbols, and (possibly evaluated) expressions all in the same parameter. Using symbols or bare strings is actually easy with ensym but also wanting to allow for code like colnames(mtcars)[9] that has to be evaulated before returning a string is the problem. This potentially can be quite confusing. For example, what's the behavior you expect when you run the following?
am <- 'disp'
cyl <- 'gear'
foo(mtcars, am, cyl)

You could write a helper function if you want to assume all "calls" should be evaluated but symbols and literals should not. Here's a "cleaner" function
clean_quo <- function(x) {
  if (rlang::quo_is_call(x)) {
    x <- rlang::eval_tidy(x)
  } else if (!rlang::quo_is_symbolic(x)) {
    x <- rlang::quo_get_expr(x)
  }
  if (is.character(x)) x <- rlang::sym(x)
  if (!rlang::is_quosure(x)) x <- rlang::new_quosure(x)
  x
}

and you could use that in your function with
foo <- function(data, x, y) {
  x <- clean_quo(rlang::enquo(x))
  y <- clean_quo(rlang::enquo(y))

  # function without formula
  print(table(data %>% dplyr::pull(!!x), data %>% dplyr::pull(!!y)))

  # function with formula
  print(
    broom::tidy(stats::t.test(
      formula = rlang::new_formula(rlang::quo_get_expr(y), rlang::quo_get_expr(x)),
      data = data
    ))
  )
}

Doing so will allow all these to return the same values
foo(mtcars, am, cyl)
foo(mtcars, "am", "cyl")
foo(mtcars, colnames(mtcars)[9], colnames(mtcars)[2])

But you are probably just delaying possible other problems. I would not recommend over-interpreting user intentions with this kind of code. That's why it's better to explicitly allow them to un-escape themselves. Perhaps provide two different versions of the function that can be used with parameter that require evaluation and those that do not.

A: I have to agree with @MrFlick and others about inherent ambiguity when mixing standard and non-standard evaluation. (I also pointed this out in your similar question from a while ago.)
However, one can argue that dplyr::select() works with symbols, strings and expressions of the form colnames(.)[.]. If you absolutely must have the same interface, then you can leverage tidyselect to resolve your inputs:
library( rlang )
library( tidyselect )

ttest <- function(data, x, y) {
  ## Identify locations of x and y in data, get column names as symbols
  s <- eval_select( expr(c({{x}},{{y}})), data ) %>% names %>% syms

  ## Use the corresponding symbols to build the formula by hand
  broom::tidy(stats::t.test(
    formula = new_formula( s[[2]], s[[1]] ),
    data = data
  ))
}

## All three now work
ttest( mtcars, am, cyl )
ttest( mtcars, "am", "cyl" )
ttest( mtcars, colnames(mtcars)[9], colnames(mtcars)[2] )


text:
Q: How to replace a stop function to loop Im using a supplied Flash template from the client that had a replay button but they wish for the ad banner to simply loop now, my problem is how do I do this with the below existing Action Script as the stop function is used to stop on frame 2 and carryout the fadein/out tweens...
stop();

import com.greensock.TweenNano;
import com.greensock.easing.*;

init();

function init():Void
{

    TweenNano.to(imgBG,.5,{_alpha:100,delay:0,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt1,.5,{_alpha:100,delay:1,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt2,.5,{_alpha:100,delay:2,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(txt2,.5,{_alpha:0,delay:5,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt3,.5,{_alpha:100,delay:6,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(txt3,.5,{_alpha:0,delay:9,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt4,.5,{_alpha:100,delay:10,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(txt4,.5,{_alpha:0,delay:15,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(hpLogoBlue,0,{_alpha:100,delay:0,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(ctaBtn,.5,{_alpha:100,delay:11,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(ctaBtn,.5,{_alpha:0,delay:15,ease:Quad.easeOut,overwrite:0});

}

ctaBtn.onRollOver = function():Void
{
    ctaBtn.gotoAndStop(2);
};
ctaBtn.onRollOut = function():Void
{
    ctaBtn.gotoAndStop(1);
};

A: I've added some new code that will reset the timeline to frame 1 after 15 seconds using a timer. See comments for explanation. Note that
I've also noticed that your return type 'Void' should be lowercase on the init() function. I've fixed it here as well.
stop();

import com.greensock.TweenNano;
import com.greensock.easing.*;

//make timer settings
timer = 0;
durationSecs = 15;

countup = function(){
    timer++;
    trace('rar');
    if(timer>=durationSecs){
        _root.gotoAndPlay(1);
        timer = 0;
        clearInterval( countupInterval );
        trace('clear');
    }
}

countupInterval = setInterval(countup,1000);

init();

function init():Void
{

    TweenNano.to(imgBG,.5,{_alpha:100,delay:0,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt1,.5,{_alpha:100,delay:1,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt2,.5,{_alpha:100,delay:2,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(txt2,.5,{_alpha:0,delay:5,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt3,.5,{_alpha:100,delay:6,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(txt3,.5,{_alpha:0,delay:9,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(txt4,.5,{_alpha:100,delay:10,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(txt4,.5,{_alpha:0,delay:15,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(hpLogoBlue,0,{_alpha:100,delay:0,ease:Quad.easeOut,overwrite:0});

    TweenNano.to(ctaBtn,.5,{_alpha:100,delay:11,ease:Quad.easeOut,overwrite:0});
    TweenNano.to(ctaBtn,.5,{_alpha:0,delay:15,ease:Quad.easeOut,overwrite:0});

};

ctaBtn.onRollOver = function():Void
{
    ctaBtn.gotoAndStop(2);
};
ctaBtn.onRollOut = function():Void
{
    ctaBtn.gotoAndStop(1);
};


text:
Q: How would one prove the existence of the following indefinite integral Find out whether or not the following integral exists
$$\int_{0}^{\infty}\frac{\sin(x)}{x(x+1)}dx$$
My idea was to split the integral into two
$$\int_{0}^{\infty}\frac{\sin(x)}{x(x+1)}dx = \int_{0}^{1}\frac{\sin(x)}{x(x+1)}dx + \int_{1}^{\infty}\frac{\sin(x)}{x(x+1)}dx$$
I'm pretty sure both integrals exist but I can't seem to find a way to prove this. Can someone please explain how one would argue.

A: Actually, it's much simpler to note that$$\bigl(\forall x\in[1,+\infty)\bigr):\left|\frac{\sin x}{x(x+1)}\right|\leqslant\frac1{x^2}.$$Note that there's no problem at $0$, since$$\lim_{x\to0}\frac{\sin x}{x(x+1)}=1.$$

A: Split in two

*

*near $0$: $\;\sin x\sim_0 x$, so
$$\frac{\sin x}{x(x+1)}\sim_0 \frac 1{x+1},$$
and as the latter is integrable on $[0,1]$ and they're positive functions, the former is too.

*near $\infty$
:
$$\biggl|\frac{\sin x}{x(x+1)}\biggr|=O\biggl(\frac 1{x^2}\biggr),$$

which is integrable on $[1,+\infty)$.