text:
Q: tough algebric problem? I wanted to know how can i prove that if

$xy+yz+zx=1$, then
$$ \frac{x}{1+x^2}+\frac{y}{1+y^2}+\frac{z}{1+z^2}
     = \frac{2}{\sqrt{(1+x^2)(1+y^2)(1+z^2)}}$$
I did let $x=\tan A$,  $y=\tan B$,   $z=\tan C$

given $xy+yz+zx =1$ we have $\tan A \tan B+ \tan B \tan C+\tan C \tan A=1$
$\tan C(\tan A+\tan B)=1-\tan A \tan B$, or $\tan(A+B)=\tan(\pi/2 -C)$ we have $A+B+C=\pi/2$.
what to do now?
Any help appreciated.
thanks.

A: HINT:
$$\frac x{1+x^2}=\frac {\tan A}{1+\tan^2A}=\frac{2\sin A\cos A}2=\frac{\sin2A}2$$
Now , $$\sin2A+\sin2B+\sin2C=2\sin(A+B)\cos(A-B)+2\sin C\cos C$$
$$=2\sin\left(\frac\pi2-C\right)\cos(A-B)+2\sin C\cos C$$
$$=2\cos C\{\cos(A-B)+\cos(A+B)\}$$ as $\sin C=\sin\{\frac\pi2-(A+B)\}=\cos(A+B)$
$$\implies \sin2A+\sin2B+\sin2C=2\cos C\cdot2\cos A\cos B$$
and  $$\frac1{\sqrt{1+x^2}}=\frac1{\sec A}=\cos A$$

A: The accepted answer by `lab bhattacharjee' is perfectly fine. For what it's worth, there's a nice geometric view that might enrich this nearly-4-year-old post a tiny bit.
The identity to be proven is, given $\alpha + \beta + \gamma = \frac{\pi}2$, $$ \frac12 \big( \sin 2\alpha + \sin 2\beta + \sin 2\gamma \big) = 2 \cos\alpha \cdot \cos\beta  \cdot\cos\gamma$$
Consider an acute triangle $\triangle MNP$ as shown in the figure, with its circumcenter denoted as point $O$. Without loss of generality, take the circumcircle as the unit circle. That is,
$$\text{diameter}~~ \overline{PP'} = 2 \qquad \text{radius}~~ \overline{OM} = \overline{ON} = \overline{OP} = 1$$
By definition, all angles are acute so that any one of them can be split into two parts, say, $\angle PMN = \alpha + \beta < \frac{\pi}2$, with a remaining complement $\gamma > 0$, as in $$\alpha + \beta + \gamma = \frac{\pi}2$$

The desired identity comes from calculating the area $\mathcal{A} \equiv |\triangle MNP|$ in two different ways:
$$\begin{align}
&\text{RHS}: & \mathcal{A} &= \frac12 \cdot \overline{MP} \cdot \overline{MN} \cdot \sin(\angle PMN ) \\
&\text{LHS}: & \mathcal{A} &= |\triangle OMP| + |\triangle ONM| +|\triangle OPN|
\end{align}$$
For the RHS, we have $$\overline{MP} = 2\cos\alpha \qquad \overline{MN} = 2\cos\beta$$ since point $O$ is the circumcenter (e.g. $\overline{MO} = 1$ and $\triangle MOP$ is an isosceles, $\overline{MP}$ is bisected by the height to point $O$). That is,
$$\begin{align}
&\text{RHS}: & \mathcal{A} &= \frac12 \cdot \overline{MP} \cdot \overline{MN} \cdot \sin(\angle PMN ) \\
&&  &= \frac12 \cdot 2\cos\alpha \cdot 2\cos\beta \cdot \sin(\alpha + \beta) \\
&& &= 2\cos\alpha \cdot \cos\beta \cdot \sin(\frac{\pi}2 - \gamma) \\
&& &= 2\cos\alpha \cdot \cos\beta \cdot\cos\gamma
\end{align}$$
Now, for the LHS we again apply the Law of Sines to each of the small triangles. For example,
$$\begin{align}
\triangle{NOP} &= \frac12 \cdot \overline{ON} \cdot \overline{OP} \cdot \sin(\angle NOP) \\
&= \frac12 \cdot 1 \cdot 1 \cdot \sin(\pi - \angle NOP') \\
&= \frac12 \sin(\pi - 2\gamma)
\end{align}$$
since $\angle NOP'$ is the central angle for the inscribed angle $\gamma$ (and $\triangle PMN$ is acute so $O$ is "inside"). Therefore, we have
$$\triangle{NOP} = \frac12 \sin 2\gamma \qquad \text{and similarly} \qquad \triangle{POM} = \frac12 \sin 2\alpha \quad \triangle{MON} = \frac12 \sin 2\beta$$
which sum to the LHS of the desired identity. Note how this proof (splitting a triangle into 3 inner ones) naturally exhibits the cyclic nature (3-fold symmetry) of the identity. $~~~~~$Q.E.D.
When the triangle is obtuse, the proof is similar: one of $\alpha, \beta, \gamma$ is negative, which corresponding 'inner' triangle becomes `outer', and its effective area is also negative). For the case where two of $\alpha, \beta, \gamma$ are negative, unfortunately the notion of a triangle breaks down (unless one considers projective geometry, I guess).
P.S.
I definitely have seen this triangle-splitting analysis before at various places, with respect to any general point and not just the circumcenter. The corresponding algebraic expression involves more than 3 angles.


text:
Q: Changing the Length of The Google Custom Search Snippet I am using Google Custom Search API for querying the web for specific text patterns. Hence, I'm basically interested in the 'snippet' of each returned result. The problem is, the current length of the 'snippet' field of the JSON result of any query is limited to 160 characters, and I sometimes need more context for the matched query than that. I was wondering if there is any way for extending the length of the snippet.
Thanks a lot

A: There is not. Google (and all other search engines) keep the size of snippets short for many reasons.
If you search query uses the double quotes signs ", and a URL is returned, fetch that URL and do your matching then.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I use JSP or servlet to generate HTML table? I need to dynamically generate html table and insert in the jsp page and would like to know the best way to do this. Theses are the options I am debating over:

*
*
Generate a string which contains html tags in Servlet and set in attribute to forward to the jsp page

*Create object which contains data to generate table and set in the attribute to forward to jsp page, jsp page will use tag library to generate the table

A: The latter. Servlets should not know or care about presentation logic. JSTL is usually enough to render the model from within the JSP, but if greater complexity is necessary, use a custom taglib to render the data.

A: The second option is the best one. A simple example:

<c:forEach items="${tableRows}" var="row">

      ${row.foo}
      ${row.bar}

</c:forEach>

The servlet should not be aware of HTML


text:
Q: Intent data not updated in activity while launched from Android push notification click I looked for a solution for my problem and couldn't find anything. My app is using GCM and some of the pushes that I send are wrong (sometimes the Intent's data is not updated, it's the same as the previous one).
I sent push notification using the following payload:
{
   "registration_ids" : ["dS9iBOAXlWc:APA9..."],
    "notification" : {
        "title" : "Hey",
        "body" : "This is the body"
    },
   "data" : {
       // my data
   }
}

The Notification is generated by the system when the Application is in the background and it is what I want. I process the data this way:
public class MyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

    @Override
    public void onActivityResumed(Activity activity) {

        Intent activityIntent = activity.getIntent();
        if (null != activityIntent && null != activityIntent.getExtras()) {
            // process activityIntent.getExtras();
        }
    }
}

Everything is working well except in one particular set of events:

*

*I killed the app and sent a push notification P1.

*I received a Notification with its data after I clicked on the Notification.

*I closed the app by pressing the home button.

*I sent myself another push notification P2.

*I clicked the received notification and here is my bug: the data is P1's data, not P2's.

How can I clear this Intent? and make the GCM Receiver update it?
Edit 1:
After more research, it really looks like a FCM or Android bug.
When my app is in the background and I click on a notification, a new Activity is created. But following the steps I described, the same activity is resumed:

After kill, on notification click:

11-16 10:10:35.434 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityCreated: com.zinfroy.intentstest.MainActivity@c14c125

11-16 10:10:35.517 24132-24132/com.zinfroy.intentstest D/MainActivity#onCreate: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

11-16 10:10:35.521 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityStarted: com.zinfroy.intentstest.MainActivity@c14c125
11-16 10:10:35.522 24132-24132/com.zinfroy.intentstest D/ActivityLifecycle#onStarted: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

11-16 10:10:35.525 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityResumed: com.zinfroy.intentstest.MainActivity@c14c125
11-16 10:10:35.525 24132-24132/com.zinfroy.intentstest D/ActivityLifecycle#onResumed: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

11-16 10:10:35.526 24132-24132/com.zinfroy.intentstest D/MainActivity#onResume: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

Click on Home button:

11-16 10:13:12.366 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityPaused: com.zinfroy.intentstest.MainActivity@c14c125

11-16 10:13:12.406 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivitySaveInstanceState: com.zinfroy.intentstest.MainActivity@c14c125
11-16 10:13:12.406 24132-24132/com.zinfroy.intentstest D/ActivityLifecycle#saveInstance: Key: com.google.firebase.analytics.screen_service Value: Bundle[{referrer_name=MainActivity, id=-7274484894154241509, name=null}]

11-16 10:13:12.408 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityStopped: com.zinfroy.intentstest.MainActivity@c14c125

Click on notification:

The is no onActivityCreated here!
11-16 10:13:22.342 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityStarted: com.zinfroy.intentstest.MainActivity@c14c125
11-16 10:13:22.342 24132-24132/com.zinfroy.intentstest D/ActivityLifecycle#onStarted: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

11-16 10:13:22.342 24132-24132/com.zinfroy.intentstest W/ActivityLifecycle: onActivityResumed: com.zinfroy.intentstest.MainActivity@c14c125
11-16 10:13:22.343 24132-24132/com.zinfroy.intentstest D/ActivityLifecycle#onResumed: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

11-16 10:13:22.344 24132-24132/com.zinfroy.intentstest D/MainActivity#onResume: Key: google.message_id Value: 0:1479287431249234%162dc7d9162dc7d9

So as the same Activity is resumed, the same Intent is read :/


text:
Q: What would the propType be of a JSX prop in react In react you can set the propType of the props that come into a component. For one of my props I want the value to either be null or a line of JSX. The React docs don't cover what propType should be used for JSX.
When testing this I found that it wouldn't throw errors when using the propTypes of object or element. When using another such as symbol I would get an error that said it was an object. If it was an object surely it should complain when it's an element.
What is the correct propType for JSX?

A: Try using this propType...
React.PropTypes.element

A: PropTypes.node or PropTypes.element can be used


text:
Q: jquery on click not working for dynamically added items I'm adding some code(!with js code included!) dynamically.

Problem that this click event works anythere I click in div.w and returns text of ALL div.w combined in one string without spaces (sometext1sometext2).
Sorry if I wrote something wrong. I'm bad in english.

A: Event delegation is wrong. You are using a jQuery collection
$('.r').on('click', $('.w'), function (e) {
                    ^^^^^^^

where it should be just a selector
$('.r').on('click', '.w', function (e) {
                    ^^^^

A: The selector has to be of type string. Look at the following:
$('.r').on('click', '.w', function (e) {

from documentation of on


text:
Q: What is your approach to debugging a transient problem I am working on a system that controls a label printer and occasionally the label printer will print the same label 2,3,...,10 times.  The error is transient, occurring once per 3000-4000 (once a month) or so labels.
I am adding tracing to a log file to see what commands are being sent to the printer and state of the printer (we have a state machine defining allowable commands). But since this is a transient problem that may tell me that we had an error, but not why we had the error so I can fix the problem.
I am also trying to get the print job files for the errant jobs so that I can emulate the job in my test environment.  Hopefully with these I can reliably make the error occur
I am curious how other might approach diagnosing this type of transient error.

A: Assuming you've already checked the default logs for exceptions ...
Explain the problem to your debug duck.
When it stares at you blankly, go into more detail. Tell the duck how it's supposed to work. If the stupid duck is still staring at you blankly, go into more detail about how it's supposed to work.
As you explain each component and interaction, ask the duck whether it can think of any reason (bad input, bad assumptions, protocol/communication mismatch, or errors therein) that could manifest the problem. If neither you or the duck can think of a reason the component could be misbehaving, move on (for now).
But at each step during your explanation, if you have even a faint suspicion of misbehavior, add some tests to your suite.

And when your coworkers ask who you're talking to, simply tell them, "Oh, I wasn't talking. The duck was."

A: When I hit a really painful real-world problem, sometimes it helps to escape to a land of make-believe where absurd assumptions can be made - and then work backwards from this more pleasant world.
So, let's remodel your problem as one that...well, sucks less to have to deal with.
Let's say you know that the next time this function runs and someone tries to print a label, you will get this duplicate behavior. However, this isn't a perfect world - you can't change the request or use step-through debugging to walk through the problem one line at a time.
So, how will you figure out what caused it this time, when you can't just "do that again" and have it happen again?
In short, logging out stack traces and debug info, identifying the most critical question you need to answer. The most obvious is, at a minimum, what EXACTLY is being sent to the printer? Is the printer being told once to print an item, or is it being told over and over and over, or is it being told once but with a quantity specified?
One "simplest possible thing that might work" is to log exactly every single print request, with the expectation that this might be a big log (deal with that in planning). At the very last step before a request is sent to the printer, log exactly what is being sent. Depending in your implementation this might mean wrapping a streamwriter in a buffer, etc - whatever you need to do).
This log should allow you to "reprint" any label using only the information right there in the log, so you can just "resubmit" the request and have it work EXACTLY like if the request was created by the system in the normal fashion.
Then, the human component - you need someone to make a note of when the bug happens, as close to exactly in time as when it happens (so you can go hunting for a rough timestamp), and even attach one of the duplicate labels to your little "bug report" piece of paper with the time on it. If they could make a note of what came before and what came after, that would be even better - but this is obviously subject to business workflows that may be out of your hand. The suspect label and a rough timestamp would be hugely helpful though.
Then you search your potentially huge log files for that event, and you study it. You resubmit that label and see if it happens with that exact, perfect copy of the request - or if it works normally. You look closely at each byte of the request and make sure it is perfectly according to spec and just like any other proper request.
You make sure that this really is exactly what is being sent to the printer, even if you have to have someone setup a networking appliance as an invisible repeater that logs network traffic so you can make sure it really works like you think it works.
In short, you narrow it down - is it the request to the printer that's bad, or not?
Regardless, you'll learn something from this. Either you learn it's software screwing up the request, or it's "something else". This is defining and limiting the scope of the problem.
Then what? Well, you can always try a different printer, a new computer generating the requests, new network/cable to the printer, etc. Diagnosis by part-swapping is a time-honored tradition in all mechanical fields :)
If all else fails, list this duplicate result as a "rare occurrence, approximately once per month", unable to reliably replicate, known work-around "throw extra labels away", etc...declare it's caused by ghosts, with relevant XKCD:

...and accept that some things are not meant for man to know. Some day the problem will go away, no one will know why, and you get a good story to share with senior programmers some day when "unexplained programming mysteries" becomes the lunch topic.

A: In rough order of difficulty:

*

*Recall that the error may be out of your system. Maybe some person in accounting submitted the same label 10 times. Debug the database it came from, etc. Sometimes when you debug a unit test, it can take you hours to realize there's a typo in your test data.
Honestly reading your problem my suspicion is your components really
are working as designed, they just, somewhere, somehow, are actually receiving the instruction 10 times, from something you're not actively considering (human error, duplication happening somewhere else in program, human clicking 10 times on a frozen screen, etc.)

*Be sure to print the input of the component causing the error. Then you can reproduce and test locally. Your code is unit-testable, right?

*Lots and lots and lots of trace.

*Dump a lot of information of this error. Print all stack trace. Create a heap dump.

*If you can successfully run it on your local machine rapidly and transiently reproduce it, do so and put a breakpoint where you can. Then you can look around the program much better.

*Make usual code improvements. Review all culprit files. Refactor anything that strikes you fishy or wrong. In particular see my first point and refactor your buggy components so they have isolated inputs and are more testable. This is similar to cleaning your room until you find your keys.

A: I would look for a way to detect the duplicates inside your code, check it at various levels of abstraction, and log when it occurs.  You could require a sequence number be submitted with each job, or attach a timestamp to a job, or check a hash.  That way if you detect a duplicate at layer 3, but not layer 2, you've narrowed down your search criteria.
The other benefit to this approach is you can often work around the symptom even before you know the cause.  Assuming you can tell the difference between user-initiated duplicates and bug duplicates, you can just suppress the duplicates when they are detected after the fact.  This isn't an ideal solution, but it's better than leaving the problem for months or years, especially if the duplicates now are only being caught by manual inspection.


text:
Q: unifying const T& and T&& overloads I have the following two function template overloads:
template<typename T>
optional<T> some(const T& x)
{
    return optional<T>(x);
}

template<typename T>
typename std::enable_if<std::is_rvalue_reference<T&&>::value, optional<T> >::type
some(T&& x)
{
    return optional<T>(std::move(x));
}

My first attempt at unifying the overloads via perfect forwarding failed:
template<typename T>
optional<T> some(T&& x)
{
    return optional<T>(std::forward<T>(x));
}

error: forming pointer to reference type 'const std::basic_string<char>&'

As did my second attempt:
template<typename T>
optional<typename std::remove_reference<T>::type> some(T&& x)
{
    return optional<typename std::remove_reference<T>::type>(std::forward<T>(x));
}

error: no matching function for call to
'std::basic_string<char>::basic_string(gpa::optional<const std::basic_string<char> >)'

Is there a clean way to unify the overloads, or should I just live with having them?

A: I'm not familiar with your optional, but perhaps you need to add:
typename remove_const< ... >::type

around your remove_reference in two places.  (because your 1st overload of your 2-overload solution - which I assume is passing all of your tests - effectively does a remove_const when declaring optional<T>).

A: In general, the best way to do this is to take the object by value and let the caller decide whether to copy or move it:
template<typename T>
optional<T> some(T x)
{
    return optional<T>(std::move(x));
}

If the caller calls it with a temporary or uses std::move on their value, then it's moved. Otherwise it's copied.
Yes, this does mean that you'll do one additional move (which, if movement is the same as copying, means doing two copies). If that's a significant performance problem for you, then you'll have to use the two overloads implementation.


text:
Q: How to get value of the span corresponding to the checked checkbox in jquery I need to retrieve the span value as per checkbox checked using Jquery. I am explaining my code below.

Select Vehicle

    <input type="radio" checked="checked" name="sVehicle">
    Car
    435

    <input type="radio" name="sVehicle">
    Bus
    356

    <input type="radio" name="sVehicle">
    Tempo Traveller
    567

  <input type="hidden" value="" name="vehicleprice" />

Here my requirement is when checkbox will be checked then its corresponding span value will be etched and add to that hidden input textbox.

A: Just add change event your radio buttons and then get your span text in that. Add vehicleprice id to your hidden field

$(document).ready(function () {
        $("input[type='radio']").change(function () {
            if ($(this).is(":checked")) {
                var spanValue = $(this).parent().find("span:last").text().trim();
               // var oldVal = $("#vehicleprice").val();
                $("#vehicleprice").val(spanValue);

                console.log(spanValue);
            }
        });
    });

Select Vehicle

     <input type="radio" checked="checked" name="sVehicle">
     Car  435

   <input type="radio" name="sVehicle">
   Bus  356

<input type="radio" name="sVehicle">
Tempo Traveller  567

<input type="hidden" value="" name="vehicleprice" id="vehicleprice" />

A: You should use change event listener for input[name='sVehicle'] elements and in function use .nextAll() to selecting next element after target input.

$(":radio").change(function(){
  $("input[name='vehicleprice']").val(
    $("input[name='sVehicle']:checked").nextAll(".badge").text()
  );
  console.log($("input[name='vehicleprice']").val());
});

Select Vehicle

    <input type="radio" checked="checked" name="sVehicle">
    Car
    435

    <input type="radio" name="sVehicle">
    Bus
    356

    <input type="radio" name="sVehicle">
    Tempo Traveller
    567

  <input type="hidden" value="" name="vehicleprice" />

Note that you can use .trigger("change") to fire change event on page load to set value of first checked radio into hidden input.
$(":radio").change(function(){
  $("input[name='vehicleprice']").val(
    $("input[name='sVehicle']:checked").nextAll(".badge").text()
  );
}).trigger("change");

A: Here is small jquery code for getting corresponding span value :

$(document).on('change','input[name="sVehicle"]',function(){

  var spanval =$(this).closest('label.radio').find('span.badge').text();
  $("input[name='vehicleprice']").val(spanval);
  console.log($("input[name='vehicleprice']").val());
});


text:
Q: c# executing a string as code...is it worth the effort? Here's the story so far:
I'm doing a C# winforms application to facilitate specifying equipment for hire quotations.
In it, I have a List<T> of ~1500 stock items.
These items have a property called AutospecQty that has a get accessor that needs to execute some code that is specific to each item. This code will refer to various other items in the list.
So, for example, one item (let's call it Item0001) has this get accessor that may need to execute some code that may look something like this:
[some code to get the following items from the list here]

if(Item0002.Value + Item0003.Value > Item0004.Value)
{ return Item0002.Value }
else
{ return Item0004.Value }

Which is all well and good, but these bits of code are likely to change on a weekly basis, so I'm trying to avoid redeploying that often. Also, each item could (will) have wildly different code. Some will be querying the list, some will be doing some long-ass math functions, some will be simple addition as above...some will depend on variables not contained in the list.
What I'd like to do is to store the code for each item in a table in my database, then when the app starts just pull the relevant code out and bung it in a list, ready to be executed when the time comes.
Most of the examples I've seen on the internot regarding executing a string as code seem quite long-winded, convoluted, and/or not particularly novice-coder friendly (I'm a complete amateur), and don't seem to take into account being passed variables.
So the questions are:

*

*Is there an easier/simpler way of achieving what I'm trying to do?

*If 1=false (I'm guessing that's the case), is it worth the effort of all the potential problems of this approach, or would my time be better spent writing an automatic update feature into the application and just keeping it all inside the main app (so the user would just have to let the app update itself once a week)?

*Another (probably bad) idea I had was shifting all the autospec code out to a separate DLL, and either just redeploying that when necessary, or is it even possible to reference a single DLL on a shared network drive?

I guess this is some pretty dangerous territory whichever way I go. Can someone tell me if I'm opening a can of worms best left well and truly shut?
Is there a better way of going about this whole thing? I have a habit of overcomplicating things that I'm trying to kick :P
Just as additional info, the autospec code will not be user-input. It'll be me updating it every week (no-one else has access to it), so hopefully that will mitigate some security concerns at least.
Apologies if I've explained this badly.
Thanks in advance

A: Looks like you may be well served by implementing the specification pattern.
As wikipedia describes it:

whereby business logic can be recombined by chaining the business logic together using boolean logic.

A: Have you considered something like MEF, then you could have lots of small dlls implementing various versions of your calculations and simply reference which one to load up from the database.
That is assuming you can wrap them all in a single (or small number of) interfaces.

A: I would attack this problem by creating a domain specific language which the program could interpret to execute the rules. Then put snippits of the DSL code in the database.
As you can see, I also like to overcomplicate things. :-) But it works as long as the long-term use is simplified.

A: Some options to consider:
1) If you had a good continuous integration system with automatic build and deployment, would deploying every week be such an issue?
2) Have you considered MEF or similar which would allow you to substitute just a single DLL containing the new rules?
3) If the formula can be expressed simply (without needing to eval some code, e.g. A+B+C+D > E+F+G+H => J or K) you might be able to use reflection to gather the parameter values and then apply them.
4) You could use Expressions in .NET 4 and build an expression tree from the database and then evaluate it.

A: You could have your program compile up your rules at runtime into a class that acts like a plugin using the CSharpCodeProvider.
See Compiling code during runtime for a sample of how to do this.


text:
Q: mySQL: tables with many columns Sorry if this question may be very basic (or even stupid) but I am not very skilled in mySQL. However, I need to create a database for my master thesis so I want to be sure it is the most "elegant" and correct as possible.
I have a dataset with a number of Merger and Acquisition deals with relative information (dealid + 12 columns). I need to add information about the industry of the deal. However, this information comes from 3 different databases that apply to subsets of the M&A: some deals have one classification, some another and some another.
For all I know I have two options: integrate all in the deal table or splitting it in 4 tables (one for the deals and one for each different classification) with 1-1 relations. In the first case I would have a table with more than 50 columns, but the second approach does not look very nice.
Does it one of these approaches make sense? Or is there another way I don't know?
EDIT: right now I have 4 excel tables that I would like to import into mySQL. The main table is the "deal" table: it has the primary key "dealid" and then other columns like "parentname", "targetname", etc.
So far, I then have 3 more tables, one for each classification. The primary key is again "dealid", but then every table has specific columns (about 15) since every classification has different features (such as NACE code, NACE code description, industry sector, SIC code etc.).
Thanks in advance.

A: Very generally, you should aim to have smaller, less-complex tables that you can then combine in many different ways.
https://en.wikipedia.org/wiki/Database_normalization
If necessary you can then use JOINs, VIEWS and other fun stuff to pull together the info that you need for a specific requirement.

A: In your case, you should specifically have different tables, which are then combined.
Why?  Relational databases are designed to handle data in different tables.  In general, a single table contains a single "entity", and entities have relationships.  You have clearly defined multiple entities in your question -- "deals" and "industries".  From the question, I'm not sure if the best solution is 2, 3, or 4 entity tables, but clearly there are more than one.
Next, when you implement them, you want to have keys that connect them.  I strongly recommend having an auto-incremented primary key in each table and using that for the relationships.
So, a conceptual example of how to define the tables:
create table industries (
    IndustryId int not null autoincrement primary key,
    IndustryCode varchar(10),
    . . .
);

create table deals (
    DealId int not null autoincrement primary key,
    IndustryId int,
    . . .,
    constraint fk_deals_industry foreign key (IndustryId) references Industries(IndustryId)
);


text:
Q: MYSQL COUNT not returning 0 for Left Join and Group By I am simply trying to get the code below to recognize when the count is zero and return 0.
Setting the date variables and week numbers table
//set first of the year and today
  $year = date("Y");
  $start = "01/01/".$year;
  $today = date("Y-m-d");
  $first = $year."-01-01";
  $start = $year."-01-01";

  $date1 = new DateTime($first);
  $date2 = new DateTime($today);
  $interval = $date1->diff($date2);

  $weeks = floor(($interval->days) / 7);

  //create weeks table
    $sql = "DROP TEMPORARY TABLE IF EXISTS weekstbl" ;
    mysqli_query ($db, $sql ) or ( "Error " . mysqli_error () ) ;

    $weekstbl = "
      CREATE TEMPORARY TABLE weekstbl (
        `weekNo` int NOT NULL,
        `weekStart` Date,
        `weekEnd` Date,
        PRIMARY KEY(weekNo)
      )
    ";

   mysqli_query($db, $weekstbl) or die ("Sql error : ".mysqli_error());

  for($i = 1; $i <= $weeks; $i++){
      $week = $date1->format("W");
      $date1->add(new DateInterval('P6D'));
      $date1->format('Y-m-d');
      $newDate1 = $date1->format('Y-m-d');

      $statement = $db->prepare("INSERT INTO weekstbl (weekNo,weekStart,weekEnd) VALUES (?,?,?)");
      $statement->bind_param('iss', $week,$start,$newDate1);
      $statement->execute();

      $date1->add(new DateInterval('P1D'));
      $start = $date1->format('Y-m-d');
  }

This code outputs the all of the week numbers, start date for the week and end date for the week for the current year through the current day.  Looks like the following:
------------------------------------
| weekNo |  weekStart |  weekEnd   |
------------------------------------
|   52   | 2017-01-01 | 2017-01-07 |
|    1   | 2017-01-08 | 2017-01-14 |
|    2   | 2017-01-15 | 2017-01-21 |

This continues on through the current date the system is being accessed.  This will then be used to join with another few other tables with conditions.  This is what I expect to be returned but in all of my trials listed below, I cannot accomplish this.  I ran this when there were 12 weeks in the current Year, which means there should be 12 numbers following the name.
[["Ryan Balcom",3,30,3,1,10,0,1,2,5,1,3,3],["Jared Beckwith",40,8,13,8,13,7,5,3,11,5,3,1],["Jim Roberts",0,32,8,7,2,9,4,2,8,4,4,10],["Jim Kelly",44,24,12,14,14,16,10,25,12,8,7,6],["Josh Bell",34,10,10,5,9,8,5,23,7,6,6,14],["Rick Zuniga",0,0,0,0,0,3,1,1,0,0,0,0],["Mike Horton",37,20,7,10,16,5,6,4,5,3,5,1],["Paul Schilthuis",31,11,9,2,8,6,4,0,5,9,8,4],["TJ Sutton",1,10,0,0,0,0,0,0,0,0,0,0]]

Trial 1
    $assignments = "
SELECT COUNT(j.leadid) AS leadcount, u.username
  FROM weekstbl wk
  LEFT JOIN jobbooktbl j
    ON wk.weekNo=WEEK(j.leadcreated)
  LEFT JOIN assignmentstbl a
    ON j.leadid=a.custid
  LEFT JOIN usertbl u
    ON a.userid=u.userid
  WHERE j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."'
  GROUP BY WEEK(j.leadcreated), a.userid";
    $assignmentsqry = mysqli_query($db,$assignments);
    while ($row = mysqli_fetch_array($assignmentsqry)) {
      $key = $row['username']; //unnecessary variable for demonstration purposes
      if (!isset($volumeYTDsm[$key])) {
        $volumeYTDsm[$key] = [$row['username']];
      }
      $float = floatval($row['leadcount']);
        $volumeYTDsm[$key][] = $float;
      }
      $volumeYTDsm = array_values($volumeYTDsm);//removing keys
    }

This outputs the above but does not inlcude the 0 weeks:
[["Ryan Balcom",3,30,3,1,10,1,2,5,1,3,3],["Jared Beckwith",40,8,13,8,13,7,5,3,11,5,3,1],["Jim Roberts",32,8,7,2,9,4,2,8,4,4,10],["Jim Kelly",44,24,12,14,14,16,10,25,12,8,7,6],["Josh Bell",34,10,10,5,9,8,5,23,7,6,6,14],["Rick Zuniga",3,1,1],["Mike Horton",37,20,7,10,16,5,6,4,5,3,5,1],["Paul Schilthuis",31,11,9,2,8,6,4,5,9,8,4],["TJ Sutton",1,10]]

Trial 2
$assignments = "
  SELECT COUNT(*) AS leadcount, u.username
    FROM weekstbl wk
    LEFT OUTER JOIN jobbooktbl j
      ON (wk.weekNo=WEEK(j.leadcreated)) AND j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND YEAR(j.leadcreated) = '".$year."'
    LEFT JOIN assignmentstbl a
      ON j.leadid=a.custid
    LEFT JOIN usertbl u
      ON a.userid=u.userid
    GROUP BY wk.weekNo, a.userid";

This outputs the following...not really sure what this is outputting with the null name:
[[null,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],["Ryan Balcom",3,30,3,1,10,1,2,5,1,3,3],["Jared Beckwith",40,8,13,8,13,7,5,3,11,5,3,1],["Jim Roberts",32,8,7,2,9,4,2,8,4,4,10],["Jim Kelly",44,24,12,14,14,16,10,25,12,8,7,6],["Josh Bell",34,10,10,5,9,8,5,23,7,6,6,14],["Rick Zuniga",3,1,1],["Mike Horton",37,20,7,10,16,5,6,4,5,3,5,1],["Paul Schilthuis",31,11,9,2,8,6,4,5,9,8,4],["TJ Sutton",1,10]]

With both of these methods I have tried to include COALESCE and IFNULL but neither changed the result for either query:
COALESCE(COUNT(j.leadid),0) AS leadcount
IFNULL(COUNT(j.leadid),0) AS leadcount

I have been trying to figure this out for a month and nothing I throw at it seems to work.  Any assistance or direction would be greatly appreciated!

A: You need to add a column from the primary table to your group by, otherwise you are grouping by values that only exist in one of your left joins.
SELECT
    COUNT(j.leadid) AS leadcount,
    IF(u.username IS NULL,'NOT FOUND',u.username) AS username
FROM weekstbl wk
LEFT JOIN jobbooktbl j
    ON wk.weekNo=WEEK(j.leadcreated)
LEFT JOIN assignmentstbl a
    ON j.leadid=a.custid
  LEFT JOIN usertbl u
    ON a.userid=u.userid
  WHERE (j.leadcreated >= '".$first."' AND
        j.leadcreated <= '".$today."' AND
        YEAR(j.leadcreated) = '".$year."') OR
        j.leadcreated IS NULL
  GROUP BY wk.weekno, WEEK(j.leadcreated), a.userid
  ORDER BY wk.weekStart

A better where clause would compare to the date in weekstbl.

A: The condition in the WHERE is turning the first LEFT JOIN into an inner join.  So, you would seem to want:
SELECT COUNT(j.leadid) AS leadcount, u.username
FROM weekstbl wk LEFT JOIN
     jobbooktbl j
     ON wk.weekNo = WEEK(j.leadcreated) AND
        j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND
        YEAR(j.leadcreated) = '".$year."'LEFT JOIN
     assignmentstbl a
     ON j.leadid = a.custid LEFT JOIN
     usertbl u
     ON a.userid = u.userid
GROUP BY WEEK(j.leadcreated), a.userid;

However, you are aggregating by the week, but not including the week in the SELECT.  I suspect that you want:
SELECT wk.weekNo, u.username, COUNT(j.leadid) AS leadcount
FROM weekstbl wk LEFT JOIN
     jobbooktbl j
     ON wk.weekNo = WEEK(j.leadcreated) AND
        j.leadcreated >= '".$first."' AND j.leadcreated <= '".$today."' AND
        YEAR(j.leadcreated) = '".$year."'LEFT JOIN
     assignmentstbl a
     ON j.leadid = a.custid LEFT JOIN
     usertbl u
     ON a.userid = u.userid
GROUP BY wk.weekNo, a.userid;

You don't want to aggregate by WEEK(j.leadcreated) because that might be NULL.


text:
Q: How to automatically determine customer industry from email address or company name? I have a customer database containing email addresses and company names. I want to know what industries my customers are in so that I can analyze revenue statistics. However, I have historically not asked my customers what industries they are in. And when a customer signs up for my web app, I want to ask them as few questions as possible, so I'd rather not ask them for their industry if I can avoid it.
I know that industry information is sort-of public. I can manually scrape them from LinkedIn. There may be other sites too where I can lookup industry information too. But the LinkedIn ToS does not allow automatic scraping. So I'm wondering whether there are other automatic ways to determine a customer's industry, based on either an email address or a company name.


text:
Q: React Hooks Onchange Synchronize Im passing my app from the class model to the hooks and in my code y have a dropdown list that when executes the onChange method it does this:
filter(event)
{
    this.setState({
        selectedFilter: event.target.value
      },() => { this.chargeInfo(); });
}

In my class model works perfectly, but i dont know how to do this with the hooks, im passing the method chargeInfo() and the variable selectedFilter by the props because this component is a child, so what I have is this code:
<Dropdown onChange={onChangeDropdown} />

const onChangeDropdown = function(event)
{
    props.changeSelectedFilter(event.target.value);//this do setSelecedFilter in the parent
    props.chargeInfo();//this is the method of the parent that do something
}

How can I adapt this in a Sync mode that execute first the props.changeSelectedFilter and later the props.chargeInfo?.

A: You may need to use the State Hook like this:
// setting up the default dropdown value
const [dropdownValue, setDropdownValue] = useState('Some Value');

// later, setting a new dropdown value
setDropdownValue('New Value')

See https://reactjs.org/docs/hooks-state.html for more info

A: I solved using useEffect:
useEffect(
    () => {
    // eslint-disable-next-line react-hooks/exhaustive-deps
    props.chargeInfo();}, [props.selectedFilter]
    )

const onChangeDropdown = function(event)
{
    props.changeSelectedFilter(event.target.value);
}

return(

    <Dropdown style={{ marginRight: 10, }} value={props.selectedFilter} options={filters}
    onChange={onChangeDropdown} optionLabel="name" placeholder="Filter by" />
)


text:
Q: tex-common error when trying to install texlive -- Ubuntu 20.04 LTS I'm trying to install texlive.
I "purged" texlive after a "successful" installation in Ubuntu 20.04 on a new machine produced a situation where I could not compile any of the *.tex files that easily work on my other systems. So I decided to wipe that installation, and try again.
I put "purged" in quotes because, after attempting to purge texlive from my system (by going through the steps given in the accepted answer in this Tex Stack Exchange post), it appeared the process actually did not remove everything texlive-related as I had expected.
Nonetheless, I tried installing texlive again, and am now in a hopeless loop where whatever command I use -- sudo apt-get install 'texlive-*' or sudo apt install texlive-full or any of the longer, more involved ones -- I get an error that always involves tex-common:
fmtutil failed. Output has been stored in /tmp/fmtutil.L7mCqGpc Please include this file if you report a bug.

dpkg: error processing package tex-common (--configure):  installed
tex-common package post-installation script subprocess returned error
exit status 1 Errors were encountered while processing:  tex-common E:
Sub-process /usr/bin/dpkg returned an error code (1)

After each failed attempt, I go through the same steps to "purge" texlive so as to remove from my system what I hope are all vestiges of the failed attempt.
I have noticed that after going through those eight steps to remove texlive from my system, there are files still left over, that relate to tex-common. So when I try sudo apt-get purge tex-common and then do locate tex-common sixteen files/folders come up.
How can I resolve this issue so I can successfully install texlive?

N0rbert, thanks for your response. PPA... don't think I used one. Sorry, can't remember, I never had an issue with my other machines. I think I just used sudo apt install texlive-full or something similar. I might have installed TexWorks using the Ubuntu Software Center... wiped it using the stepwise method I mentioned above.
Output of grep -r "^deb " /etc/apt/ --include="*.list":
/etc/apt/sources.list:deb http://archive.ubuntu.com/ubuntu/ focal main restricted universe multiverse
/etc/apt/sources.list:deb http://security.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse
/etc/apt/sources.list:deb http://archive.ubuntu.com/ubuntu/ focal-updates main restricted universe multiverse
/etc/apt/sources.list.d/teams.list:deb [arch=amd64] https://packages.microsoft.com/repos/ms-teams stable main
/etc/apt/sources.list.d/miktex.list:deb http://miktex.org/download/ubuntu bionic universe
/etc/apt/sources.list.d/system76-dev-ubuntu-stable-focal.list:deb http://ppa.launchpad.net/system76-dev/stable/ubuntu focal main
/etc/apt/sources.list.d/google-chrome.list:deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main

Output of apt-cache policy texlive-full:
texlive-full:
  Installed: 2019.20200218-1
  Candidate: 2019.20200218-1
  Version table:
 *** 2019.20200218-1 500
        500 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages
        100 /var/lib/dpkg/status

Output of sudo apt-get dist upgrade:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  fwupd fwupd-signed google-chrome-stable libegl-mesa0 libegl1-mesa libfwupd2 libfwupdplugin1 libgbm1 libgl1-mesa-dri
  libgl1-mesa-glx libglapi-mesa libglx-mesa0 libmysqlclient21 libnetplan0 libnss-systemd libpam-systemd libsystemd0 libudev1
  libxatracker2 linux-firmware mesa-vulkan-drivers netplan.io python3-update-manager system76-driver system76-power systemd
  systemd-sysv systemd-timesyncd udev update-manager update-manager-core
31 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
Need to get 143 kB/312 MB of archives.
After this operation, 5,979 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://ppa.launchpad.net/system76-dev/stable/ubuntu focal/main amd64 libegl-mesa0 amd64 21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev [143 kB]
Fetched 135 kB in 1s (240 kB/s)
Extracting templates from packages: 100%
(Reading database ... 475587 files and directories currently installed.)
Preparing to unpack .../libnss-systemd_245.4-4ubuntu3.13_amd64.deb ...
Unpacking libnss-systemd:amd64 (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Preparing to unpack .../udev_245.4-4ubuntu3.13_amd64.deb ...
Unpacking udev (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Preparing to unpack .../libudev1_245.4-4ubuntu3.13_amd64.deb ...
Unpacking libudev1:amd64 (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Setting up libudev1:amd64 (245.4-4ubuntu3.13) ...
(Reading database ... 475588 files and directories currently installed.)
Preparing to unpack .../systemd-sysv_245.4-4ubuntu3.13_amd64.deb ...
Unpacking systemd-sysv (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Preparing to unpack .../systemd-timesyncd_245.4-4ubuntu3.13_amd64.deb ...
Unpacking systemd-timesyncd (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Preparing to unpack .../libpam-systemd_245.4-4ubuntu3.13_amd64.deb ...
Unpacking libpam-systemd:amd64 (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Preparing to unpack .../systemd_245.4-4ubuntu3.13_amd64.deb ...
Unpacking systemd (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Preparing to unpack .../libsystemd0_245.4-4ubuntu3.13_amd64.deb ...
Unpacking libsystemd0:amd64 (245.4-4ubuntu3.13) over (245.4-4ubuntu3.11) ...
Setting up libsystemd0:amd64 (245.4-4ubuntu3.13) ...
(Reading database ... 475588 files and directories currently installed.)
Preparing to unpack .../00-libgl1-mesa-dri_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libgl1-mesa-dri:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../01-libglx-mesa0_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libglx-mesa0:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../02-libegl-mesa0_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libegl-mesa0:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../03-libglapi-mesa_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libglapi-mesa:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../04-libgbm1_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libgbm1:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../05-google-chrome-stable_94.0.4606.71-1_amd64.deb ...
Unpacking google-chrome-stable (94.0.4606.71-1) over (94.0.4606.54-1) ...
Preparing to unpack .../06-libnetplan0_0.103-0ubuntu5~20.04.1_amd64.deb ...
Unpacking libnetplan0:amd64 (0.103-0ubuntu5~20.04.1) over (0.102-0ubuntu1~20.04.2) ...
Preparing to unpack .../07-netplan.io_0.103-0ubuntu5~20.04.1_amd64.deb ...
Unpacking netplan.io (0.103-0ubuntu5~20.04.1) over (0.102-0ubuntu1~20.04.2) ...
Preparing to unpack .../08-python3-update-manager_1%3a20.04.10.9_all.deb ...
Unpacking python3-update-manager (1:20.04.10.9) over (1:20.04.10.7) ...
Preparing to unpack .../09-update-manager-core_1%3a20.04.10.9_all.deb ...
Unpacking update-manager-core (1:20.04.10.9) over (1:20.04.10.7) ...
Preparing to unpack .../10-update-manager_1%3a20.04.10.9_all.deb ...
Unpacking update-manager (1:20.04.10.9) over (1:20.04.10.7) ...
Preparing to unpack .../11-fwupd-signed_1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev_amd64.deb ...
Unpacking fwupd-signed (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) over (1.5.11-0ubuntu2pop1~1627329462~20.04~3e64f3f~dev) ...
Preparing to unpack .../12-libfwupd2_1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev_amd64.deb ...
Unpacking libfwupd2:amd64 (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) over (1.5.11-0ubuntu2pop1~1627329462~20.04~3e64f3f~dev) ...
Preparing to unpack .../13-libfwupdplugin1_1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev_amd64.deb ...
Unpacking libfwupdplugin1:amd64 (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) over (1.5.11-0ubuntu2pop1~1627329462~20.04~3e64f3f~dev) ...
Preparing to unpack .../14-fwupd_1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev_amd64.deb ...
Unpacking fwupd (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) over (1.5.11-0ubuntu2pop1~1627329462~20.04~3e64f3f~dev) ...
Preparing to unpack .../15-libegl1-mesa_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libegl1-mesa:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../16-libgl1-mesa-glx_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libgl1-mesa-glx:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../17-libmysqlclient21_8.0.26-0ubuntu0.20.04.3_amd64.deb ...
Unpacking libmysqlclient21:amd64 (8.0.26-0ubuntu0.20.04.3) over (8.0.26-0ubuntu0.20.04.2) ...
Preparing to unpack .../18-libxatracker2_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking libxatracker2:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../19-linux-firmware_1.200+system76~1632347857~20.04~9a6d09b~dev_all.deb ...
Unpacking linux-firmware (1.200+system76~1632347857~20.04~9a6d09b~dev) over (1.199+system76~1627913034~20.04~a184ea1~dev) ...
Preparing to unpack .../20-mesa-vulkan-drivers_21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev_amd64.deb ...
Unpacking mesa-vulkan-drivers:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) over (21.2.1-2ubuntu1pop0~1631200248~20.04~4d5cd49~dev) ...
Preparing to unpack .../21-system76-power_1.1.18~1632516399~20.04~0bf0fc7~dev_amd64.deb ...
Unpacking system76-power (1.1.18~1632516399~20.04~0bf0fc7~dev) over (1.1.18~1632252487~20.04~4f636eb~dev) ...
Preparing to unpack .../22-system76-driver_20.04.43~1632933380~20.04~0ac2ed2~dev_all.deb ...
Unpacking system76-driver (20.04.43~1632933380~20.04~0ac2ed2~dev) over (20.04.42~1631829434~20.04~fd049c1~dev) ...
Setting up mesa-vulkan-drivers:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up libmysqlclient21:amd64 (8.0.26-0ubuntu0.20.04.3) ...
Setting up libgbm1:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up linux-firmware (1.200+system76~1632347857~20.04~9a6d09b~dev) ...
update-initramfs: Generating /boot/initrd.img-5.13.0-7614-generic
update-initramfs: Generating /boot/initrd.img-5.11.0-7633-generic
update-initramfs: Generating /boot/initrd.img-5.11.0-37-generic
Setting up libfwupd2:amd64 (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) ...
Setting up libnetplan0:amd64 (0.103-0ubuntu5~20.04.1) ...
Setting up libxatracker2:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up libegl1-mesa:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up tex-common (6.13) ...
Running mktexlsr. This may take some time... done.
Running mtxrun --generate. This may take some time... done.
Running updmap-sys. This may take some time... done.
Running mktexlsr /var/lib/texmf ... done.
Building format(s) --all.
    This may take some time...
fmtutil failed. Output has been stored in
/tmp/fmtutil.VSeGny8X
Please include this file if you report a bug.

dpkg: error processing package tex-common (--configure):
 installed tex-common package post-installation script subprocess returned error exit status 1
Setting up udev (245.4-4ubuntu3.13) ...
update-initramfs: deferring update (trigger activated)
Setting up libfwupdplugin1:amd64 (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) ...
Setting up libglapi-mesa:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up python3-update-manager (1:20.04.10.9) ...
Setting up fwupd (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) ...
fwupd-offline-update.service is a disabled or a static unit not running, not starting it.
fwupd-refresh.service is a disabled or a static unit not running, not starting it.
Setting up google-chrome-stable (94.0.4606.71-1) ...
Setting up libgl1-mesa-dri:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up fwupd-signed (1.5.11-0ubuntu2pop1.1~1632510283~20.04~5dec90e~dev) ...
Setting up libegl-mesa0:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up update-manager-core (1:20.04.10.9) ...
Setting up libglx-mesa0:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up update-manager (1:20.04.10.9) ...
Setting up libgl1-mesa-glx:amd64 (21.2.1-2ubuntu2pop0~1632348269~20.04~616afda~dev) ...
Setting up systemd (245.4-4ubuntu3.13) ...
Installing new version of config file /etc/dhcp/dhclient-enter-hooks.d/resolved ...
Setting up netplan.io (0.103-0ubuntu5~20.04.1) ...
Setting up systemd-timesyncd (245.4-4ubuntu3.13) ...
Setting up system76-power (1.1.18~1632516399~20.04~0bf0fc7~dev) ...
Setting up systemd-sysv (245.4-4ubuntu3.13) ...
Setting up libnss-systemd:amd64 (245.4-4ubuntu3.13) ...
Setting up libpam-systemd:amd64 (245.4-4ubuntu3.13) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu3) ...
Processing triggers for mime-support (3.64ubuntu1) ...
Processing triggers for initramfs-tools (0.136ubuntu6.6) ...
update-initramfs: Generating /boot/initrd.img-5.13.0-7614-generic
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for libglib2.0-0:amd64 (2.64.6-1~ubuntu20.04.4) ...
Processing triggers for libc-bin (2.31-0ubuntu9.2) ...
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for dbus (1.12.16-2ubuntu2.1) ...
Setting up system76-driver (20.04.43~1632933380~20.04~0ac2ed2~dev) ...
INFO    product_version: 'meer6'
INFO    displayport1_force_enable_audio: Force enable audio output from DP-1 (physical HDMI 1 port.)
INFO    Skipping 'displayport1_force_enable_audio' as it was already applied
Errors were encountered while processing:
 tex-common
E: Sub-process /usr/bin/dpkg returned an error code (1)

Output of apt-cache policy miktex:
miktex:
  Installed: (none)
  Candidate: 21.6-bionic1
  Version table:
     21.6-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     21.3-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     21.1-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     20.12-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     20.11-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     20.10-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     20.6.29-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages
     20.6-bionic1 500
        500 http://miktex.org/download/ubuntu bionic/universe amd64 Packages

Output of sudo apt-get install tree:
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  tree
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
Need to get 43.0 kB of archives.
After this operation, 115 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu focal/universe amd64 tree amd64 1.8.0-1 [43.0 kB]
Fetched 43.0 kB in 0s (88.5 kB/s)
Selecting previously unselected package tree.
(Reading database ... 475613 files and directories currently installed.)
Preparing to unpack .../tree_1.8.0-1_amd64.deb ...
Unpacking tree (1.8.0-1) ...
Setting up tex-common (6.13) ...
Running mktexlsr. This may take some time... done.
Running mtxrun --generate. This may take some time... done.
Running updmap-sys. This may take some time... done.
Running mktexlsr /var/lib/texmf ... done.
Building format(s) --all.
    This may take some time...
fmtutil failed. Output has been stored in
/tmp/fmtutil.1bdpEBPj
Please include this file if you report a bug.

dpkg: error processing package tex-common (--configure):
 installed tex-common package post-installation script subprocess returned error exit status 1
Setting up tree (1.8.0-1) ...
Processing triggers for man-db (2.9.1-1) ...
Errors were encountered while processing:
 tex-common
E: Sub-process /usr/bin/dpkg returned an error code (1)`

Output of tree /usr/local/bin:
/usr/local/bin

0 directories, 0 files

N0rbert, thanks for your fast responses. The /tmp/fmtutil.VSeGny8X is pretty large, over 14,000 lines. Is there a way to upload it?
Yes, running System76 meerkat hardware.
which miktexsetup returns nothing.
Output of dpkg -l:
Apologies, but how do I upload the file that contains the output? It's another biggie

A: TL;DR Do not use/mix MikTex with deb-packaged TeXLive. Do not use/mix binary TeXLive with deb-packaged TeXLive. Use only deb-packaged TeXLive instead to prevent problems.
Details. The system has active MikTex repository. To prevent possible conflicts with TexLive disable it using commands below:
miktexsetup cleanup
sudo miktexsetup --shared=yes cleanup

sudo apt autoremove --purge miktex
sudo rm -v /etc/apt/sources.list.d/miktex.list
sudo rm -v /etc/fonts/conf.d/09-miktex.conf
sudo apt-get update

and then use only TexLive.
During chat session we discovered that system had local installation of Texlive. We did this by using the following steps:

*

*remove all TeX related packages with
sudo apt autopurge $(dpkg -l | grep "TeX" | grep ^ii | awk '{print $2}')

And what is interesting - removal process has several lines like dpkg: warning: while removing texlive-latex-extra, directory '/usr/share/texlive/texmf-dist/tex/latex/stex/statements' not empty so not removed. So we classified them and removed by commands like:
sudo rm -rfv /usr/share/fonts/truetype/artemisia
sudo rm -rfv /usr/share/fonts/truetype/baskerville
sudo rm -rfv /usr/share/fonts/truetype/bodoni-classic
sudo rm -rfv /usr/share/fonts/truetype/didot
sudo rm -rfv /usr/share/fonts/truetype/didot-classic
sudo rm -rfv /usr/share/fonts/truetype/gazis
sudo rm -rfv /usr/share/fonts/truetype/gentium
sudo rm -rfv /usr/share/fonts/truetype/neohellenic
sudo rm -rfv /usr/share/fonts/truetype/olga
sudo rm -rfv /usr/share/fonts/truetype/porson
sudo rm -rfv /usr/share/fonts/truetype/solomos
sudo rm -rfv /usr/share/fonts/truetype/theokritos
sudo rm -rfv /usr/share/fonts/type1/texlive-fonts-recommended
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/achemso
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/acro
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/animate
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/base
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/caption
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/cdpbundl
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/circuitikz
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/dtk
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/endfloat
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/exsheets
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/fancyvrb
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/fontspec
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/glossaries/base
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/graphics
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/hyperref
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/invoice
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/isodoc
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/l3experimental/l3str
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/l3kernel
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/latexconfig
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/lettre
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/makedtx
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/memoir
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/minitoc
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/ms
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/nomencl
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/oberdiek
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/pdfpages
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/pdfx
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/pkgloader
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/polyglossia
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/cmath
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/dcm
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/hwexam
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/metakeys
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/mikoslides
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/modules
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/omdoc
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/omtext
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/presentation
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/problem
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/sproof
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/sref
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/statements
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/stex/workaddress
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/sttools
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/titlesec
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/tkz-base
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/tkz-euclide
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/unicode-math
sudo rm -rfv /usr/share/texlive/texmf-dist/tex/latex/xdoc
sudo rm -rfv /usr/share/texmf/fonts/opentype/public/lm
sudo rm -rfv /usr/share/texmf/fonts/opentype/public/lm-math

*then we tried to find the texlive-related files and folders which does not came from deb-packages by using command below
sudo find /bin /etc /lib /lib64 /opt /sbin /srv /usr /var -iname "*texlive*" -exec dpkg -S {} \; > /dev/null

and it shown the following

dpkg-query: no path found matching pattern /usr/share/texlive

and this folder has 98 directories, 482 files according to tree /usr/share/texlive.
So we removed this folder as simple as sudo rm -rfv /usr/share/texlive and then proceed.

*Install all needed stuff as usual
sudo apt-get install texlive-base
sudo apt-get install tex-common
sudo apt-get install texlive-full


text:
Q: Concat a dataframe's value to a dictionary's matching value Tangent related to this post: Customize Bokeh Unemployment Example: Replacing Percentage Value
Starter code:
https://docs.bokeh.org/en/latest/docs/gallery/texas.html
from bokeh.io import show
from bokeh.models import LogColorMapper
from bokeh.palettes import Viridis6 as palette
from bokeh.plotting import figure

from bokeh.sampledata.us_counties import data as counties
counties = { code: county for code, county in counties.items() if county["state"] == "tx" }

csv data:

I have a dictionary of county names:
{(48, 1): {'name': 'Anderson',
  'detailed name': 'Anderson County, Texas',
  'state': 'tx'}
{(48, 3): {'name': 'Andrews',
  'detailed name': 'Andrews County, Texas',
  'state': 'tx'}

and a dataframe created from a csv file of percentage values:
 {'Anderson': 21.0,
 'Andrews': 28.0,
 'Angelina': 31.0,
 'Aransas': 24.0,
 'Archer': 11.0,
 'Armstrong': 53.0,
 'Atascosa': 27.0,
 'Austin': 30.0,
 'Bailey': 42.0,
 'Bandera': 0.0}

I am trying to merge the dataframe's percentage value on the county name in the dictionary.
from bokeh.models import LogColorMapper
from bokeh.palettes import Viridis6 as palette
from bokeh.plotting import figure, show
from bokeh.sampledata.us_counties import data as counties
import csv
import pandas as pd

pharmacy_concentration = {}
with open('resources/unemployment.csv', mode = 'r') as infile:
    next(infile)
    reader = csv.reader(infile, delimiter = ',', quotechar = '"')
    for row in reader:
        name, concentration = row
            pharmacy_concentration[name] = float(concentration)

counties = { code: county for code, county in counties.items() if county["state"] == "tx" }
counties = pd.concat(pharmacy_concentration[concentration], on='name',
how='left', keys='concentration')

counties

I receive a keyerror showing the percentage value and can't figure out why.
Expected output:
 counties
 {(48, 1): {'name': 'Anderson',
 'detailed name': 'Anderson County, Texas',
 'state': 'tx', 'concentration': 21}

A: If I understand you correctly, this is what you want to do:
First of all, we get your dictionarys in two dataframes: county_names & csv_data.
After that I transform them to the right format, but this is probably not necessary for you:
county_names = pd.DataFrame({'(48, 1)': {'name': 'Anderson', 'detailed name': 'Anderson County, Texas', 'state': 'tx'},
                             '(48, 3)': {'name': 'Andrews', 'detailed name': 'Andrews County, Texas', 'state': 'tx'}}).T.reset_index().rename({'index': 'County_ID'}, axis=1)

print(county_names)
  County_ID           detailed name      name state
0   (48, 1)  Anderson County, Texas  Anderson    tx
1   (48, 3)   Andrews County, Texas   Andrews    tx

 d = {'Anderson': 21.0,
 'Andrews': 28.0,
 'Angelina': 31.0,
 'Aransas': 24.0,
 'Archer': 11.0,
 'Armstrong': 53.0,
 'Atascosa': 27.0,
 'Austin': 30.0,
 'Bailey': 42.0,
 'Bandera': 0.0}

csv_data = pd.DataFrame(d, index=[0]).melt(var_name='name', value_name='concentration')
print(csv_data)
        name  concentration
0   Anderson           21.0
1    Andrews           28.0
2   Angelina           31.0
3    Aransas           24.0
4     Archer           11.0
5  Armstrong           53.0
6   Atascosa           27.0
7     Austin           30.0
8     Bailey           42.0
9    Bandera            0.0

Now we can merge our data on the name column:
df_final = pd.merge(county_names, csv_data, on='name')

print(df_final)
  County_ID           detailed name      name state  concentration
0   (48, 1)  Anderson County, Texas  Anderson    tx           21.0
1   (48, 3)   Andrews County, Texas   Andrews    tx           28.0

Note
You can easily read a csv file with pandas, simply use:
pd.read_csv(infile, delimiter = ',', quotechar = '"')

A: Credit to @Tony
from bokeh.models import LogColorMapper
from bokeh.palettes import Viridis256 as palette
from bokeh.plotting import figure, show
from bokeh.sampledata.us_counties import data as counties
import csv

pharmacy_concentration = {}
with open('resources/unemployment.csv', mode = 'r') as infile:
    reader = [row for row in csv.reader(infile.read().splitlines())]
    for row in reader:
        try:
            county_name, concentration = row
            pharmacy_concentration[county_name] = float(concentration)
        except Exception, error:
            print error, row

counties = { code: county for code, county in counties.items() if county["state"] ==
"tx" }
county_xs = [county["lons"] for county in counties.values()]
county_ys = [county["lats"] for county in counties.values()]
county_names = [county['name'] for county in counties.values()]
# Below is the line of code I was missing to make it work
county_pharmacy_concentration_rates = [pharmacy_concentration[counties[county]
['name']] for county in counties if counties[county]['name'] in
pharmacy_concentration]


text:
Q: How can I cancel LoadAsync() without closing the underlying socket? I have an app that communicates to some hardware over rfcomm on bluetooth.  My app works on Android and am in the process of getting things working on UWP. Here's how I set up the stream reader/writers in the UWP code:
var btDevice = await BluetoothDevice.FromIdAsync(devId);

var services = await btDevice.GetRfcommServicesAsync();

if (services.Services.Count > 0)
{
    // We only have one service so use the first one...
    var service = services.Services[0];
    // Create a stream...
    _bluetoothStream = new StreamSocket();
    await _bluetoothStream.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);

    _dataReader = new DataReader(_bluetoothStream.InputStream);
    _dataWriter = new DataWriter(_bluetoothStream.OutputStream);

    _dataReader.InputStreamOptions = InputStreamOptions.Partial;

My hardware only sends data to my app after the app sends it data so I've set up a send/receive mechanism.  Everything works great except for a specific use case where my device is restarting (but bluetooth connection is still active) and is unable to send a response.  In this case my upper level code is setup to attempt a retry, however the bluetooth connection gets closed when the receive times out.
_dataWriter.WriteBytes(comm.TransmitData);

Task<UInt32> writeAysncTask = _dataWriter.StoreAsync().AsTask();

UInt32 bytesWritten = await writeAysncTask;
:
try
{
    using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(comm.TimeoutMs))) // _receiveTimeoutMs)))
    {
        // When this times out, exception gets thrown and socket is closed
        // How do I prevent the socket from closing so I can do a retry???
        var loadTask = _dataReader.LoadAsync(comm.ReceiveCount).AsTask(cts.Token);

        bytesRead = await loadTask;

        if (bytesRead > 0)
        {
            rxData = new byte[bytesRead];
            _dataReader.ReadBytes(rxData);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Received 0!");
        }
    }
}
catch (Exception ex)
{
    // The bluetooth connection is closed automatically if the
    // caancellationToken fires...In my case, I need the connection
    // to stay open...How do I achieve this???

    // Update: When this code is executed with _dataReader/Writer
    // that was created with SerialDevice class (see below), the
    // timeout exception does not cause the Serial connection to
    // close so my calling code can then issue a retry.
    System.Diagnostics.Debug.WriteLine(ex.Message) ;
}

UPDATE:  It should be noted that when I use the exact same code with streams created from a SerialDevice everything works as I would expect...When the receive times out the socket is NOT closed.  Seems like maybe I'm up against something in the Bluetooth Implementation in UWP.  Ugh.  Here's how I create the _dataReader/_dataWriter with the SerialDevice class:
_serialDevice = await SerialDevice.FromIdAsync(devId);
// Configure the port
_serialDevice.BaudRate = _baudrate;
_serialDevice.Parity = SerialParity.None;
_serialDevice.DataBits = 8;
_serialDevice.StopBits = SerialStopBitCount.One;

_dataReader = new DataReader(_serialDevice.InputStream);
_dataWriter = new DataWriter(_serialDevice.OutputStream);

A: I've come up with a work around to the problem I was facing.  Unfortunately, I can't use the same code for SerialDevice and BluetoothDevice.  I have to say, it really stinks that the bluetooth socket gets closed when a cancellation token times out.  The code would be so much cleaner if it didn't close!  Shouldn't it be up to me to decide if the socket should be closed?  Now I'm stuck with this:
    using (var cts = new CancellationTokenSource())
    {
        Task.Run(async () =>
        {
            try
            {
                await Task.Delay((int)comm.TimeoutMs, cts.Token);

                System.Diagnostics.Debug.WriteLine("Canceling async read");
                // If we make it this far, then the read as failed...cancel the async io
                // which will cause the bytesRead below to be 0.
                await _bluetoothStream.CancelIOAsync();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }, cts.Token);

        var loadTask = _dataReader.LoadAsync(comm.ReceiveCount).AsTask();

        bytesRead = await loadTask;

        if (bytesRead > 0)
        {
            // SIgnal the delay task to cancel...
            cts.Cancel(true);
            if (bytesRead > comm.ReceiveCount)
                System.Diagnostics.Debug.WriteLine("Received too much!!");

            rxData = new byte[bytesRead];
            _dataReader.ReadBytes(rxData);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Received 0!");
        }
    }

After implementing this, I did notice that after I've paired my BT device, Windows returns it as a SerialDevice in the following query:
string aqs = SerialDevice.GetDeviceSelector();
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(aqs);
// My bluetooth device is included in the 'devices' collection

So if I connect to it as a serial device, I guess I won't need the work around after all.  Oh well, hopefully this post will help someone else.


text:
Q: Pandas and HDF5, querying a table, string containing '&' character I've ran into a problem grouping with HDFStore which turned out to extend to selecting rows based on strings that contain the '&' character. This should illustrate the problem
>>> from pandas import HDFStore, DataFrame
>>> df = DataFrame({'a': ['a', 'a', 'c', 'b', 'test & test', 'c' , 'b', 'e'],
                   'b': [1, 2, 3, 4, 5, 6, 7, 8]})
>>> store = HDFStore('test.h5')
>>> store.append('test', df, format='table', data_columns=True)
>>> df[df.a == 'test & test']

     a              b
4    test & test    5

>>> store.select('test', 'a="test & test"')

Int64Index([], dtype='int64')   Empty DataFrame

Now I'm wondering if I'm missing something from the documentation or if this is a bug.

A: As commented, this is now fixed (since pandas 0.14):
In [11]: df[df.a == 'test & test']
Out[11]:
             a  b
4  test & test  5

In [12]: store.select('test', 'a="test & test"')
Out[12]:
             a  b
4  test & test  5

A: In my opinion h5py is a much more robust python module for HDF5 files than pandas.
http://www.h5py.org/


text:
Q: matplotlib.animation over a list I am new with matplotlib and I am trying to make an animation of a list of grib files.
I wrote this code:
import pygrib
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import os
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
          lat_0=0, lon_0=-130)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
for grib in os.listdir("path"):
    grbs=pygrib.open(grib)
    for grb in grbs:
        print grb
    lats, lons = grb.latlons()
    data=grb.values
    x, y = m(lons,lats)
norm=colors.LogNorm())
    m.drawcoastlines()
    m.drawcountries()
    m.fillcontinents(color = 'gray')
    m.drawmapboundary()
    m.drawmeridians(np.arange(0, 360, 30))
    m.drawparallels(np.arange(-90, 90, 30))
    cmap = plt.get_cmap('YlOrBr')
    cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
    plt.colorbar(cs,orientation='vertical', shrink=0.3)
    plt.show()

and it works opening a windows that I have to close and after this opening a new one.
I want to use a nice animation with matplotlib.animation : i would change the grib over a map and showing it as a time series.
I try this:
m = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
          lat_0=0, lon_0=-130)

m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary()
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
#reading the gribs files

griblist = os.listdir("path")

def animate (i):
    global griblist
    for grib in griblist:
        grbs=pygrib.open(grib)
        for grb in grbs:
            grb
        lats, lons = grb.latlons()
        x, y = m(lons, lats)
        data = grb.values
        cmap = plt.get_cmap('YlOrBr')
        cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
        plt.colorbar(cs,orientation='vertical', shrink=0.5)
        plt.title('UV biological effective dose')

anim = animation.FuncAnimation(plt.gcf(), animate,
                               frames=len(os.listdir("/home/gloria/UV_CAMS")), interval=500, blit=True)

plt.show()

But I got this error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
    return self.func(*args)
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 590, in callit
    func(*args)
  File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 373, in idle_draw
    self.draw()
  File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 354, in draw
    FigureCanvasAgg.draw(self)
  File "/usr/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 474, in draw
    self.figure.draw(self.renderer)
  File "/usr/lib/python2.7/dist-packages/matplotlib/artist.py", line 61, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/figure.py", line 1165, in draw
    self.canvas.draw_event(renderer)
  File "/usr/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1809, in draw_event
    self.callbacks.process(s, event)
  File "/usr/lib/python2.7/dist-packages/matplotlib/cbook.py", line 563, in process
    proxy(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/cbook.py", line 430, in __call__
    return mtd(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 648, in _start
    self._init_draw()
  File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 1193, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
  File "/usr/lib/python2.7/dist-packages/matplotlib/animation.py", line 1214, in _draw_frame
    for a in self._drawn_artists:
TypeError: 'NoneType' object is not iterable

What I got if that I need to tell Python to iterate thought some variable using the function animate().
I am not fluent with defining functions and I am stuck in this part of the code: I cannot understand where my code is wrong...
Some help about this?
Many thanks!!

A: To get rid of the error, set blit=False.
Apart the animation would currently not animate anything because for each frame you loop over all files. Instead you want to show one file per frame.
griblist = os.listdir("path")

def animate (i):
    grib = griblist[i]
    grbs=pygrib.open(grib)
    lats, lons = grb.latlons()
    x, y = m(lons, lats)
    data = grb.values
    cmap = plt.get_cmap('YlOrBr')
    cs = m.pcolormesh(x,y,data,shading='flat',cmap=cmap)
    plt.colorbar(cs,orientation='vertical', shrink=0.5)
    plt.title('UV biological effective dose')

anim = animation.FuncAnimation(plt.gcf(), animate,
                               frames=len(griblist), interval=500)

plt.show()


text:
Q: adding a dynamic Table to an pdf template I'm using the following Java code to fill an pdf Template with itext
    PdfReader pdfTemplate = getPdfReader(templateFile);
    PdfStamper stamper = new PdfStamper(pdfTemplate, writer);
    stamper.getAcroFields().setField("#ID", "1");
    stamper.getAcroFields().setField("#value", "27");
    stamper.getAcroFields().setField("#valuexxx", "99");
    stamper.setFormFlattening(true);
// TODO Dynamic Table
    stamper.close();
    pdfTemplate.close();

an now my problem:
I would replace an textfield in the PDF with a Table dynamic length.
I've tryed
    float[] fieldPosition= pdfTemplate.getAcroFields().getFieldPositions("tableField");
    PdfPTable table = buildTable();
    PdfContentByte cb = stamper.getOverContent(1);
    table.writeSelectedRows(0, -1, fieldPosition[1],fieldPosition[4],cb);

this works fine but when after the field is some content the table "overides it",
the secound problem is when the table has more rows than the page can hold.
Has someone a good idea how to realy replace a field and rebuild the following document?


text:
Q: How can I ensure that friends with iPhones send me SMS/text instead of iMessages? I have an android phone and normally use the Google Messages app for sending and receiving SMS.
Yesterday, I used the macOS Messages.app app for the first time to send a friend a link.  I guess they have an iPhone, because now when they text me it comes to Messages.app instead of to my phone.  I'm assuming this will be the same for all other iOS users.
How do I prevent all Messages.app and iOS Messages users from sending me NON-SMS messages?  Thinks I have tried:

*

*Closing Messages.app.  I still get macOS notifications of messages.

*In Messages > Preferences… > Accounts > [my email address], untick "Enable this account".  Then my friends messages disappear and I never see them at all, at least until I reenable in Messages.app.

*Looking in System Preferences and on icloud.com and appleid.apple.com to see if there is some setting I can disable—but I've not found anything relevant.

*Using Apple's Deregister iMessage tool to unregister my mobile number.  When I attempted this it gave me the message "Your phone number is not registered with iMessage."

This question was closed as a duplicate of Removing phone number from iMessage, but as noted my phone number is not registered with iMessage, so that question is not relevant.
Am I doomed to never receive SMS from iPhone users ever again?

A: You may not have to do anything except deregister your cellular number from messages.

*

*https://selfsolve.apple.com/deregister-imessage/
At that point, if people send you messages to your Apple ID they won't deliver if you sign out of the app on any remaining Apple OS devices.


text:
Q: How can I build a wrapper to wait for listening on a port? I am looking for a way of programmatically testing a script written with the asyncore Python module. My test consists of launching the script in question -- if a TCP listen socket is opened, the test passes. Otherwise, if the script dies before getting to that point, the test fails.
The purpose of this is knowing if a nightly build works (at least up to a point) or not.
I was thinking the best way to test would be to launch the script in some kind of sandbox wrapper which waits for a socket request. I don't care about actually listening for anything on that port, just intercepting the request and using that as an indication that my test passed.
I think it would be preferable to intercept the open socket request, rather than polling at set intervals (I hate polling!). But I'm a bit out of my depths as far as how exactly to do this.
Can I do this with a shell script? Or perhaps I need to override the asyncore module at the Python level?
Thanks in advance,
- B

A: This felt like code-golf:
#!/bin/sh
# iamwaiting: run a command for a specified time then kill it
# returns the status of cmd on normal termination

opath=$PATH
PATH=/bin:/usr:/bin

SIGNAL=
case $1 in
    -*) SIGNAL=$1; shift;;
esac

case $# in
    0|1) echo 'usage iamwaiting [-signal] wait cmd [args]' 1>&2; exit 2;;
esac

wait=$1 ; shift

PATH=$opath "$@" &
child=$!

# unfortunately, this script takes at least wait seconds to run
sleep $wait

if kill ${SIGNAL:--2} $child 2> /dev/null ; then
    echo "iamwaiting timeout after $wait seconds: $@" 1>&2
    exit 1
else
    wait $child
    exit $?
fi

runs thusly:
$ iamwaiting  5 dd if=/dev/zero of=/dev/null count=5
5+0 records in
5+0 records out
2560 bytes (2.6 kB) copied, 2.0973e-05 s, 122 MB/s
$ echo $?
0
$ iamwaiting -9 5 dd if=/dev/zero of=/dev/null
iamwaiting timeout after 5 seconds: dd if=/dev/zero of=/dev/null
$ echo $?
1
$ iamwaiting 1 cat /dev/does-not-exist
cat: /dev/does-not-exist: No such file or directory
$ echo $?
1

I'd be wary of testing asyncore programs with asynchore routines, but I'm superstitious that way.

A: Another option is to mock the socket module before importing the asyncore module. Of course, then you have to make sure that the mock works properly first.


text:
Q: How do i make my code in kotlin read data from the firebase firestore I am trying to make an app that reads data from the firebase firestore and then shows in a screen that same data
The problem the data only appears when shown in log but i want the in text(string)
Can anyone help me understand how to do it
I already tried many videos explaining but none of then work so my last option is really ask in here for help.
Here is the code
@SuppressLint("UnrememberedMutableState")
@Composable
fun DB () {
    val db = Firebase.firestore
    val collectionReference = db.collection("Inventário")
        .document("Bloco E")
        .collection("Sala E0.05")

    val data = mutableStateOf(mapOf<String, Any>())
    val job = remember { Job() }

    remember {
        GlobalScope.launch(Dispatchers.Main) {
            val documentSnapshot = collectionReference.document("Computador").get().await()
            try {
                data.value = documentSnapshot.data ?: mapOf()
            }catch (e: Exception){
                Log.e("Firestore", "Error retrieving data", e)
            }

        }
    }

    Column() {
        data.value.forEach { (key, value) ->
            Text("$key: $value")}
    }
}

And here is the database structure:

A: It seems like you forgot to use remember on your MutableState (and also suppressed the lint warning with (@SuppressLint("UnrememberedMutableState"))):
val (data, setData) = remember { mutableStateOf(mapOf<String, Any>()) }

Also, using GlobalScope in Android is not recommended. Consider using a LaunchedEffect instead:
@Composable
fun DB () {
    val db = Firebase.firestore
    val collectionReference = db.collection("Inventário")
        .document("Bloco E")
        .collection("Sala E0.05")

    val (data, setData) = remember { mutableStateOf(mapOf<String, Any>()) }

    LaunchedEffect(collectionReference) {
        try {
          val documentSnapshot = collectionReference.document("Computador").get().await()
          setData(documentSnapshot.data ?: mapOf())
        } catch (e: Exception) {
          Log.e("Firestore", "Error retrieving data", e)
        }
    }

    Column() {
        data.value.forEach { (key, value) ->
            Text("$key: $value")}
    }
}


text:
Q: file upload using phpSmug I am working on an app that will upload images to my smugmug account. I am using phpSmug 3.4 and the following code:
require_once( "phpSmug.php" );

    try {
        //assign Variable to smugmug
        $f = new phpSmug("APIKey=*****************", "AppName=Test/1.0");
        // Login Anonymously
        $f->login();

            $f->images_upload("AlbumID=2282300", "File=TestPic.jpg");

    }
    catch ( Exception $e ) {
        echo "{$e->getMessage()} (Error Code: {$e->getCode()})";
    }

?>
but I get back:
      SmugMug API Error for method image_upload: missing required parameter (Error Code: 22)
Do I have to use Oauth to upload? or can it be done anonymously? or is my syntax wrong?
any help is appreciated... Thanks
I also asked the question on the smugmug stack exchange so
if this is not appropriate here, I apologize..

A: As the author of phpSmug, I can tell you your problem and solution is simple: you can't upload images to Smugmug anonymously. You need to login using one of the identifying authentication methods supported by SmugMug and implemented in phpSmug.

A: My fault...was not working from my localhost, works fine on server


text:
Q: .NET Core Informix multiple parameters in IfxCommand This is the environment I work in:

*

*.NET Core 3.1 (console application for testing purposes)

*CSDK 4.50.FC5

*Informix.Net.Core.dll from the CSDK 4.50.FC5 package

*Informix Server 12.10

The problem I have is that some of the queries from my .NET Core app are executed successfully and results are retrieved from the Informix database, but sometimes I get weird errors that have to do something with parameters. Of course, I am trying to use IfxParameters in order to be safe from SQL Injection attacks.

*

*This passes succesfully (table names and columns are made up). Here I am using positional parameters:

IfxCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM employees WHERE name LIKE '%John%' SKIP ? LIMIT ?";

IfxParameter paramSkip = new IfxParameter("skip", IfxType.Integer);
paramSkip.Value = 30;
command.Parameters.Add(paramSkip);

IfxParameter paramLimit = new IfxParameter("limit", IfxType.Integer);
paramLimit.Value = 10;
command.Parameters.Add(paramLimit);

connection.Open();
using (IfxDataReader reader = command.ExecuteReader())
{
    ... // reading data from the IfxDataReader
}

*Let's see now this example which produces an error:

IfxCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM employees WHERE name LIKE ? SKIP 10 LIMIT ?";

IfxParameter paramSearch = new IfxParameter("searchQuery", IfxType.VarChar);
paramSearch.Value = "%John%";
command.Parameters.Add(paramSearch);

IfxParameter paramLimit = new IfxParameter("limit", IfxType.Integer);
paramLimit.Value = 10;
command.Parameters.Add(paramLimit);

con.Open();
using (IfxDataReader reader = command.ExecuteReader())
{
    ...
}

Error:
IfxException: ERROR [22018] [Informix][Informix ODBC Driver][Informix]A character to numeric conversion process failed
The only difference here is that I have parameters that are not of the same type. In the first example both parameters were IfxType.Integer, and now I have IfxType.Integer and IfxType.VarChar

*Using named parameters doesn't help. For the following IfxCommand:

command.CommandText = "SELECT * FROM employees WHERE name LIKE '%John%' SKIP 10 LIMIT @limit";

I get the following error:
Error: IfxException: ERROR [42000] [Informix][Informix ODBC Driver][Informix]A syntax error has occurred.
I hope someone will be able to point me in the right direction in order to solve this issue. I am open to any suggestion that will solve this. If any further info is needed, please hit me up!

A: This is because of the precedence of positional parameters. "where" parameters have lower precedence than "skip" and "limit". Therefore, create the "where IfxParameter" parameters (paramSearch) at the end.
Try:
IfxCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM employees WHERE name LIKE ? SKIP 10 LIMIT ?";

IfxParameter paramLimit = new IfxParameter("limit", IfxType.Integer);
paramLimit.Value = 10;
command.Parameters.Add(paramLimit);

IfxParameter paramSearch = new IfxParameter("searchQuery", IfxType.VarChar);
paramSearch.Value = "%John%";
command.Parameters.Add(paramSearch);

...


text:
Q: JBoss 7: JNDI lookup after quite a while I made the remote access to a stateless EJB run under JBoss 7.1.1. using Properties object:
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,
    "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.PROVIDER_URL,"remote://localhost:4447");
jndiProps.put(Context.SECURITY_PRINCIPAL, "remote");
jndiProps.put(Context.SECURITY_CREDENTIALS, "remotepwd");
jndiProps.put("jboss.naming.client.ejb.context", true);
Context ctx = new InitialContext(jndiProps);

String lookupString = "//HelloWorld/HelloWorldBean!org.acme.test.HelloWorld";
HelloWorld hw = (HelloWorld) ctx.lookup(lookupString);
System.out.println("Response: "+ hw.sayHello("Hi there"));

So this works fine but now I want to put the JNDI thing into jndi.properties file but failed, this is how the file looks like:
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.provider.url=remote://localhost:4447
java.naming.security.principal=remote
java.naming.security.credentials=remotepwd

The exception:
Exception in thread "main" java.lang.IllegalStateException: No EJB receiver available for handling [appName:,modulename:HelloWorld,distinctname:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext@108c175
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:584)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:119)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:136)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
at $Proxy0.sayHello(Unknown Source)
at de.brockhaus.test.client.TestClient.main(TestClient.java:35)

I already went through several doco but failed, so how does it have to look like then?

A: OK, so I found the answer myself ...
First you need to have two properties files, jndi.properties plus jboss-ejb-client.properties.
jndi.properties:
#
# jndi.properties
#
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.provider.url=remote://localhost:4447
java.naming.security.principal=remote
java.naming.security.credentials=remotepwd

jboss-ejb-client.properties:
#
# jboss-ejb-client.properties
#
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false

Having both of them on the classpath will make the code run like a charm even without specifying the properties within the code.
Still confusing is the construction of the lookup string ...


text:
Q: How to show the original image in galleria jquery library I want images to display in their original size, not stretched. How? How can I disable that.
Anyone who knows the solution please help me.

A: max_scale_ratio

*

*type: Number

*default: undefined

*Sets the maximum scale ratio for images. F.ex, if you don't want Galleria to upscale any images, set this to 1.

*undefined will allow any scaling of the images.


text:
Q: oauth facebook api access token misses tagged photos When I fetch tagged photos for a user I only get a certain set even after requesting the friend_photos_videos/user_photos/user_photos_videos tags and basically any other permissions list.
However doing a sample call from the fb oauth overview site gives me the entire list of tagged photos for myself with their generated access token...how is this possible?
Just wondering if anyone else has the same issue.


text:
Q: Generate a sequence of all cases There is a sequence of numbers that satisfies
$a_1=2$, $a_n-a_{n-1}\in \{1,3,5\}$

I tried to enumerate all possibilities using the code below
n = 3;
NestList[Join @@ Outer[Plus, #, {1, 3, 5}] &, {{2}}, n - 1]

{{{2}}, {{3, 5, 7}}, {{4, 6, 8}, {6, 8, 10}, {8, 10, 12}}}

Now I hope to get such a list, is there an easy way?

{{2,3,4},{2,3,6},{2,3,8},{2,5,6},{2,5,8},{2,5,10},{2,7,8},{2,7,10},{2,7,12}}

A: Accumulate /@ Prepend[2] /@ Tuples[{1, 3, 5}, 2]

{{2, 3, 4}, {2, 3, 6}, {2, 3, 8}, {2, 5, 6}, {2, 5, 8}, {2, 5, 10}, >
  {2, 7, 8}, {2, 7, 10}, {2, 7, 12}}

And, for fun:
ng = NestGraph[{1, 3, 5} + # &, 2, 2, VertexLabels -> Automatic]

root = 2;
sinks = VertexList[ng, _?(VertexOutDegree[ng, #] == 0 &)];

Join @@ (FindPath[ng, ##, Infinity, All] & @@@ Thread[{root, sinks}])

{{2, 3, 4}, {2, 5, 6}, {2, 3, 6}, {2, 7, 8}, {2, 5, 8}, {2, 3, 8},
 {2, 7, 10}, {2, 5, 10}, {2, 7, 12}}

A: FoldList[Plus, 2, #] & /@ Tuples[{1, 3, 5}, 2]


text:
Q: Ambiguity between methods of calculating quartiles. Which method is more correct? I am having confusion between two methods of calculating the first quartiles.
Let me explain by an example:
$A = [1,2,3,4,5]$
The method that I know:
To find the first quartile in the list above I first find the median = $3$ that is the 3rd element.
Now I split the list in the following fashion:
$(1,2)$
$3$
$(4,5)$
Now we take the list $(1,2)$ and we find the media between them that is $(1+2)/2 = 1.5$.
So according to my calculation the first quartile $Q_1 = 1.5$.
The nearest rank method(Found here)
$ n = \lceil\frac{P}{100} \times N\rceil$
So for the above list the $0.25$ percentile or the first quartile $Q_1$ will be
$\lceil \frac{25}{100} \times {5} \rceil = 2$
which is 2nd position.
So which is correct $1.5$ or $2$ ? Or does chosing any of them is fine ?
If I am correct in my original calculation why am I getting a difference between the 2 methods.
This different from this question since my question involves in understanding which method is more correct.

A: According to this page and many other pages, the first quartile is defined as the middle number of the lower half of the data set.
However, the meaning of 'lower half' is ambiguous. This is because in the situation where there is an odd number of data points, dividing by half will give a number which is not an integer. Therefore, one method excludes the median (a set of $\lfloor{\frac{n}{2}}\rfloor$ numbers), and another method includes the median (a set of $\lceil{\frac{n}{2}}\rceil$ numbers).
From what I have seen, the first method is by far the most common method, so what you are doing is not wrong. This is because the method taught in the classroom teaches from a more theoretical perspectives, and so the data sets are small to facilitate computation.
Method 2 seems to be more useful in applied mathematics, such as when you have a large dataset. In this case, there is a finer distinction between the $25$th percentile and the $26$th percentile, so in this case calculating the exact $25$th percentile would give a different answer.
And of course, when there are an even number of data points, there is no ambiguity, so both methods give the same result.