Change mimetype for VSC Jupyter Notebook ouput

Question: I'd like to change the output format in VSC from html to plain. I notice I can do this for individual cell as below, but I wonder if I can change the settings.json for the entire file. I'm using Jupyter Notebook.
Comment: Same question here. Did you figure it out by any chance?
Comment: Hi @shkelda, unfortunately no
Answer: From the vscode notebook console
click "customize notebook layout"
click "editting settings.json"
you should see something like this:
{"workbench.colorTheme": "Default Dark+",
"editor.fontSize": 16,
"notebook.lineNumbers": "on",
"notebook.output.textLineLimit": 50,
"notebook.editorOptionsCustomizations": null,
"terminal.integrated.inheritEnv": false,
"notebook.displayOrder": ["image/png", "text/plain"]}

Update the last line with your prefered order of output format.


Remove column name suffix from DataFrame Python

Question: I have the following pandas DataFrame in python:

attr_x
header
example_x
other

3232
322
abv
ideo

342
123213
ffee
iie

232
873213
ffue
iie

333
4534
ffpo
iieu

I want to remove the suffixes '_x' from all columns containing it. The original DataFrame is much longer. Example result:

attr
header
example
other

3232
322
abv
ideo

342
123213
ffee
iie

232
873213
ffue
iie

333
4534
ffpo
iieu
Answer: Use str.removesuffix:
df.columns = df.columns.str.removesuffix("_x")

Or replace:
df.columns = df.columns.str.replace(r'_x$', '')

Comment: This for python 3.10 I believe


How to return a value to another function

Question: I cannot seem to figure out how to make this work any help would be greatly appreciated as i have been trying for days :(
#include <iostream>
#include <math.h>

using namespace std;

int input;
int sum;
int number1;
int number2;
int number3;

void isArmstrong (int input, int sum)
{
    if (input == sum)
        cout << input << " is an Armstrong number" << endl;

    if (input != sum)
        cout << input << " is not an Armstrong number" << endl;
}

cubeOfDigits does not return input and sum to isArmstrong, (return input,sum) error is as follows: expression result unused [-Wunused-value]
int cubeOfDigits (int input, int sum, int number1, int number2, int number3)
{
    cout << "Enter an integer between 0-999" << endl;
    cin >> input;

    number1 = input / 100;
    number2 = input % 100;
    number3 = number2 % 10;

    sum = pow(number1, 3) + pow(number2, 3) + pow(number3, 3);

    isArmstrong(input, sum);

    return input,sum;
}

main calls cubeOfDigits
int main(void)
{
    cout << "Welcome" << endl;

    cubeOfDigits(input, sum, number1, number2, number3);

    return 0;
}

Comment: `return input,sum;` will not work. You can only return 1 value and the comma operator does not work this way.
Comment: Give the function a return type instead of `void`, e.g.: `bool isArmstrong(int input, int sum)`
Comment: Also get rid of all the global variables.
Comment: _cubeOfDigits does not return input and sum to isArmstrong_  - `cubeOfDigits()` cannot "return" something to `isArmstrong()` because it *calls* `isArmstrong()` while *passing* arguments `input` and `sum` to it. You make it sound as if it should be the other way around.
Answer: change the cubeofdigits function from (int) cubeofdigits to (void) cubeofdigits and then remove the return statement from the end of cubeofdigits function .then it must work.
Answer: I think what you intended was..
#include <iostream>
#include <math.h>

using namespace std;

int input;
int sum;
int number1;
int number2;
int number3;

void isArmstrong(int input, int sum){

if(input == sum)
cout << input << " is an Armstrong number" << endl;
if(input != sum)
cout << input << " is not an Armstrong number" << endl;

}

int cubeOfDigits (int input)
{

number1 = input/100;
number2 = input % 100;
number3 = number2 % 10;
number2 = number2/10;
sum = pow(number1,3) + pow(number2,3) + pow(number3,3);

return sum;

}

int main(void){
cout << "Welcome" << endl;
cout << "Enter an integer between 0-999" << endl;
cin >> input;
isArmstrong(input,cubeOfDigits(input));
return 0;

}


Where is the best place for demon hunting? (kill 100,000 demons achievement)

Question: The Hunter or Hunted achievement requires you to kill 100,000 demons. Where is the best place for demon hunting?
It is not about experience/time efficiency; it is just about getting the highest possible count of demon kills in a single run.
Answer: Act 4, Quest 1.
When you fight Iskatu, there will be lots of these tiny black demons. Just take some Thorns equipment and start the game there on Normal. Let them hit you, kill em with thorns, restart.
Each time there are approximately 350 of these demons
Answer: Most of Act IV consists of Demon classified creatures.  The suggestion to farm Act IV Quest I is appropriate, however you should probably use Blackthorn's set to gain immunity from Molten or have sufficient health regeneration to accommodate it being layered on you while you stand still (if simply afk farming the demons).
I propose however that you run all of Act IV or run Act IV bounties to complete this achievement since you will also gain the Act IV caches which may contain a ring of royal grandeur (which is why people farm Act I caches).
You're certain to gain a number of levels, gems, etc with this method as opposed to the mindless farming which requires nearly 300 game resets (based on 350 small demons).
If you can pull this off in Torment 1 efficiently you should also be able to simultaneously farm a number of keys towards your Hellfire crafting requirements.
Answer: My opinion: Act III from The Breached Keep to Siegebreaker inclusive.
Or only The Breached Keep.
More variants on Battle.net forums with kill/min statistics.
Comment: The link is for exp/hour routes, leveling routes, the question is about slaying demons only.
Comment: @givanse the link is for kill/min too, take a closer look
Comment: Those are impressive and pretty useful stats. Still no demon specific runs.
Answer: war that time forgot. its in the battlefields of eternity. kill the angel and stand in the starting point by the "time lock" and let the demon captain summon his unlimited timelost demonic marauders. make sure your xbox autoshut off is not on.


Is my proof for this lemma of gcd correct?

Question: I have to prove the following lemma: $\gcd(ab,c) =\gcd(a,c)  \gcd(b,c)$
I am using prime factorization to proof this lemma.
We have $a,b,c\in \mathbb N$
Let the prime factorizations of $a,b,c$ be:
$a = p_1^{a_1}p_2^{a_2}\cdots p_n^{a_n}$
$b = p_1^{b_1}p_2^{b_2}\cdots p_n^{b_n}$
$c = p_1^{c_1}p_2^{c_2}\cdots p_n^{c_n}$
$p_i,a_i,b_i,c_i \in \mathbb N$
I. $ \gcd(ab,c) = p_1^{\min (a_1+b_1,c_1)}p_2^{\min (a_2+b_2,c_2)} \cdots p_n^{\min (a_n+b_n,c_n)}$
II. $gcd(a,c) = p_1^{\min (a_1,c_1)}p_2^{\min (a_2,c_2)} \cdots p_n^{\min (a_n,c_n)}$
III $gcd(b,c) = p_1^{\min (b_1,c_1)}p_2^{\min (b_2,c_2)} \cdots p_n^{\min (b_n,c_n)}$
Now we look at the product $\gcd(a,c)\gcd(b,c)$ which is
$= p_1^{\min (a_1,c_1)}p_1^{{\min} (b_1,c_1)} \cdots p_n^{\min (a_n,c_n)}p_n^{\min (b_n,c_n)}$
$= p_1^{\min (a_1+b_1,c_1)} \cdots p_n^{\min (a_n+b_n,c_n)}$
At Roman I we see how the prime factorization of $\gcd(ab,c)$ looks like. It is the same exponentiation with the added exponents as the product of $\gcd(a,c)$ and $\gcd(b,c)$. Due to this identity $\gcd(ab,c)$ should divide the product of $\gcd(a,c)$ and $\gcd(b,c)$.                            $\blacksquare$
I don't know whether this proof is correct or not. I would like to receive some feedback.
Comment: The equality is not correct, e.g if $\,a=b=c > 1$ then it claims $\,a = (a^2,a) = a\cdot a.\,$ It is true if $\,(a,b,c) = 1.\ $ Double-check the statement of the exercise for the required hypotheses.
Comment: I think you had the correct formatting @Anil but forgot to add the dollar signs! I fixed it for you in the edit I made.
Comment: thank you. I am completely new to mathjax
Comment: No probs! For a new user, you have done extremely well in formatting! Keep it up!
Comment: The last part you product gcd's has some issues. For example: you have $p_1^{\min(a_1,c_1)}p_1^{\min(b_1,c_1)}=p_1^{\min(a_1+b_1,c_1)}$. Let $a_1=1$, $b_1=4$, and $c_1=3$ then for the powers you should have equality $\min(1,3)+\min(4,3)=\min(1+4,3)$ that is $4=3$. You only need to check $p_1^{\min(a_1+b_1,c_1)}$ divides $p_1^{\min(a_1,c_1)}p_1^{\min(b_1,c_1)}$, which is easy by what @Paolo Leonetti said.
Answer: The exponents are not exactly the same. But, in general, given integers $a,b,c\ge 0$, then
$$
\min(a+b,c) \le \min(a,c)+\min(b,c),
$$
from which the claimed divisibility follows.
Comment: Okay I got your point, but this isn't the whole proof is it?
Comment: @Anil This is just the conclusion, the first part of your proof is correct.


Javascript function after ajax call

Question: I'm trying to call to a JavaScript function that is sent in a Ajax call
What is the correct way to execute a JavaScript function returned from an Ajax call?
Let say the script looks like this before the Ajax call

I receive

Here is the code I have now
nav = $('.js-as'),
$content = $('.js-content'),
$status  = $('.js-status'),
$script  = $('.js-script'),

$.ajax({
  url: '/ajax',
  cache: false,
  beforeSend: function() {
      if (isSupported('transition')) $status.removeClass('start done');

      fadeTimer = setTimeout(function() {
          if (isSupported('transition')) $status.addClass('start');
      }, 100); // Avoid fadeTimer() if content already in cache
  },
  success: function(data) {
      if (fadeTimer) clearTimeout(fadeTimer);

      $nav.removeClass('selected');
      stateLink(e, 'active');
      handler(data);
  }
});
handler = function(data) { // Response
  d.title = data.pagetitle;
  $content.html(data.content);
  $script.html(data.script); // my new script
  eval(start()); // execute it
};

UPDATE: Solution
Using jQuery.globalEval solved this issue
Comment: Can you paste your AJAX call and the above code in the same context so we can understand your question more...
Comment: So, what's wrong with your code? What isn't working?
Comment: after ajax call the script changes to console.log('2'); but calling start() return 1
Comment: add `async: false` as an option to your `$.ajax()` call, try it again, and let me know how it goes.
Comment: Debugging 101- remove EVERYTHING except the AJAX call and the data you're getting in and out, and `console.log()` that data from the response and within the handler. Still not sure what your problem is, so remove your top two examples and replace it with your real code that's the problem - in it's barest form :)
Comment: You mean you want to execute data.script
Comment: I rewrote the question to reflect your actual question. Your assumptions about Ajax are wrong. You cannot change the html of a script tag. You need to use [getScript](https://api.jquery.com/jQuery.getScript/) for example instead
Comment: Using jQuery.globalEval solved this issue
Comment: This is a huge security problem in your application. Careful.
Comment: why? I tried also getScript but no success
Answer: Use one function with argument.
Something like that:

So before the AJAX call tou can call start(1) and after the AJAX call you can call start(2)
Comment: Thanks but my purpose is not console log, I mean in genarally, how to change the function that after ajax call the function would do what inside this
Comment: You all misunderstood the question
Answer: var start = function(){
  console.log(1);
}

After ajax calling
start = function(){
  console.log(2);
}
start();
// output "2"

Comment: You all misunderstood the question
Comment: @mplungjan i understand like that: we must replace context of function. If its wrong can you explain?

Javascript function after ajax call


Testimonial slider usability

Question: I'm building a careers/recruiting landing page for a company and 1 of the things we decided should go into the page are some quotes from existing employees. My first inclination was to pull out the 3 strongest quotes and display them along with a photo of the employee in 3 grid cells all in a row, but the quotes themselves are of all different lengths (some kind of lengthy), plus they want to be able to show up to 5 or6 of them (to represent the major areas they're recruiting for), so the grid idea soon got nixed. In order to accommodate all thee quotes, at at all their different lengths, I feel like I'm stuck using a slider.
Now my main issue is how long to play each slide for. If I play each one long enough to read the longest quote, the shortest one will make you wonder if it's broken/stuck. I'm using dots below the slide area to show the total number of slides and which one is currently playing. I can also pause it on hover. AND I added a play/pause toggle to both show that it is in fact paused when hovering (or playing when not) and to allow the user to be able to play/pause it at their leisure... in case they want to ogle at the photo or linger on the words of wisdom of a certain employee.
Right now, it seems like a lot of elements (with the text, the photo, the dots and toggle button), but I think design-wise I can make it work. I'm just not sure if it's worth the time. Personally, I think there is other content on the page that belongs in a slider before these testimonials, but the requirement to accommodate up to 6 quotes (with photos) kind of has my hands tied.
Is the toggle button overkill? Maybe a tooltip on mouseenter and mouseleave displaying the status (playing or paused) would be sufficient? But then that makes it less likely that mobile users will benefit from the ability to control it. i've been thinking myself in circles... wanted to get some input from some experts.
EDIT:
The more showcases I see highlighting well designed sliders, the more manually-navigated (i.e. no autoplay, rather prev & next buttons) sliders I see. I thought I read in more than 1 place that expecting a user to click through your slider was a sure way to have content go unseen. Is this trend changing? or perhaps i am mistaken in what I thought i had learned from solid sources.
After some deliberation and looking a couple dozen more websites using sliders for roughly the same purpose, I am thinking that the best behavior is as follows:

autoplay, previous/next buttons and dots to start with
no toggle
pause on hover - unpause on mouseleave
cancel autoplay as soon as the user clicks a prev/next button or a dot

Thoughts?
Answer: I think the grid idea is the way to go, sliders are good but in this case since you are focusing on 5-6 different areas.
If you show on a slider, users may miss the ones relevant to them unless they take the time to click through all the slides.
With a grid, they can get a clear overview of the 5-6 major areas at a glance.
For example:
https://blog.ongig.com/company-career-site/employee-testimonials/

or:
https://www.aihr.com/blog/employee-testimonial-examples/

Testimonial slider usability


Optimal WP7 bitmap drawing with XNA

Question: I want to display a bitmap on a WP7 in vertical position, but it rotates it 90 degrees and coordinates are in landscape position. Is it possible to make WP7 display everything in vertical mode and make coordinates starting from top left corner in vertical mode? If not, whats the best way to display my bitmaps in vertical mode? Should I rotate my bitmaps when I design them, or should i use rotation in my drawing functions? I use XNA spriteBatch.Draw to draw my bitmaps, but it has some advanced rotation techniques that I don't understand.
Answer: XNA apps are based on the assumption that the game will be displayed in landscape mode. Whether it's easier/better for you to rotate things at design time or when displayign them in the app will depend on various factors, including: what the game does; your preferences; the number of items; the impact on movement calculations; etc...

Optimal WP7 bitmap drawing with XNA


ASP.NET MVC - Job of Controllers

Question: I think I'm beginning to be confused with the job of a controller in MVC.
I have a service that exposes five functions:

list packages in queue
get package
delete package
accept package
deny package

My ASP.NET MVC controller depends on this service, and can generally execute a service call on an Action.  I'm happy so far.
The second part is then building the ViewModel result.  If I do this inside of the controller, the controller now has an exploding dependency list -- each action added increases the dependencies in order to build the view model, and these are all inherited by the controller.  I don't like this very much.  I'm building this controller that depends on N different view model builders, but only using one of them per request.
So I was thinking of pulling all of this out and applying action filters specific to each view model.  I haven't done this yet, but it seems okay.
The question this is raising for me is: what is the responsibility of the controller?  If I end up pulling the view model building into filters, my controller is doing little more than having a route execute a service call (and providing a filter plugin).  If I instead leave my controller responsible for building each view model, it becomes a mess.
It seems like I almost want to instantiate an action per request, not a controller, and I'm just abusing filters to get at that?
Comment: This question is in dire need of some code samples.
Answer: Do you have dedicated ViewModels and Poco-Models? If this is the case you can handle the data from the services  inside the ViewModel.
I am quite happy with this uproach.
public class PackageViewModel()
{
    public PackageDetail{get;set;}
    public int PackageID{get;set;}
    public List<Package>Packages{get;set;}
    public string SomeFilterCriteria{get;set;}

    publlic void FillPackageList(IPackageService packageService)
    {
        Packages = packageService.GetPackages(SomeFilterCriteria);
    }
}

In Controller:
public ViewResult ListPackages(PackageViewModel model)
{
    model.FillPackageList(PackageService);
    return View("ListPackages",model);

}

I dont understand what you mean by "view model builders".
Comment: "View model builders" could be referring to assigning values from a DTO to a viewmodel object. I'm currently doing this in my controllers -- not sure if that's the correct move or not, but the alternative I see is passing a DTO to the constructor of a viewmodel, which I'm not sure is better.
Answer: The controller is supposed to orchestrate all actions you want to occur in your view.  If you pull this logic out into action filters, it's still doing the logic per route request, it's just going to be cleaner in your case.

ASP.NET MVC - Job of Controllers


Should the composer package name in a laravel project be edited?

Question: I'm making a custom application using Laravel. By default Laravel generates a composer.json file like the following:
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
}

Is it good practice to change the name, description, license etc on my project?
More info: I am developing this project for another company. They will use it internally (as a public website) and may or may not hire a different developer in the future.
Comment: You'd only change this if you're going to be offering the application on packagist.
Answer: To be honest, changing it provides no real benefit unless you're planning to release the project as a composer projects that allows people to run composer create-project you/yourproject.
There's no real rule around changing if you plan to keep it internal only, but there are two arguments, one for and one against.

Changing it keeps it simple, and gives developers working on your project a nice little source to some basic information.
Keeping it as the default allows you and other developers to access some basic information about the systems creation.

So ultimately, it's entirely up to you.
Answer: Yes, you should edit it to reflect the current state. At least delete info that you don't want, like the MIT license (you probably don't want to license proprietary code that way), the keywords, description and name.
Maybe in the future, composer create-project will deal with it more properly (the source project needs to have a name to be identifiable, but creating a project almost never needs to keep that name) - but this also won't help you with existing projects.
Keep that meta data correct (at least delete incorrect data) - you never know the benefits. Personally, I hugely like having the right project names because that name gets displayed on my Satis pages as "projects using this package", i.e. the reverse dependency - so I know what to update if I change a library.
Comment: The second paragraph answers the question best for me, I was not sure if projects should keep the same info as the source project. The code will be proprietary and I am developing this for another company so it's probably good to have my name and my company name in it.


D3 color change on mouseover using classed("active",true)

Question: I'm new to js and D3.  I've generated a heatmap of-sorts and would like to change the color of a tile using D3's on.mouseover.  I'm able to change the color explicitly but want to use a CSS active rule.  Probably something simple to fix.  Any help would be greatly appreciated.  The full code is below.
Thanks.
<!DOCTYPE html>
<meta charset="utf-8">

<title>MJ-Heatmap</title>

Country By District_Port_Nme Heatmap

Answer: EDIT
First off, you were right that your CSS is slightly off.
.tile active {
  fill: red;
}

should be:
.tile.active {
  fill: red;
}

Then, sort of like I explained below, the fill you're applying to the element with
.style("fill", function(d) { return z(d.count_shipments); })

ends up taking precedence over the fill applied by the active class.
However, unlike what I initially suggested, you can work around it by simply swapping style with attr, so you need:
.attr("fill", function(d) { return z(d.count_shipments); })

(probably should do this for stroke as well).
Here's an updated, working jsFiddle

ORIGINAL POST
I suspect it works the way it should –– i.e. class "active" with its associated fill is being added/removed appropriately –– and you'd be able to verify this by right-clicking and inspecting the element in dev tools.
I think the real problem is that you're also setting a fill directly on the element (one line before your .on("mouseover"...) call), which ALWAYS overrides the fill applied by your class. Generally in CSS you could (not saying you should) use the !important keyword to force it to accept the fill applied by the class. But I'm pretty sure that won't work with SVG (as opposed to normal HTML elements).
So, I think your only option is:
.style("fill", function(d) { return z(d.count_shipments); })
.on("mouseover", function() {
  d3.select(this)
    .attr('fill', '') // Un-sets the "explicit" fill (might need to be null instead of '')
    .classed("active", true ) // should then accept fill from CSS
})
.on("mouseout",  function() {
  d3.select(this)
    .classed("active", false)
    .attr('fill', function(d) { return z(d.count_shipments); }) // Re-sets the "explicit" fill
  });

Hope this works....
Comment: Thank God you answered this post ... It works for me ... you saved me ... thankyou thankyou :)
Comment: Thanks for help.  This didn't work either on my end.  I'm wondering if there's a newbie mistake in my CSS rule or how I reference it.


SQL SELECT using a variable condition after WHERE

Question: I am using ASP.NET with the Webpages model and have created a database for users to post to, which is all great, then I created a page so users can edit their posts, however I want it so users can only edit their own posts.
To do this, I tried the following:
I made a variable
var EmailMatch = WebSecurity.CurrentUserName;

so if I put @EmailMatch anywhere in the html markup it will display the email address of the user who is currently logged in.  Now in order to display only the posts that this user has made, I used this select statement:
var selectAllString = "SELECT * FROM SaleData WHERE Email = '@EmailMatch'";

In theory I am thinking this should work, because when the user makes a post it sends their email address to the database under the field 'Email' and it should display records that are equal to the user currently logged in.  However this statement returns 0 results, I have tried all I can think of with no success, this is my last resort, can someone please tell me what I am missing? Thanks in advance..
Answer: The correct way to do this is through parameterized queries.  Never ever concat strings that you do not have control over in to a query.
var EmailMatch = WebSecurity.CurrentUserName;
var selectAllString = "SELECT * FROM SaleData WHERE Email = @EmailMatch";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("@EmailMatch", EmailMatch);
var resultsTable = cmd.ExecuteReader();

Comment: The relevant point here being that you don't need quotes around '@EmailMatch'
Comment: @MichaelBray - you are absolutely correct -  I should have mentioned that in my answer.
Comment: thank you for your prompt reply, but this code is giving me this error that im not familiar with: 'CS0246: The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)'
Comment: @Ben - it will be located in the System.Data.SqlClient namespace - this is for SQL Server.  For other DBs, use the SqlCommand provided in the dll provided
Answer: var selectAllString = "SELECT * FROM SaleData WHERE Email = '" + EmailMatch + "'";

Note: This could possibly expose you to SQL Injection attacks.
Answer: Try this:
var selectAllString = "SELECT * FROM SaleData WHERE Email = '"+EmailMatch+"'";

or to avoid SQL Injecton, your SQL statement is correct but you have to add this in your code:
using (OleDbConnection CON = new OleDbConnection("your connection string")) {
   OleDbCommand Com = CON.CreateCommand();
   Com.CommandText = "SELECT * FROM SaleData WHERE Email = @EmailMatch";
        Com.CommandType = CommandType.Text;
        Com.CommandTimeout = 0;
        Com.Connection.Open();
        Com.Parameters.AddWithValue("EmailMatch",EmailMatch);
   ...
   // continue your code from here...
}

Comment: Your command type is StoredProcedure, yet you are providing an sql select statement.  your command type should be CommandType.Text
Comment: the code that leaves me at risk of sql injection works, but yes, leaves the site open.. when i tried to add the extra code it returned this error:  'CS0246: The type or namespace name 'OleDbConnection' could not be found (are you missing a using directive or an assembly reference?)'
Comment: what data provider are you using? OleDbConnection can be used if you are using MSAccess or MSSQL
Comment: add this reference `using System.Data.OleDb`
Comment: I pretty sure I'm using MSSQL, whichever goes with Webmatrix 2.. Sorry, I am a beginner with this, all these answers are very different and it's hard to follow the logic. I still can't get it to work, I need to do more research I guess, thank you for your help.
Answer: cmd = new MySqlCommand("SELECT * FROM SaleData WHERE Email = @EmailMatch", MySqlConn.conn);
cmd.Parameters.AddWithValue("@EmailMatch", EmailMatch);
cmd.Prepare();
cmd.ExecuteReader();

Comment: thanks, but this code tells me an error: 'CS0103: The name 'cmd' does not exist in the current context'


User input in Java versus python

Question: Again problem with understanding Java. When I asked previous question about Hello world in Java versus python, I received suggestion of taking the language as granted for a while till I don't get hang of it. However, I cannot take that approach and is baffled by some weird things in Java versus python.
Here is the program which takes input from user and convert F to degree Celsius in python.
def main ():
 fahr = input (" Enter the temperature in F: ")
 cel = ( fahr - 32) * 5.0/9.0
 print " the temperature in C is : " , cel

This is pretty straightforward without any quirky things going on inside.
The example to do the same thing in Java:
import java . util . Scanner ;

 public class TempConv {
 public static void main ( String [] args ) {
 Double fahr ;
 Double cel ;
 Scanner in ;

 in = new Scanner ( System . in );
 System . out . println (" Enter the temperature in F: " );
 fahr = in . nextDouble ();

 cel = ( fahr - 32) * 5.0/9.0;
 System . out . println (" The temperature in C is : " + cel );

 System . exit (0);
 }

 }

What I thought should happen was: Scanner was Java class/instance of class/object to take user input and with
Scanner in

created a new object to take user input. It turns out to be we are just declaring in to be of Scanner type in Java (Correct me if I am wrong).
Now, if it was python, we would have just called the method of the newly created Scanner object that takes input from the user. OMG, what is this in Java? We create

new Scanner

object  and pass System.in as a parameter and assign it to

in

again?
Can somebody please explain to me in pythonic terms, What is happening here and how and why it should differ from python so much?
Any creative suggestions are appreciated.
Comment: @Jack_of_All_Trades: This is explained in chapter 1 of Any Java Introduction Text Ever Written.  Show some effort before asking questions.
Comment: @nikhil: I am trying to learn new things here. I would have appreciated a little explanation suggesting why it is meaningless rather than such a rude response.
Answer: Your question is a little garbled, but here's my attempt at an answer.  In Java, just like in Python, you need to instantiate a class before you can call methods on it.  In Python, you might do this:
myvar = MyClass(name="example")

In Java, the syntax is very similar:
in = new Scanner(System.in);

And just like in Python, we can now call methods on it, such as:
fahr = in.nextDouble();

This is just about identical to what the equivalent Python code would look like.  It's possible I'm not understanding the source of your confusion, so if this doesn't help let me know and I'm happy to update things.
Comment: `Scanner` is a class that reads input from a stream (in this case, `System.in`, which is equivalent to Python's `stdin`).  The example is using the `Scanner` class to read a double value from the input. This is roughly equivalent to the `fscanf()` function in C.  See [this documentation](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html) for details about the `Scanner` class.
Comment: Thanks larsks for your answer.
Answer: Think of the object declarations as an implicit assignment of None.  This would be pretty pointless in python, because variables don't have types, but their VALUES do (which is why declaring a variable w/o assigning it a value is pointless).  In Java, when you declare a variable, you make a promise as to what subset of types will be stored therein, and as there might be some code between making that promise and actually having a value to put in there, they are accomplished in separate statements.
Comment: Interesting... you say almost the exact same thing I do, yet I get -2 and you get +1...
Answer: Java is a static typed language, you have to declare the type of a variable before you use it.
Scanner input; //This declare a variable of type Scanner but not assign anything to it yet
input = new Scanner(System.in); // This create a new object of Scanner type and assign it to the variable in

This can be shorten as
Scanner input = new Scanner(System.in);

Assuming we have a Scanner class in Python, the roughly-equivalent code is
input_obj = None
input_obj = Scanner()

Python is dynamic typed language, so you don't need to declare the type. The first line therefore don't serve any purpose, it can be and should be omitted, which result in
input_obj = Scanner()

Answer: I don't think you really understand how programs and computers work.  You can think of it as Scanner in creates a label for a region in memory  named in of the correct size for a Scanner type object, then in = new Scanner() actually creates that object in that location in memory that was previously reserved.  You can think of it as roughly analogous to in = None in = Scanner() in Python, though that's not really quite correct.  The thing is that since Python is loosely typed, it handles all the bookkeeping behind the scenes, thus allowing you to do what is really multiple steps with a single line of code.
Comment: This is the most rude answer I could ever get! What do you mean by that? I am finding the difference in the language I am used to and I am trying to learn so what makes you think that I don't know "how programs and computers work".
Comment: I appreciate your answer but the not the rudeness which you showed while answering. There is a difference between being a talented human being and humble human being. Everybody has some starting point. With little effort, I am sure you can be latter.
Comment: @Jack_of_All_Trades Because your question suggests that you don't.  Do you understand the process of reserving memory and then writing values to it?  When you create a variable in Python, it is more or less a pointer to an arbitrary piece of data whose type is defined when you actually assign a value.  In Java, you have to declare the type of data to be stored at that location ahead of time so that the interpreter can tell the OS how much space it needs, since that is determined at compile time instead of run time.
Comment: You should have firstly considered that I am trying to learn Java and I am used to python where I don't have to worry about memory management. You comments answers itself.
Comment: @Jack_of_All_Trades Java has managed memory too, however, if you don't really understand what is going on under the hood, you can't expect to really get the full value of any language.  Start with the basics, then build on top of that.
Comment: I wrote whole of my MS thesis with MATLAB without knowing what goes under the hood. Choices are different for everybody.
Comment: And therein is the difference between being a scripter and a programmer.  With some effort, you might actually become the later.
Comment: +1 for the correct answer. Your question is something like why do we do something this way in language X and another way in language Y.
These sort of questions aren't constructive, to learn about this the best way is to read any textbook.
All you've done here is start a mini flame war, I think this question should be closed.

User input in Java versus python


Matplotlib: how to specify width of x-label bounding box

Question: I'm trying to create a stacked bar chart in MatPlotLib with two distinct x-labels on top and bottom. The upper one is supposed to have a bounding box with the same width as the bars themselves.
Plot that's not quite right

This is how I create the labels:
plt.tick_params(axis="both", left=False, bottom=False, labelleft=False)
plt.xticks(ind, diagram.keys())
ax.set_frame_on(False)

for label, x in zip([q[1] for q in diagram.values()], ind):
    ax.text(
        x, 1.05, '{:4.0%}'.format(label),
        ha="center", va="center",
        bbox={"facecolor": "blue", "pad": 3}
    )

diagram is a dictionary like {bottom-label: [[contents], top-label]}
So I guess my question boils down to: How do I manipulate the bounding boxs of the text objects?
Thanks a lot!
As per request, a runnable example:
import matplotlib.pyplot as plt
import numpy as np

def stacked_bar_chart(
        diagram, title="example question", img_name="test_image", width=0.7, clusters=None, show_axes=True,
        show_legend=True, show_score=True):
    """
    Builds one or multiple scaled stacked bar charts for grade
    distributions. saves image as png.
    :param show_score: whether the score should be shown on top
    :param show_legend: whether the legend should be shown
    :param show_axes: whether question name should be shown on bottom
    :param clusters: indices of clusters to be displayed.
    :param width: the width of the bars as fraction of available space
    :param title: diagram title
    :param img_name: output path
    :param diagram: dictionary: {x-label: [[grade distribution], score]}
    :return: nothing.
    """

    grades = {
        "sehr gut":     "#357100",
        "gut":          "#7fb96a",
        "befriedigend": "#fdd902",
        "ausreichend":  "#f18d04",
        "mangelhaft":   "#e3540e",
        "ungenügend":   "#882d23"
    }

    # select clusters
    if clusters is not None:
        diagram = {i: diagram[i] for i in clusters}

    # normalize score distribution => sum of votes = 1.0
    normalized = []
    for question in diagram.values():
        s = sum(question[0])
        normalized.append([x / s for x in question[0]])

    # transpose dict values (score distributions) to list of lists
    transformed = list(map(list, zip(*normalized)))

    # input values for diagram generation
    n = len(diagram)  # number of columns
    ind = np.arange(n)  # x values for bar center
    base = [0] * n  # lower bounds for individual color set
    bars = []
    fig, ax = plt.subplots()

    # loop over grades
    for name, grade in zip(grades.keys(), transformed):
        assert len(grade) == n, \
            "something went wrong in plotting grade stack " + img_name
        bar = plt.bar(ind, grade, width=width, color=grades[name], bottom=base)
        bars.append(bar)

        # loop over bars
        for i, (rect, score) in enumerate(zip(bar, grade)):
            # update lower bound for next bar section
            base[i] += grade[i]
            # label with percentage
            # TODO text color white
            ax.text(
                rect.get_x() + width / 2, rect.get_height() / 2 + rect.get_y(), "{0:.0f}%".format(score * 100),
                va="center", ha="center")

    # label diagram

    plt.suptitle(title)
    if show_axes:
        plt.tick_params(axis="both", left=False, bottom=False, labelleft=False)
        plt.xticks(ind, diagram.keys())
        ax.set_frame_on(False)

    else:
        plt.tick_params(axis="both", left=False, bottom=False, labelleft=False, labelbottom=False)
        plt.axis("off")

    # show score label above
    if show_score:
        for label, x in zip([q[1] for q in diagram.values()], ind):
            ax.text(
                x, 1.05, '{:4.0%}'.format(label),
                ha="center", va="center",
                bbox={"facecolor": "blue", "pad": 3}
            )

    # create legend
    if show_legend:
        plt.legend(
            reversed(bars), reversed([*grades]),
            bbox_to_anchor=(1, 1), borderaxespad=0)

    # save file
    plt.show()

diagram = {
    "q1": [[1, 2, 3, 4, 5, 6], 0.6],
    "q2": [[2, 3, 1, 2, 3, 1], 0.4]
}
stacked_bar_chart(diagram)

Comment: This is rather cumbersome, see [this question](https://stackoverflow.com/questions/40796117/how-do-i-make-the-width-of-the-title-box-span-the-entire-plot), which wants to do this for the title box. Of course one may adapt it for the barwidth. On the other hand, one may rather put some text to the axes and draw a rectangle of the required dimensions in the background of it. In which direction would you like to go?
Comment: I'd prefer the former variant. I had already explored the option of drawing rectangles but failed for a reason I can't remember... then again, I'm the one asking for advice so I'm open for whatever you think best.
Comment: I can see what I can do, but would you mind providing a [mcve] (don't use your real data, just something I can copy, paste and run).
Comment: I tried. It's still a bit much, the interesting part is near the comment `# show score label above`
Comment: That is no [mcve]. I created my own to answer the question. Mind that you cannot expect people to this work for you.
Answer: For arguments why setting the width of a text box to a defined width is hard see this question which is about setting the title text box width. In principle the answer over there could be used here as well - making this rather complicated.
A relatively easy solution would be to specify the x-position of the text in data coordinates and its y position in axes coordinates. This allows to create a rectangle as background for the text with the same coordinates such that it looks like a bounding box of the text.
import matplotlib.pyplot as plt
import numpy as np

ind = [1,2,4,5]
data = [4,5,6,4]
perc = np.array(data)/float(np.array(data).sum())
width=0.7
pad = 3 # points

fig, ax = plt.subplots()
bar = ax.bar(ind, data, width=width)

fig.canvas.draw()
for label, x in zip(perc, ind):
    text = ax.text(
        x, 1.00, '{:4.0%}'.format(label),
        ha="center", va="center" , transform=ax.get_xaxis_transform(), zorder=4)
    bb= ax.get_window_extent()
    h = bb.height/fig.dpi
    height = ((text.get_size()+2*pad)/72.)/h
    rect = plt.Rectangle((x-width/2.,1.00-height/2.), width=width, height=height,
                         transform=ax.get_xaxis_transform(), zorder=3,
                         fill=True, facecolor="lightblue", clip_on=False)
    ax.add_patch(rect)

plt.show()

Comment: Thank you so much! that did it.

Though for some reason, probably because I switched to creating the actual bars with pandas in the meantime, I had to use `ax = plt.gca()` and `fig = plt.gcf()` instead of `plt.subplots()` or it would have created to seperate plots.


What does "unsqueeze" do in Pytorch?

Question: The PyTorch documentation says:

Returns a new tensor with a dimension of size one inserted at the specified position. [...]
>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])

Answer: unsqueeze turns an n.d. tensor into an (n+1).d. one by adding an extra dimension of depth 1. However, since it is ambiguous which axis the new dimension should lie across (i.e. in which direction it should be "unsqueezed"), this needs to be specified by the dim argument.
e.g. unsqueeze can be applied to a 2d tensor three different ways:

The resulting unsqueezed tensors have the same information, but the indices used to access them are different.
Comment: I would give a bounty for the highlights. Thank you.
Comment: @iacob - how did you draw this awesome image? in which software?
Answer: If you look at the shape of the array before and after, you see that before it was (4,) and after it is (1, 4) (when second parameter is 0) and (4, 1) (when second parameter is 1). So a 1 was inserted in the shape of the array at axis 0 or 1, depending on the value of the second parameter.
That is opposite of np.squeeze() (nomenclature borrowed from MATLAB) which removes axes of size 1 (singletons).
Answer: It indicates the position on where to add the dimension. torch.unsqueeze adds an additional dimension to the tensor.
So let's say you have a tensor of shape (3), if you add a dimension at the 0 position, it will be of shape (1,3), which means 1 row and 3 columns:

If you have a 2D tensor of shape (2,2) add add an extra dimension at the 0 position, this will result of the tensor having a shape of (1,2,2), which means one channel, 2 rows and 2 columns. If you add at the 1 position, it will be of shape (2,1,2), so it will have 2 channels, 1 row and 2 columns.
If you add at the 1 position, it will be (3,1), which means 3 rows and 1 column.
If you add it at the 2 position, the tensor will be of shape (2,2,1), which means 2 channels, 2 rows and one column.
Answer: Here are the descriptions from the PyTorch docs:

torch.squeeze(input, dim=None, *, out=None) → Tensor
Returns a tensor with all the dimensions of input of size 1 removed.
For example, if input is of shape: (A×1×B×C×1×D) then the out tensor will be of shape: (A×B×C×D) .
When dim is given, a squeeze operation is done only in the given dimension. If input is of shape: (A×1×B) , squeeze(input, 0) leaves the tensor unchanged, but squeeze(input, 1) will squeeze the tensor to the shape (A×B) .

torch.unsqueeze(input, dim) → Tensor
Returns a new tensor with a dimension of size one inserted at the specified position.
The returned tensor shares the same underlying data with this tensor.
A dim value within the range [-input.dim() - 1, input.dim() + 1) can be used. Negative dim will correspond to unsqueeze() applied at dim = dim + input.dim() + 1.
Answer: unsqueeze is a method to change the tensor dimensions, such that operations such as tensor multiplication can be possible. This basically alters the dimension to produce a tensor that has a different dimension.
For example: If you want to multiply your tensor of size(4), with a tensor that has the size (4, N, N) then you'll get an error.
But using the unsqueeze method, you can convert the tensor to size (4,1,1). Now since this has an operand of size 1, you'll be able to multiply both the tensors.

What does "unsqueeze" do in Pytorch?


Adding Profile to Google Analytics using API with C#

Question: I wish to use the method specified here:
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/profiles/insert
I've tried to work it out by looking at some guides here: http://www.daimto.com/google-analytics-api-v3-with-c/ and http://www.arboundy.com/2012/04/getting-started-with-google-analytics-in-c/ but in truth I'm completely lost and can't seem to get close.
Any help would be greatly appreciated.
Thanks.
Comment: I have been trying to get that to work for a while now.  Its not in any of my tutorials because I haven't been able to get it to work.  I just sent an email off to one of the Google Devs, asking him for some info on what we need to send to get it to work.  I tried sending everything I can think of though the Query Explorer and nothing works  https://developers.google.com/apis-explorer/#p/analytics/v3/analytics.management.profiles.insert
Comment: @DaImTo, I've made some progress on this. I'll edit in with some code tomorrow. It seems like the insert function returns an authorization error saying the function is not available. I searched the specifics of the error and it seems that some functions in the api are in beta and you have to be whitelisted for them to work. Will be more precise tomorrow when back in work.
Comment: 2 downvoters and no comment why?
Comment: Downvotes are likely because a) you don't say whats wrong, or ask a specific question b) you don't post your code.
Comment: @user2025312 I was wondering if maybe it was only available to professional GA accounts.   I just think its weird that they don't mention in the documentation that you have to be whitelisted.  If they have a try it section you should be able to try it yet that doesn't work either.   I sent another mail off to the devs asking if you needed to be whitelisted.
Answer: Write operations are still in beta.  Before you can access this feature you need to request access to the beta.

Write operations in the Management API (e.g. create, update, delete,
  patch) for Web Property, View (Profile), and Goal resources is
  currently available as a developer preview in limited beta. If you're
  interested in using these features,  request access to the beta.
Comment: That's the conclusion I had come to aswell, but that's the only page I've seen the whitelisting aspect confirmed. Thanks a lot for the link. I've requested my project to be whitelisted now.
Comment: Let me know if it works :)  BTW it takes around 24 hours to get access to the Real-time API beta.
Comment: @DalmTo - Unfortunately still no response from google yet. Once they reply and I've checked it works I'll probably add an answer here with the full steps I took w/ code and such.
Comment: If its anything like the Real-time API beta, you wont get a reply it will just start working.  Try it.  :)
Comment: Thanks I'll keep trying it. No success yet, I sent a second request through, maybe it'll land in someone elses inbox and go through.


Convergence of a compound sequence

Question: let $a_n=\frac{1}{2}\sqrt{n}+\sum_{k=1}^n(\sqrt{k}-\sqrt{k+\frac{1}{2}})$ be a sequence.
Is this sequence convergent?
Comment: It might be slightly nicer to rewrite it to $$ a_n = \frac12\sum_{k=1}^n \left(3\sqrt k - \Bigl(2\sqrt{k+1/2}+\sqrt{k-1}\Bigr)\right) $$ Then, intuitively, the terms go asymptotically like the second derivative of $\sqrt k$.
Answer: Write $\sqrt{n} = \sum_{k=1}^{n} \left(\sqrt{k}-\sqrt{k-1}\right)$. Then you get:
$$a_n = \sum_{k=1}^{n}\left(\sqrt{k}-\sqrt{k+1/2}+\frac{1}{2}\sqrt{k}-\frac{1}{2}\sqrt{k-1}\right)=\sum_{k=1}^n \left(\frac 3 2\sqrt{k}-\sqrt{k+1/2}-\frac{1}{2}\sqrt{k-1}\right)$$
This represents $a_n$ as a pure series, with $a_n=\sum_{k=1}^{n} b_k$ with $b_k=
\frac 3 2\sqrt{k}-\sqrt{k+1/2}-\frac{1}{2}\sqrt{k-1}$.
Now $$\sqrt{k+1/2}=\sqrt{k}{\sqrt{1+1/(2k)}} = \sqrt{k}+\frac{1}{4\sqrt{k}} + O\left(\frac{1}{k^{3/2}}\right)$$ and similarly $$\sqrt{k-1}=\sqrt{k}-\frac{1}{2\sqrt{k}}+O\left(\frac{1}{k^{3/2}}\right)$$
So you get
$$b_k=\frac 3 2\sqrt{k}-\sqrt{k+1/2}-\frac{1}{2}\sqrt{k-1}=O\left(\frac1{k^{3/2}}\right)$$
So $\sum_{k=1}^{\infty} b_k$ converges, and you are done.
Wolfram alpha gives an exact value of:
$$\frac{(\sqrt2-4) \zeta(3/2)+4 \pi\sqrt 2}{8 \pi}$$

Convergence of a compound sequence


Changing constant variables in C

Question: Why are we able to change constant variables using a pointer, but we can't change a constant string index value using a pointer?
For example,
Case1: Changing constant variables using pointers, this works fine.
int main()
{
    const int var = 10;

    int *ptr = &var;
    *ptr = 12;

    printf("var = %d\n", var); //12

    return 0;
}

Case2: Changing constant string using pointers, this gives compiler error
 int main()
    {
        char * a = "test";//test is in ROM, a is a pointer to its start address in ROM

       a[3] = 'M';//error

        return 0;
    }

Comment: You can't do either. Both invoke Undefined Behaviour. If one crashes and the other transfers the money in your account to my account, all is well in the UB-land. On a full-moon day your program might as well work as you expect :)
Comment: [C11 6.7.3p6](http://port70.net/~nsz/c/c11/n1570.html#6.7.3p6): "If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined"
Comment: Try making `var` a global variable.
Comment: @AhmadAnwar Yes, both are wrong according to the C standard. The first works *in practice only*.
Comment: @AhmadAnwar all local non-static variables are on the stack, so yes. In case 2, the variable `a` is a *pointer* to a string, and this pointer is on the stack. But it points to a string which is in read-only memory.
Comment: However the first one seems to be totally legal, I know its logically wrong, but are BOTH wrong according to c standard?
Comment: "we can" [Says who?](https://ideone.com/wtk8Bq)
Comment: Maybe it works if you use `*(a+3)` instead of `a[3]`
Comment: @dan1st: `*(a + 3)` and `a[3]` are 100% absolutely identical.
Comment: I know. But maybe the compiler does not recognize that you modify the pointer.
Comment: @AhmadAnwar Can you clarify your question?  You said your first program, that attempts to modify a const int, "works fine", but I would expect to get warnings or errors from the compiler, and indeed under my compiler I do.  For the second program, on the other hand, that attempts to modify a string literal, I would expect to get a *run-time* error, not a compiler error (and, again, on my computer, that's exactly what happens).
Comment: @Steve Summit GCC only gave me a warning that a non-const pointer is pointing to const data, however I was able to change the value, in the string case, we can't change any index's value.
Comment: @G.Sliepen The global trick made it un-edit able, can you clarify why?
Comment: @AhmadAnwar Yes, when it's a local variable, it is on the stack, which is always writable. If it's in global memory and const, the compiler will put it in a read-only section.
Comment: @G.Sliepen Wait, so const local variables are in the stack not in a read-only section?
Answer: The both programs are ill-formed and have undefined behavior.
According to the C Standard (6.7.3 Type qualifiers)

6 If an attempt is made to modify an object defined with a
  const-qualified type through use of an lvalue with non-const-qualified
  type, the behavior is undefined.

It seems that the first program produces the expected result only due to the fact that the variable var has automatic storage duration. That is the compiler did not place it in a read-only memory.
All string literals (though in C they have types of non-constant arrays opposite to C++) have the static storage duration and usually are collected by the compiler in a literal pool that is stored in a read-only memory.
In any case according to the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.
Comment: @EricPostpischil It does not mean that I may not use this term.:)
Comment: @EricPostpischil No the statement is very clear and unambiguous
Comment: @EricPostpischil In some languages a term has a definition in other languages it is used with the common sense. It does not mean that you may not use a term with the common sense. Consider for example the term generic.
Comment: It is misleading to state that string literals are "usually" collected the compiler and stored in read-only memory. While you may use general-purpose multi-user systems most commonly, they are not actually the most common systems in the world, and there are a variety of systems. It is not "unusual" for a compiler to store string literals in writeable memory. It could be better to say it is "common."
Comment: The C++ standard has a concept of well-formed and ill-formed programs, but the C standard does not use this terminology. A compiler may accept a program that violates constraints.
Comment: It means that your answer is misleading and possibly incorrect. It incorrectly presents the rules of C.
Comment: Neither "clear" nor "unambiguous" means correct. And it is not unambiguous; there is no definition for "well-formed" or "ill-formed" in C stated in either the C standard or this answer. Therefore there is no good meaning for "ill-formed" at hand. It is ambiguous.
Comment: Common sense is insufficient to clarify what the term means. Common sense would say that "well-formed" or "ill-formed" is about the **form** of the program, which is readily interpreted to mean its syntax and grammar. But there is nothing wrong with the grammar of the programs in the question; they are accepted by a parser that uses the grammar specified in the C standard. The C++ standard added semantic rules to "ill-formed." That was the choice of its committee, and possibly not a good one. But it would not make sense to say "ill-formed" for C merely obeys all the semantic rules. Some…
Comment: … rules apply only conditionally, if the program does certain things at execution time. So defining "ill-formed" for C to mean anything more than the grammar and less than obeying all semantic rules is tricky. And it is certainly not covered in this answer.
Answer: Declaring a const int and then assigning a value to it through a pointer is undefined behavior. Modifying this variable through a pointer will not throw an exception when it is allocated in a writable memory though (seems that your compiler is allocating the variable in the stack).
However when you declare char *str = "test"; the string "test" is usually allocated in a read-only memory section (which seems to be your case). Thus probably throwing an ACCESS_VIOLATION when you try to change it through a[3] = 'M';.
To stress that out though: both cases should be considered undefined behavior.
Comment: String literals are common allocated in read-only memory, but this is of course not true on systems that do not support this. C can be implemented for even very tiny processors in embedded systems, which lack the protection features of general-purpose multi-user systems. It is undoubtedly the cause in OP's case, but it is not a rule that strings are "always" allocated in read-only memory.
Comment: IMHO assigning to a constant via pointer is not "undefined behavior"; it's a "programming error". No need to discuss what might be the consequences of it: The compile does not need to allocate an actual variable for it, but could optimize it away. It could also place the constant in the text segment, causing an access violation on write attempts for modern systems.
Answer: There are at least four factors involved in the observations made in the question.
1. Implicitly removing const should generate a warning
Consider this:
int *ptr = &var;

In this statement, &var is a pointer to a const int, but ptr is a pointer to int. This violates the constraints for simple assignments in C 2018 220.127.116.11 (which apply because the rules for initialization in 6.7.9 11 refer to them). In this case, the left operand must have all the qualifiers of the right operand and be of otherwise compatible type.
Because a constraint is violated, a compiler conforming to the C standard is required to issue a diagnostic. You either used a non-conforming compiler to compile this program or you ignored the diagnostic and executed the program anyway.
Since a constraint is violated, the resulting behavior is not defined by the C standard.
An important principle here is that the C standard does not prevent you from breaking some rules. In this case, it merely does not guarantee what will happen.
2. The behavior of attempting to modify const object is not defined by the C standard
In this line:
*ptr = 12;

the program attempts to modify the constant var through a pointer. This violates C 6.7.3 7, which says:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

(The expression *ptr is an lvalue with non-const-qualified type.)
As above, the C standard does not prevent you from breaking this rule; it merely does not define what will happen.
What happens when you break this rule? It depends on how the compiler treated your program. Several things are common:

If the object is static and const, the compiler might assign it to a read-only location of memory. Then attempting to modify it would cause a memory access violation and crash the program.
If the object is automatic (defined inside a function with default storage), the compiler might assign it to the stack. The stack is both readable and writeable (it has to be writeable because we change the stack frequently, as routines are called and return). Thus, although the object is const, the compiler has no good way to put an automatic object into read-only memory. So it is on the stack and is writeable. Then attempting to modify it succeeds.
The compiler, during optimization, modifies your program in various ways. This can cause hard-to-predict results when you attempt to modify a const object. The optimizer might recognize that the attempt is not defined by the C standard and simply remove the attempt from your program. But other results are possible too.

3. Due to historical language development, string literals are not const-qualified
At the time string literals were introduced to the C language, there was no const qualifier. There was merely a rule (at some point, if not initially), that you were not allowed to modify the elements of string literals.
When const was introduced to the C language, string literals could not be made const because this would cause many programs not to compile, because those programs were using char * to refer to elements in string literals. They were not modifying the string literals, but they were using these old pointer types to refer to them.
So string literals remained non-const-qualified.
4. The rule that modifying string literals is not supported remains
Another feature of string literals is that they may be consolidated. If you use "abcdefghijklmnopqrstuvwxyz" in one place in the program and you use the same string in another place in the program, even in a different translation unit, the compiler and linker are allowed to create just one instance of them in the executable file and in the memory of the loaded program. This feature was important for early programs, because machines had limited space, so combining copies of the same data was valuable.
This permission is in C 2018 6.4.5 7, which says, about string literals:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.…

That paragraph also gives us the rule that the behavior of attempting to modify string literals is not defined by the C standard:

… If the program attempts to modify such an array, the behavior is undefined.

The first rule of this paragraph is also a reason we need the second rule. If two string literal can be consolidated into one memory location, then a routine that changed what it thought of as its string could inadvertently change the data used by another routine, possibly in an entirely different part of the program written by a different person at a different company.
Thus, due to how the C language developed historically, string literals are not const-qualified, but the C standard does not support modifying them.
What happens when you break this rule? Commonly, string literals are put in a read-only portion of memory. When you attempt to modify them, a likely result is that your program causes a memory access violation and crashes. This is the proximate cause of the behavior you observed: The string was in read-only memory, and modifying it caused a crash, but the ptr object was on the stack, and modifying it "worked." So the results are not a necessary consequence of the rules of C but were consequences of how your compiler behaved.

Changing constant variables in C


Attempt to access an unitialized boost::match_result<> class

Question: The pattern matches any floating point number with <= 10 digits before the dot.
string pattern = (?<value>([1-9][0-9]{0,9})(,[0-9]+){0,1});
string line = " s - ssd";
boost::regex expr{val_pat};
boost::smatch match;
boost::regex_search(line, match, expr);
if(match["value"].matched){
    cout << match["value"]<<endl;
}

This code gives me the

Attempt to access an unitialized boost::match_result<> class error.

How do I safely extract the named group: value?
Answer: boost::regex_search has a post condition of

If the function returns false, then the effect on parameter m is undefined, otherwise the effects on parameter m are given in the table:

So what you need to do is either capture the return from regex_search to make sure it did find something or can can use it as the condition of an if statement like
if(boost::regex_search(line, match, expr)){
    if(match["value"].matched){
        cout << match["value"]<<endl;
    }
}

If you can use C++11 you can use std::regex_search which will update the match argument even if no matches are found.


where is the tmp/setup folder created when doing ADD cmd in docker?

Question: My dockerfile has this line, it sends the txt file to /tmp/setup folder, but i dont see it anywhere in the current docker folder where Dockerfile sits.
ADD requirements.txt /tmp/setup/requirements.txt

how do i look inside this folder? where is "tmp/setup" located?
Comment: ADD adds that file under that directory in the docker image. When you run the docker image, it should be there.
Answer: This line(ADD requirements.txt /tmp/setup/requirements.txt) will copy the file requirements.txt from the current folder to the folder /tmp/setup in the filesystem of Docker image when you building your image.
You can find this file a folder in the container that run from the built image, not in the current Dockerfile folder.


Is it possible to do a CSS @supports check on a @media rule?

Question: The @support rule allows one to do a feature query on CSS properties. I am wondering whether it is possible to do a feature check on specifically @media rules?
For example, I like to know if the browser supports the @media pointer or any-pointer condition:
@supports @media (pointer:fine) {

Or
@supports @media (pointer) {

This does not seem to work. Should it work?
Edit: This is not a duplicate of the referenced question. Perhaps I should clarify the question to explain why this is a different question, so here goes:
I do not want to nest @supports inside @media or vice versa. I want to feature detect whether the @media query itself is supported, in particular the @media rule for pointer. This is a completely different scenario from just nesting a random support query inside a media query.
Comment: I'm not sure but have you tried nesting something like https://codepen.io/anon/pen/mmYNgp?
Comment: tl;dr you need to nest the media query inside the  @supports brackets.
Comment: @tylerh: the question is how?
Comment: @MichaelCoker: Thanks, I created a fork of your starting point:
https://codepen.io/fchristant/pen/BRgoKN

It basically proves that this approach does not work. It does not detect the rule nested inside @ media, yet on its own without nesting, it does work. So my question still stands.
Answer:
This does not seem to work. Should it work?

No; @supports only supports property declarations, not at-rules or indeed any other grammatical construct in CSS. You're not looking to check for support for the @media rule anyway; you're trying to check for support for specific media features. But @supports doesn't support that either, even though media features share the same declaration syntax with property declarations.
To that end, you don't need the @supports rule at all. To check if a browser supports a certain media feature, simply write a @media rule with a media query list containing both the media feature and its negation:

@media not all and (pointer), (pointer) {
  p { color: green; }
}

If this text is green, your browser supports the pointer media feature.

(Note that Media Queries 4 removes the restriction of not requiring a media type from MQ3, so the negation really ought to be not (pointer), but no browser supports this yet and a media type is still required.)
Browsers that don't recognize the pointer media feature will interpret the @media rule as @media not all, not all (in spite of the not in the not all and (pointer) media query). See section 3.2 of the spec, which says

An unknown <mf-name> or <mf-value>, or disallowed <mf-value>, results in the value "unknown". A <media-query> whose value is "unknown" must be replaced with not all.

If you need to apply CSS for when a browser does not support a media feature, these error handling rules mean you'll need to take advantage of the cascade (and if you don't know the original values in advance, you may be stuck):

p { color: red; }

@media not all and (pointer), (pointer) {
  p { color: currentcolor; }
}

If this text is red, your browser does not support the pointer media feature.
Comment: I saw it happen in real-time, you are fast. Thanks!
Comment: Thank you, that is exactly what I was looking for! I do have one follow-up question for the sake of completeness: what would be the syntax in your example to do the opposite? To check if a browser does NOT support pointer?
Comment: @Ferdy: The cascade will be your friend in that case. I've updated my answer with an example.
Comment: This is just beautiful! For completion the answer for a pointer value: `@media not all and ( pointer: fine ), ( pointer: fine ) {}`


Select Only the Most Recent Row

Question: I'm using a query to pull the valuation cost of projects. It works well, except sometimes it returns multiple rows for a valuation.
How can I modify my query to get only the most recent record to avoid multiple rows?
Query
SELECT
    to_char( BVALUATN.G3_CALC_VALUE, '$999,999,999,999,999' ) AS "Valuation",
    TO_CHAR( G6ACTION.G6_ACT_DD, 'mm/dd/yyyy') AS "Final Date"

FROM PERMIT

LEFT OUTER JOIN G6ACTION G6ACTION
    ON  (PERMIT.B1_PER_ID1 = G6ACTION.B1_PER_ID1)
    AND (PERMIT.B1_PER_ID3 = G6ACTION.B1_PER_ID3)

LEFT OUTER JOIN BVALUATN BVALUATN ON (PERMIT.B1_PER_ID1 = BVALUATN.B1_PER_ID1 AND PERMIT.B1_PER_ID3 = BVALUATN.B1_PER_ID3)

WHERE TRUNC (G6ACTION.G6_ACT_DD) > TO_DATE ('01/01/2020', 'mm/dd/yyyy')
AND TRUNC (G6ACTION.G6_ACT_DD) < TO_DATE ('04/06/2022', 'mm/dd/yyyy')

ORDER BY "Valuation" DESC;

Output

Desired Output

I'm interested in seeing various suggestions to see what works best for different use-cases, e.g., using an aggregate function, subquery, etc. Thanks for any help.
I am using Oracle Database version 184.108.40.206.0.
Comment: It sounds like you want the last row per valuation, and not just the most recent row overall. Is that right?
Comment: @WilliamRobertson Yes, that's correct.
Answer: You can do a group by on the valuation and select the max date like below
SELECT
    to_char( BVALUATN.G3_CALC_VALUE, '$999,999,999,999,999' ) AS "Valuation",
    MAX(TO_CHAR( G6ACTION.G6_ACT_DD, 'mm/dd/yyyy')) AS "Final Date"

FROM B1PERMIT

LEFT OUTER JOIN G6ACTION G6ACTION
    ON  (PERMIT.B1_PER_ID1 = G6ACTION.B1_PER_ID1)
    AND (PERMIT.B1_PER_ID3 = G6ACTION.B1_PER_ID3)

LEFT OUTER JOIN BVALUATN BVALUATN ON (PERMIT.B1_PER_ID1 = BVALUATN.B1_PER_ID1 AND PERMIT.B1_PER_ID3 = BVALUATN.B1_PER_ID3)

WHERE TRUNC (G6ACTION.G6_ACT_DD) > TO_DATE ('01/01/2020', 'mm/dd/yyyy')
AND TRUNC (G6ACTION.G6_ACT_DD) < TO_DATE ('04/06/2022', 'mm/dd/yyyy')
GROUP BY to_char( BVALUATN.G3_CALC_VALUE, '$999,999,999,999,999' )
ORDER BY "Valuation" DESC

Answer: As you're using DB version 12c+, then you can use FETCH clause following ORDER BY for ascending "Valuation" such as
ORDER BY "Valuation", "Final Date" DESC
FETCH FIRST 1 ROW ONLY

If you needed both of the equal values, then you'd replace ONLY with WITH TIES and remove the part , "Final Date" DESC
Comment: Looking for last row per valuation, not just the most recent row overall.
Comment: Well, can you express what's the difference between the last row and the most recent row overall, since it's hard to distinguish considering the current dataset @GTSJoe

Select Only the Most Recent Row


Unable to receive mails using smtplib as recipient is getting added in bcc list

Question: import smtplib

server = smtplib.SMTP('smtp-mail.outlook.com', 587)
server.ehlo()
server.starttls()
server.login("email@example.com", "pass")

body = 'Subject: Mail test .\n\n' + 'Email\'s BODY text' + '\nYour :: Signature/Initials'
server.sendmail("firstname.lastname@example.com","email@example.com",body)
server.quit()

I can see the mail sent in user1 sent items but user2 is in bcc list not in to as to shows unknown and mail is not received in user 1 account.
Please help me as what i am doing wrong here
Answer: import smtplib
toaddr = 'firstname.lastname@example.com'
cc = ['firstname.lastname@example.com','firstname.lastname@example.com']
bcc = ['firstname.lastname@example.com']
fromaddr = 'email@example.com'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
    + "To: %s\r\n" % toaddr
    + "CC: %s\r\n" % ",".join(cc)
    + "Subject: %s\r\n" % message_subject
    + "\r\n"
    + message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('server',port)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()

Comment: Thanks for the answer,I can see the message in sent items but is not getting delivered to the recipient,What could be the issue here?
Comment: i can send mail to gmail but not to outlook?Please help me with this
Comment: then you should be configure SMTP settings according to outlook.try to remove the port parameter.


Restart an application if taking lot of memory

Question: How can I restart an application if it's taking a lot of say CPU utilization or taking too much RAM on Linux, is there any shell script to do the same?
Answer: Why would you want to use a script to do that? Close the application. Or, in the system monitor, end or kill the process. If you don't want to use the GUI, then you can open a terminal, run ps ax to find the process ID and use kill prosessid to end it. Use the -9 switch to use force, but avoid that whenever possible.
Comment: dont want it to be manual, need some automated stuff.
Comment: I don't think anything like that exists. For CPU, you can renice it so that all other applications will be prioritized. For RAM.. What if you decide to record a screencast. Should the system just prevent you from doing that? Or if you want to start 3D animations? Having the system automatically deny you the opportunity to do what you want, seems like a bad idea.
Comment: @Jo-Erend Schinstad - actually need this for a server that has multiple applications running on it, and it happends quite many times that one of the many application start taking full utilisation and has to be restarted ...


numpy ndarray throw exception when truncating string

Question: I'm having an ndarray of ascii strings of different lengths. Until now I used dtype=object for this. However profiling showed that this is actually a bottleneck in my program. Using dtype=np.string_ is faster, however  it has the downside that it silently truncates the set values. Since this is a perfect recipe for hard to find bugs I wonder if there is a possibility to either rescale (I know that this could be costly in case of entire reallocation) the array or raise an Exception in case of truncation?
I couldn't change ndarray.__setitem__ since its an read-only attribute. Here is some code to demonstrate what I mean:
import numpy as np

def Foo(vec):
    vec[1] = 'FAIL'

    print('{:6s}: {}'.format(str(vec.dtype), vec))

VALUES = ['OK', 'OK', 'OK']

Foo(np.array(VALUES, dtype=object)) # Slow but it works
Foo(np.array(VALUES, dtype=np.string_)) # Fast but may fail silently

Resulting in:
object: ['OK' 'FAIL' 'OK']
|S2   : [b'OK' b'FA' b'OK']

Comment: *"...raise an Exception in case of truncation?"*  It would be nice if setting some flag enabled this behavior, perhaps something similar to how `numpy.seterr()` controls the handling of floating point errors.  I've never seen such a flag, but as an enhancement request for numpy, I'd give it a +1.
Comment: @WarrenWeckesser. I agree, it could also be a warning or something similar.
Answer: Let's see I can explain what's going on
In [32]: ll=['one','two','three']
In [33]: a1=np.array(ll,dtype=object)
In [34]: a1
Out[34]: array(['one', 'two', 'three'], dtype=object)
In [35]: a1[1]='eleven'
In [36]: a1
Out[36]: array(['one', 'eleven', 'three'], dtype=object)

a1 just like ll consists of pointers - pointers to strings that reside elsewhere in memory.  I can change any of those pointers, just as I could in a list.  In most ways a1 behaves just like a list - except that it is possible to reshape, and do some other basic array things.
In [37]: a1.reshape(3,1)
Out[37]:
array([['one'],
       ['eleven'],
       ['three']], dtype=object)

But if I make a string array
In [38]: a2=np.array(ll)
In [39]: a2
Out[39]:
array(['one', 'two', 'three'],
      dtype='<U5')
In [42]: a1.itemsize
Out[42]: 4
In [43]: a2.itemsize
Out[43]: 20

the values are stored in the array's data buffer.  Here it made an array with 5 unicode characters per element (Python3) (5*4 bytes each).
Now if I replace an element of a2 I can get truncation
In [44]: a2[1]='eleven'
In [45]: a2
Out[45]:
array(['one', 'eleve', 'three'],
      dtype='<U5')

because only 5 of the characters of the new value fit in the allocated space.
So there's a trade off - faster access speed because the bytes are stored in a fixed, known size array, but you can't store bigger things.
You could allocate more space per element:
In [46]: a3=np.array(ll,dtype='|U10')
In [47]: a3
Out[47]:
array(['one', 'two', 'three'],
      dtype='<U10')
In [48]: a3[1]='eleven'
In [49]: a3
Out[49]:
array(['one', 'eleven', 'three'],
      dtype='<U10')

genfromtxt is a common tool for creating arrays with string dtypes.  That waits until it has read all the file before setting the string length (at least if using dtype=None). And the string fields are often part of a multi-field structured array.   The string fields are usually labels or ids, not something you commonly change.
I can imagine writing a function that would check string length against the dtype and raise an error if the truncation would happen.  But that's going to slow down the action.
def foo(A, i, astr):
    if A.itemsize/4<len(astr):
        raise ValueError('too long str')
    A[i] = astr

In [69]: foo(a2,1,'four')
In [70]: a2
Out[70]:
array(['one', 'four', 'three'],
      dtype='<U5')
In [72]: foo(a2,1,'eleven')
...
ValueError: too long str

but is it worth the extra work?
Comment: Thank you for the explanation. This elaborates on the cause, but unfortunately doesn't give me a solution to my problem. I played around a bit and found an solution of sorts, not very flexible I'm afraid though.
Comment: What kind of flexibility do you need?  What are you doing with these string arrays after construction?  It can be tricky to ensure that subclassing is preserved when passing through various `numpy` functions.  Note for example that `np.array` has `subok` parameter.
Comment: I don't know as of this moment. At the moment you can think of it as a table which is read (>95% the times) and somethimes written to. However future use might differ. Which is also somethings that scares my about subclassing/constructing the container myself instead of the provided factory function. I'd hate to introduce some hard to track bugs which will only surface once I forgot what I did half a year ago.
Comment: A table as in a 2d layout out of strings?
Answer: I found a non-flexible solution by inheriting from ndarray. I will not accept this answer till Friday maybe somebody comes up with something better. It fulfills its duties, even on views (eg. StringArray(...)[1:4])
import numpy as np

class StringArray(np.ndarray):
    def __new__(cls, val):
        field_length = max(map(len, val))
        # Could also be  self.dtype.itemsize:
                raise ValueError('Itemsize too big')
        elif isinstance(val, str):
            if len(val) > self.dtype.itemsize:
                raise ValueError('Itemsize too big')
        else:
            raise ValueError('Unknown type')
        super().__setitem__(key, val)

val = StringArray(['a', 'ab', 'abc'])
print(val)
val[0] = 'xy'
print(val)
try:
    val[0] = 'xyze'
except ValueError:
    print('Catch')

try:
    val[1:2] = ['xyze', 'sd']
except ValueError:
    print('Catch')

produces:
[b'a' b'ab' b'abc']
[b'xy' b'ab' b'abc']
Catch
Catch


Combine a result file from several txt-files

Question: I need to create a summary file from a large portion of txt-files from different folders. I started to do it with python, but any provided solution is fine ie. python, awk, bash
find = "find -name \"summary.txt\" > output.txt"
os.system(find)

o = open("output.txt", "r")
read = o.readlines()
for items in read:
    pilko = items.split("/")
    id = pilko[1]

I need to search summary-files from subfolders and compile the results of the txt-file to a result file. I'm kinda stuck here how to open the txt-file in for loop, save the data to a result file and move on.
plate = pilko[4]
print id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]
foo = open("id+"/"+pilko[2]+"/"+pilko[3]+"/"+plate+"/"+pilko[5]", "r")

That is approach that I tried, but everything is failing there:)
I could imagine there are easier ways to do this that I haven't heard yet.
Comment: `id` is a builtin method. never use it as a variable
Comment: post some sample input and expected output.
Answer: for f in `find -name 'summary.txt' -print` ; do cat $f >> /tmp/grandsummary.txt ; done

Comment: Could go even simpler: `cat $(find . -name 'summary.txt') > grandsummary.txt`. If too many arguments, `find . -name 'summary.txt' -print0 | xargs -0 cat > grandsummary.txt`. Or with recursive blobbing, `cat **/summary.txt > grandsummary.txt`
Answer: If you look at the code coloration, your quoting is incorrect in the last line. Furthermore, you should probably use the os.path APIs for your stuff. And with just in case to ensure the file is correctly closed. Finally, no need to readline, a file is an iterable of lines. Finally, why do you recompose your path manually? Why not just open(items, 'rb')?
Answer: Here's a python solution:
import os
with open('/path/to/result/file.txt', 'wb') as result_file:
    for root, dirs, files in os.walk('/path/to/start/directory'):  # walk the file system
        if 'file_name_I_want.txt' in files:  # This folder has the file i'm looking for!
            with open(os.path.join(root, 'file_name_I_want.txt'), 'rb') as src_file:  # open it up
                result_file.write(src_file.read())  # Read from src, store in dest.

This was written from memory, so it may need some jiggering.


Finding the area of an ellipse using change of coordinates

Question: I would like to find the area of the ellipse $x^{2} +2xy +2y^{2} \leq 1$.
I was told to use the substitution $s = x+y$ and $ t=y$.
Using this, I found the Jacobian determinant to be $1$ and then also completing the square I found the ellipse in the new coordinate system is $(x+y)^{2} + y^2 = s^{2} + t^{2} \leq 1 $.
I understand the area in this case is $\iint\limits_{R}1dxdy = \iint\limits_{R'}1dsdt$ but I'm unsure what the regions $R$ and $R'$ to integrate over are. I tried $s,t \in [-1,1]$ as $s^{2} + t^{2} \leq 1$ which means, as $s,t \in \mathbb{R}$, both of the squares are non-negative and so the squares are in $[0,1]$. But I'm nearly certainly sure this is incorrect.
Any help would be greatly appreciated.
Comment: $s^2+t^2=1$ is a circle of unit radius, centered at $(s,t)=(0,0)$
Answer: First, you have an ellipse $E = \{(x,y) \in \Bbb{R}^2| \, \, x^2 + 2xy + y^2 \leq 1\}$. Then, you have the unit disk $D = \{(s,t) \in \Bbb{R}^2| \, \, s^2 + t^2 \leq 1\}$. Next, you have the coordinate transformation $\xi(x,y) = (x+y, y)$, so that $\xi[E] = D$. In other words, $\xi$ sends points in the $x,y$ plane to the $s,t$ plane, so that it maps the ellipse $E$ onto the disk $D$.
So,
\begin{align}
\text{Area}(E) &= \int_E 1 \, dx \, dy \\
&= \int_{\xi^{-1}[D]} 1 \, dx \, dy \\
&= \int_D(1 \circ \xi^{-1})(s,t) \cdot |\det (\xi^{-1})'(s,t)|\, ds\, dt \\
&= \int_D 1 \, ds \, dt \\
&= \text{Area}(D)
\end{align}
But notice that this area is simply the area of a circle of radius $1$, so it is $\pi$.

As for how you can explicitly calculate this area, you have a few possibilities: the first is to use a symmetry argument that the area of $D$ is twice the area of the upper semicircle, which I shall denote as $D^{\uparrow}$. But now note that
\begin{align}
D^{\uparrow} &= \{(s,t)\in \Bbb{R}^2| \, t \geq 0, \quad \text{and} \quad \, s^2 + t^2 \leq 1\} \\
&= \left\{(s,t) \in \Bbb{R}^2| -1 \leq s \leq 1 \quad \text{and} \quad 0 \leq t \leq \sqrt{1-s^2} \right\}
\end{align}
Therefore,
\begin{align}
\text{Area}(D) &= 2 \int_{D^{\uparrow}} 1 \, ds \, dt \\
&= 2 \int_{-1}^1 \int_0^{\sqrt{1-s^2}} \, 1 \, dt \, ds
\end{align}
I leave it to you to evaluate the integral. If for some reason you do not wish to invoke the symmetry argument, you can also calculate the integral directly as $\int_D  = \int_{D^{\uparrow}} + \int_{D_{\downarrow}}$, i.e break up the disk over the upper and lower halves, and calculate each area separately. I leave the details to you.
Another approach is to use a change of variables again to polar coordinates; $s = r \cos \phi$ and $t = r \sin \phi$, with $0 \leq r \leq 1$ and $0 \leq \phi \leq 2 \pi$. Now, be careful with the Jacobian determinant! You should find that
\begin{align}
\text{Area}(D) &= \int_D1 \, ds \, dt = \int_0^{2\pi}\int_0^1 r \, dr \, d \phi.
\end{align}


How to Handle JSON with escaped Unicode characters using python json module?

Question: EDIT: The error doesn't appear in Prompt, but in the following Google App Engine environment.

I have following json
<code>>>>dat = r"""{"name":"Something", "data":"For youth \n\nBe a hero! Donate blood!\n\u091c\u092f \u0939\u093f\u0902\u0926! \u0935\u0928\u094d\u0926\u0947 \u092e\u093e\u0924\u0930\u092e\u094d"}"""
</code>
It contains unicode escaped characters.
I want to parse this. So I did
<code>>>>jsDat = json.loads(js)
</code>
Then following works
<code>>>>name = jsDat.get('name')
>>>name = name.encode('ascii') #This is because json module handles in unicode
>>>print name
Something
</code>
But trying for the field with unicode data, that is "data", an error is displayed
<code>>>>data = jsDat.get('data')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 366-367: ordinal not in range(128)
</code>
How should I parse the data?
Comment: I can't reproduce your problem at all, are you sure you did this on a python prompt?
Comment: You can't just post any random code with the error. You must post the *exact* code that generated the error.
Comment: Is Not on the prompt but in a file. I have just seen you are right. On prompt there is no error. I did it in a Google App Engine Python environment.
Comment: @Sravan - I think you're missing a line - the UnicodeEncodeError is probably the result of `data = data.encode('ascii')`, right?
Comment: I have put up a screen-shot in the question producing the error
Comment: I haven't used GAE, but it looks like it can't handle non-ASCII characters on the terminal - see my answer below for a workaround.
Comment: in fact the problem is not when you do jsDat.get('data') but when you do print data
Answer: You can't encode unicode to ASCII if the characters exceed the ASCII character set.  If you want to force the conversion, and lose data, you can do this:
<code>data = jsDat.get('data')
data = data.encode('ascii', 'ignore')
</code>
See the doc for str.encode for more details about the ignore.
As an aside, I'm not sure why you're trying to encode to ASCII - the JSON module seems to handle that raw string just fine?
Comment: Ok, it worked. I am encoding it back into ascii, because python json module handles it in unicode. Thanks!
Answer: The error is coming from your 'print' line, and only because you're trying to print to a 'terminal' that doesn't understand the encoding. Doing anything else with the JSON object shouldn't produce errors.


Live location data from ASA to Power BI Map

Question: I've got a ASA output which sends the GPS coordinates of some devices devices to a Power BI Live datastream.
Data from ASA to Power BI looks something like this:

Device    Lat        Lon        Time
1         1,12345    2,34567    19-1-2018 11:48:00
2         1,34567    2,66666    19-1-2018 11:49:01
1         1,67890    2,55555    19-1-2018 11:49:13
2         1,33333    2,33333    19-1-2018 11:50:23
2         1,23222    2,44444    19-1-2018 11:50:54

I want to show the latest location of the devices on a map.
I can use a measure to show the latest Lat and Lon from a specific Device, like this:
GpsLonLast = CALCULATE(MAX('PowerBI'[lon]);FILTER('PowerBi';PowerBI[time]=[LastTime]))

Where LastTime is a measure to receive the latest time that device sent a message.
This works, when showed in a table, however I cannot map these measures to map control in Power BI, it does not support measures or aggregates.
If I use the plain Lat / Lon and Device fields as location and name on a map control I get all locations the devices were ever found. But that's not what I want, I want only the last location of the devices.
Note that I am using Azure Stream Analytics to send live data to Power BI, in Power BI this is received as a push dataset, so I cannot use custom Modeling in Power BI.
Answer: What I would suggest is creating a calculated table that only has the last locations for each device and using that table as the data set for your map.
This should give you the table you want:
= ADDCOLUMNS(SUMMARIZECOLUMNS(PowerBI[Device], "LastTime", MAX(PowerBI[Time])),
             "Lat", CALCULATE(MAX(PowerBI[Lat]),
                        FILTER(PowerBI, PowerBI[Time] = [LastTime])),
             "Lon", CALCULATE(MAX(PowerBI[Lon]),
                        FILTER(PowerBI, PowerBI[Time] = [LastTime])))

Now every time your live data updates, this calculated table should also update and give you the latest GPS coordinates to display on the map.
Comment: Thanks, but because I am using Azure Stream Analytics to send live data to Power BI, this is received in Power BI as a push dataset, where you cannot use custom Modeling in Power BI. So unfortunately this solution will not work for me.
Comment: @RodyvanSambeek OK. So you're saying the only things you can use are measures, but the map doesn't support measures? What kind of answer are you looking for here then?
Comment: The map doesn't support measures. I don't know why, because all other PowerBI components do support them. But I am looking for a solution for a fairly simple use-case. Where some GPS devices constantly send GPS data through Stream Analytics and I want to show the latest GPS location on the map. That seems to me as a reasonably simple request. Maybe there is a different solution? I don't think I am the first to try this.
Answer: I don't think it's possible what you want to do.
You could however use the Power BI API directly to a push dataset instead of Azure Stream Analytics and post the GPS coordinates yourself to the API.
You can clear the table beforehand so you only end up with the latest values. Unfortunately, you cannot remove or update a single row, so you have to post the complete table each time. It's a bit cumbersome, but it works. The performance hit of deleting all rows in the table and adding them again is not that big of a problem if there are a few items on your map.
We use this technique on some projects and it works quite fast. We only update the GPS coordinates every couple of minutes, and only post to the API when they are changed.
You can use the https://github.com/Microsoft/PowerBI-CSharp C# API library to simplify posting to the API.
Comment: Thanks! I actually ended up creating something similar. I think this is the only possible solution at the moment.
Answer: I would first calculate a "helper" column to test for for the latest Time per Device, e.g.
Latest Time per Device =
IF (
    [Time]
        = CALCULATE (
            MAX ( 'PowerBI'[Time] ),
            FILTER ( 'PowerBI', 'PowerBI'[Device] = EARLIER ( [Device] ) )
        ),
    "Is Latest Time per Device",
    "Other"
)

Then I would use that column as a Filter, e.g. add to Visual Level Filter well, then choose the "Is Latest Time per Device" entry.  Then you can use your Lat and Lon columns in the filtered visual.
Comment: Unfortunately I am in the context of a Power BI Live datastream, which means I cannot add helper columns, only measures. A measure does not allow this kind of filtering on Earlier or column values like [Time].
Answer: This is probably not the answer you are looking for, but I suggest you a couple of workarounds:

Use a top N filter (you can use one of those in real time datasets) ordered by date. Your map will show only the last points or short paths.
Modify the RoutMap custom visual to paint only the last value. I think it should be easy if you have the code :) https://github.com/weiweicui/PowerBI-Routemap


Service Interface Design - Exception or Object Hierarchy?

Question: I'm currently writing an app that posts some data to a HTML form and parses the resulting HTML response page.  Depending on the input my user sends the HTML response can either contain valid payload data or request that the user validate an error in the data they entered.
I'm slightly confused as to how to implement the interface for my call to the HTML service.  Specifically do I use exceptions to handle the responses which require further user validation or do I incorporate them into a hierarchy and use the base type as my interface return type?
Is there a best approach for implementing such interfaces?
Answer: It really depends on how you see this being used.
I would not build an API that used Exceptions for "normal" actions.  If, in your API, it is not obvious whether validation will be required in advance, I think that building the checks directly into the API, along with a clean way to verify this in advance would be preferable to exceptions.
If, however, it's fairly obvious in advance whether or not the validation is required, I'd try to build it into the API (ie: make the method calls require the validation information to be passed in).  This would prevent the need for the exceptions in most cases.  You can then raise an exception when necessary.
In general, I strongly recommend thinking of exceptions as "exceptional", not a mechanism for flow control.  A user shouldn't have to handle exceptions in order to use your API effectively.
Comment: I'm glad you mentioned exceptions in non-exceptional circumstances as that my chain of thought.

I'm not sure I follow you on the use of validation in the API however.  Are you suggesting that the API would expose a validate method that would return some token to be used in the subsequent call to retrieve the actual response data?
Comment: @mmccomb: That would be one option.  Another would be to pass a class that contained the info required for validation, and pass a reference to it into each method as required, etc.
Comment: @mmcomb: I'd strongly suggest not using exceptions as flow control, though - which was kind of what you were suggesting...


What is the "required" amount when using Plumber's Putty

Question: I have a new stainless steel sink and installed a Kohler sink flange following their package instructions. The instructions for putty only stipulated "apply a ring of putty."  However, subsequently, I find the instructions regarding the flange for the disposal I am installing on the other side stipulates a ring "half an inch thick." The ring in a flange installation online video shows a ring about that applied to the area in opening and the flange fit into that.  Other online instructions show 1/8" (which mine probably was) to 1/4" thick.  When I set the flange, putty came out pretty much all around...but not much.
Question: 1) if I got excess all around, is it set in "enough" and 2) if not and I have leakage underneath when water is run into new sink, is it set "permanent" or will it release fairly easily once I remove screws and tightened ring?
Comment: Enough to squeeze out all the way round when the sink tailrace is tightened into place was the general rule I was taught. Which is known by eyeballing the void to be filled and adding a little bit more.
Answer: You only need a enough to cover the ring area and keep the flange from leaking.  It really depends on the depth of the offset space and how your flange fits into it.
I think normally I would probably lay down 1/8 inch.  However I have ran across some new modern bathroom sinks where I used 1/4 inch because the ring was deep.

Yes.  It sounds like your application was the perfect amount.  You really should have a slight amount come out on tighten.  If you don't then you don't know if you have enough.  If a lot comes out then you run the chance of not being able to tighten enough and getting dribble leaks.  If you have too little and there are no leaks then you will still have a "crack" around the flange where water pools.  Might never leak but isn't attractive.
You have to tighten the ring to test for leaks.  Once the ring is tighten it is permanent.  If you untighten the ring then you could cause the putty to move and introduce a leak.  Often if you untighten you have to reputty.

Also I want to note two small things.  #1 - Do not use rubber/plastic gaskets instead of plumber's putty.  These are now included in a lot of kits.  First sometimes they fail right away.  Second the material can break down and it can fail in near future.  Plumber's putty isn't perfect but it is much much more reliable (also don't mix plumber's putty with these gaskets).  #2 When you apply your plumber's putty you want a little squeezing out - you should get a little squeezing out all around the circle.  If you get a lot on one side and none on the other I would start over.  The amounts squeezed out don't have to be perfectly symmetrical but you don't want to see none in an area.
Comment: While it is "permanent", putty is much easier to remove and reapply than a true sealant.  If there were a leak, a reseating  with new putty is pretty straightforward, even if no fun.
Comment: I never had issues removing plumber's putty.  I have had to replace sinks from people using some form of silicone/glue.   The big question that I have seen people argue about on applying plumber's putty is to put it on the sink or on the flange.


What gem bonus applies to socketed off-hand items?

Question: Gems provide 3 different bonuses depending on what they're inserted into: Helms, Weapons, and "Other". What do off-hand items like Wizard orbs, Demon Hunter quivers, and Witch Doctor mojos count as?
I'm leaning toward "other", but technically these items are equipped in weapon slots. Which is it?
Answer: Off-hands use "other" gem bonuses.
Answer: Any off-hand items are not counted as weapons, thus they will the "other" bonus from gems.
Answer: They count as "other".
I've tested this, and you definitely do not get the weapon bonus for shields, mojos, etc..


How do you get the items in lava in Iron Keep?

Question: In Iron Keep there are several items in stretches of Lava and one item after the first bonfire in front of a statue which is blowing fire continuously over it.
Are there tricks to get these items as you often die before to even reach them?
Comment: related: http://gaming.stackexchange.com/questions/166091/how-can-i-reach-the-chests-in-the-iron-keep-without-dying
Answer: The trick is to raise your fire-resistance stat. The minimum is at about >600 to be able to reach any item (you'll get the item, but you will die).
Raising it to >1000 is recommended.
Note: You'll still take damage, but not as fast. Be quick and you should get the items. It's also recommended that you spend your souls before you attempt a run on the items.
You can raise your fire resistance with certain armour, rings (Flame quartz ring), the pyromancy flash sweat (gives +300) and items (orange burr but doesn't stack with flash sweat).
There are also 2 Pharros' Contraption that, when activated, spill water into a pool in front of them. When you roll in the water, you temporarily boost your fire resistance by +400.
Additionally, there are huge vases scattered through the level that contain water, which have the same effect as the water from the Pharros' Contraption. Just roll through them.
To get the item (the iron key) from the fire-breathing trap, you can either carefully inch your way to it, till you get the pick-up prompt or you can deactivate the fire with a switch, later in the level.
Source: Darksouls 2 Wiki
Comment: In regards to the water you can roll in, I'm pretty sure that you get the same effect by rolling through the pottery scattered throughout the level.
Comment: Oh yeah, forgot about that. Will add it to the answer.