Flutter FutureBuilder snapshot.data receiving null

Question: I am trying to get data from sqflite using FutureBuilder
Here is my Code :
Function To get charts from Sqflite
getCharts(table, column_name, ids) async {
   var conn = await database;
   // var li = [];
   var data = await conn.query(table,
       where: "indicator_id IN (${List.filled(ids.length, '?').join(',')})",
       whereArgs: ids);

   return data;
 }

This Function Returns:
[
 {
   id: 1, indicator_id: 1,
   label: Percentage of population with access to electricity,
   np: 89.9,
   p1: 88.5,
   p2: 96.3,
   p3: 97.4,
   p4: 98.9,
   p5: 90.8,
   p6: 44.9,
   p7: 77.1,
   chart_type: pie_chart,
   name: Access to electricity,
   description: Percentage of population with access to electricity
  }
]

Function from Chart Service
Future<List<Chart>> getCharts(List<int> ids) async {
    var res = await _repository!.getCharts('charts', 'indicator_id', ids);

    var mapped = res.map((chart) => new Chart.fromJson(chart)).toList();
    print(mapped);

    return mapped;
  }

This Function Returns:
[Instance of 'Chart']

On The Chart Screen
 ChartService _chart2service = ChartService();
Future<List<Chart>>? futureChart;
  @override
  void initState() {
    super.initState();

    futureChart = _chart2service.getCharts(this.widget.ids!);
  }

But When I try FutureBuilder:
 FutureBuilder<List<Chart>>(
            future: futureChart,
            builder: (context, snapshot) {
            print(snapshot.data);
             })

snapshot.data is returning null value.
Answer: I might be offering a "stupid" answer, but the body of the builder function just directly prints snapshot.data.
When the Future is launched, by definition, it has not yet completed. You must first check its status: is it uncompleted? Is it done, or are there errors (e.g. connection lost)?
Here's some example code:
class MyApp extends StatelessWidget {
  final futureChart = Future.delayed(Duration(seconds: 5));
  @override
  Widget build(BuildContext context) => MaterialApp(
        home: Scaffold(
          body: Center(
            child: FutureBuilder(
                future: futureChart,
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    // some logic... and the following UI:
                    return Container(child: Text("Woops!"));
                  }                   else if(snapshot.connectionState != ConnectionState.done) {
                    // some logic... and the following UI:
                    return Container(child: Text("Waiting..."));
                  }

                  // we're finally done, we can add logic and some UI
                  return Container(child: Text("our future is done: ${snapshot.data}"));
                }),
          ),
        ),
      );
}

Comment: You saved my day with the snapshot.hasError, was able to solve my issue +1 ! Thanks.
Comment: I got this error
type List is not a subtype of type FutureOr>
Answer: First think you check your getChart() function that have data present or not like :
var mapped = res.map((chart) => new Chart.fromJson(chart)).toList();
  print(mapped);
  return mapped;

If your function return mapped or console print the mapped your data come successful.
Then you create Widget using FutureBuilder like below:
FutureBuilder<List<Chart>>(
                  future: futureChart(),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                return Text('Your Data : ${snapshot.data}');
          } else{
            return CircularProgressIndicator();
         }
       }
   ),

Answer: Check whether snapshot.data is null or not. FutureBuilder would provide the result when it's ready.
FutureBuilder<List<Chart>>(
  future: futureChart,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      print(snapshot.data);
      return Text('Data Loaded');
    }
    return Text('Loading Data...');
  },
);


How does one start learning music theory?

Question: I know some basic stuff like scales and how to construct chords, but I don't know much about the roles notes play in melody, what kinds of melodies there are, how to do chord progressions, and so on.
Can someone suggest a "topics curriculum" for teaching yourself music theory?
Answer: Yes, you'll need to buy books and read them, and work through the exercises.
I'm going to describe how it was taught to me in a music college in the United States. I'm sure different schools have different approaches.
Things basically fall into four categories:

Ear Training
Classical music theory
Form and Analysis
Jazz Theory

Ear training and classical music theory are taught simultaneously. They take about one and one half years of classes. Form and analysis finishes out the second year. Many schools encourage jazz musicians to complete the basic two years of classical theory before they start studying jazz theory, although after the first year, jazz majors are most likely playing plenty of jazz as well whether they understand all the theory or not.

Ear training

Intervals and Chords
Temporal Acuity (rhythms)

The principles of ear training are straightforward, but actually learning the techniques takes a lot of practice every day for a long time.
Tonal Harmony (taken from the table of contents of a college textbook)
Fundamentals

Elements of Pitch
Element of Rhythm
Triads and Seventh Chords
Diatonic Chords in Major and Minor Keys

Diatonic Triads

Principles of Voice Leading
Harmonic Progression
Triads in Inversion
Cadences and Phrases
Non-chord Tones

Diatonic Seventh Chords

Diatonic Seventh Chords

Chromaticism

Secondary Functions
Modulations Using Diatonic Common Chords
Other Modulatory Techniques
Binary and Ternary Forms
Mode Mixture
The Neapolitan Chord
Augmented Sixth Chords
Enharmonic Modulations

Tonal Harmony in the 20th Century

When you've gotten a grounding in all that, then you'll want to look at classical form and analysis, and then jazz music theory.
Wikipedia has a music theory section. This should be helpful as a reference and an overview. But you will still want to purchase a college-level textbook and workbook and work through the exercises.
Comment: Hmm, nice well-rounded answer, but if I was just starting to learn theory, I'd be too scared of it to ever learn it. I propose you split it into steps with the simplest and most foundational things first. Then list the things that would be the "next step up" and so on. When you just list everything one should know, it is quite intimidating.
Comment: Excellent answer that outlines a typical music theory curriculum (very similar to one I followed in school).  OP should benefit from such a thorough overview.
Comment: +1 Wheat. That lets me see just how much of that I have hardly touched on - excellent guidance not just for a beginner, but for someone with over 25 years in music
Answer: Buy a book. It's really as simple as that. Oh, and read it.
"The AB Guide to Music Theory" is well regarded, but there are plenty more.
Comment: Get a teacher as well.
Answer: If I were you I would buy many different books on Music Theory for guitar and consider maybe even taking lessons for a few weeks or months (however long it takes). It doesn't take long to learn the basics and the basics alone will really spark your creativity and curiosity once you understand them. Books on harmony, scales, and even some chord books that demonstrate harmonic function of each chords could help a lot as well. Once you learn the basics you can begin to experiment with different ideas and that will lead you to more advanced theoretical discoveries, and never forget the internet is a great place for any theory topics you want to explore. Read and learn from many different people because everyone has a slightly unique way of explaining things and plus its always good to see a topic from many different points of view. I hope you continue your journey to learning Music Theory to better your musical understanding and broaden your horizons:)


Meaning of different inequalities when testing the probabilities of random variables

Question: I'm trying to figure out what different inequalities mean when testing the probability that a random variable is greater or less than a certain value. I've been searching around but I can't seem to find any questions that ask this specifically.
Say I have a CDF, $F(y)$, defined as
$$F(y) = \left\{\begin{array}{ll}
0 & : y \lt 0\\
y & : 0 \le y \lt 1\\
1 & : y \ge 1
\end{array}
\right.$$
along with a random variable $X$, and some value $y$. I know that:

$P(X \le y) = F(y)$
$P(X \gt y) = 1 - F(y)$
$P(y_1 \lt X \le y_2) = F(y_2) - F(y_1)$

But what method would I use to find the following?

$P(X \lt y)$
$P(X \ge y)$
$P(y_1 \lt X \lt y_2)$

Does the strictness of the inequality have any effect in this context?
Comment: Since $F(y)$ is continuous, $P(X=y)=0$ for any $y$, so strictness doesn't matter.
Answer: You can use either of the following:

$P(X < y) = P(X \le y) - P(X=y)$
$P(X < y) = \lim\limits_{z \uparrow y} P(X \le z)$  using the limit as $z$ approaches $y$ from below

If $X$ is a continuous random variable, i.e. the cumulative distribution function $F(y)$ is a continuous function, then $P(X=y)=0$ and $P(X < y) = P(X \le y) = F(y)$, so your second triple will have the same results as your first triple


MyType DataContract is in the Silverlight client MyTypeOfT

Question: i have a WCF service with a Property<T> DataContract (with KnownType, et cetera...), but in the Silverlight client I have just PropertyOfint, PropertyOfstring, ... types, but I need in Silverlight also a generic type. How?
Comment: I'm not sure I understand the question.  Silverlight supports generics.
Answer: The soap standard doesn't support the concept of generics so it is not supported directly in WCF. However, you can achieve this support if you control both the client and the WCF service by sharing the ServiceContract DLL between the client and the service. Make sure that this is really what you want since it is not a recommended SOA best practice.
Here is an article that describes how this approach works. By sharing the ServiceContract (not the service implementation DLL) and using the WCF ChannelFactory class you do not need to generate a proxy class since the ChannelFactory class will do this dynamically for you. The ServiceContract assembly will also need to contain all the referenced DataMember marked classes which is the main flaw of this approach because any logic they contain will also be shared. As long as the DataMember classes are just data transfer objects (DTO) then you're not bending the SOA tenents entirely out of shape. The article also explains how to do this with the WCF ClientBase class.
Comment: Okay, but is it possible something like 'Convert.ChangeType'?
Comment: Not really because the type you would be trying to convert must implement the IConvertible interface which neither "Add Service Reference" or SvcUtil will do. I answered a [question along these lines here.](http://stackoverflow.com/questions/187006/how-to-expose-objects-through-wcf) The answers there (not just mine) may help you understand the limitations of WCF objects. Basically, WCF object are **not** intended to be .NET objects. The closest you can come is sharing contract DLLs which is generally not a good thing.


How do I use a template file for preparing HTML message body for emails?

Question: I want to use a template file for preparing the email message body using the table tag, and putting the submitted form data by user in table rows. I have implemented hook_mail() with the following code.
function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      $message['body'][] = $params['message'];
      break;
   }
}

I created a template file (get_price/templates/mail-to-eberhard.html.twig), but the message body is not using my template file.
How do I make Drupal 8 use my template file?
Answer: So here is the answer:
Inside the hook theme function of your module use this code
function get_price_theme() {
  return [
    'mail_to_eberhard' => array (
        'template' => 'mail-to-eberhard',  // TWIG File
        'variables' => array('submitted_data'=>[]),
    ),
  ];
}

where variables is the array of parameter you want to send to the template file. Now create a template file named as mail-to-eberhard.html.twig inside your modules template folder.
Then inside the hook_mail() alter function use this code.
function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      //$message['subject'] = t('Article created: @title', array('@title' => $params['node_title']), $options);
      // Render the template to HTML
      // Set up email template
      $body_data = array (
         '#theme' => 'mail_to_eberhard',
         '#submitted_data' => $params['message']
      );
      //$message['body']['#theme'] = 'mail_to_eberhard';
      $message['body'][] = \Drupal::service('renderer')->render($body_data);
      break;
  }
}

now inside you template file you can use the array variables like this
You have received one new message from the Get Price Tab.

Full Name : {{ submitted_data['user_full_name'] }}

Email : {{ submitted_data['user_email'] }}

Phone : {{ submitted_data['user_number'] }}

State : {{ submitted_data['user_state'] }}

Product SKU : {{ submitted_data['product_sku'] }}

Product URL : {{ submitted_data['product_url'] }}

Message : {{ submitted_data['user_message'] }`


SQL join subquery

Question: I tried searching for an answer to my problem but failed to get an answer that actually helped.
I've written an sql code but can't seem to find where the problem is.
Is it possible to put a subquery in the "FROM" section?
SELECT S2.ITEM,
       S1.SHOP_ORDER,
       S1.OPERATION_NO,
       S1.START_DATE,
       S1.QTY_GOODS,
       S1.QTY_ENTERED,
       S1.QTY_MRB
FROM   (SELECT SHOP_ORD_RPT.OPERATION_NO,
               SHOP_ORD_RPT.SHOP_ORDER
        FROM   FLAME.SHOP_ORD_RPT
        WHERE  SHOP_ORD_RPT.OPERATION_NO = 110
                OR SHOP_ORD_RPT.OPERATION_NO = 370) AS S1
       JOIN (SELECT SHOP_ORD.SHOP_ORDER
             FROM   FLAME.SHOP_ORD
             WHERE  SHOP_ORD.ITEM = '3A2375'
                     OR SHOP_ORD.ITEM = '3A2703')AS S2
         ON S1.SHOP_ORDER = S2.SHOP_ORDER;

The error I receive upon running the script is:

SQL command not properly ended

I'd appreciate if anyone can help.
Thank you very much-
Ruth
Comment: Remove the "AS" in `AS S1` and `AS S2`. possible duplicate of [SQL Command not properly ended?](http://stackoverflow.com/questions/9811711/sql-command-not-properly-ended)
Comment: I take it this is oracle.  That's one of my least favourite error messages.  You have a syntax error somewhere.  It might be worth a shot to put aliases for the shop_order columns in each subquery.  Otherwise, start again and go with baby steps until you find the error.
Comment: You don't need subqueries here -- just join the tables in the main query itself.
Comment: @DanBracuk Why would aliasing those columns help? Did you not look at the possible duplicate link and see it is the same issue?
Comment: @MartinSmith, thinking something is worth a shot is not the same as thinking it will work.  As far as your link is concerned, I first saw your comment after I posted mine.  I'm a slow typer.
Answer: Try to remove AS keywrod after FROM and JOIN subquery as below
SELECT S2.ITEM, S1.SHOP_ORDER, S1.OPERATION_NO, S1.START_DATE,S1.QTY_GOODS, S1.QTY_ENTERED, S1.QTY_MRB
FROM (
    SELECT SHOP_ORD_RPT.OPERATION_NO, SHOP_ORD_RPT.SHOP_ORDER
    FROM FLAME.SHOP_ORD_RPT
    WHERE SHOP_ORD_RPT.OPERATION_NO =110
    OR SHOP_ORD_RPT.OPERATION_NO =370
    )  S1
JOIN (
    SELECT SHOP_ORD.SHOP_ORDER
    FROM FLAME.SHOP_ORD
    WHERE SHOP_ORD.ITEM ='3A2375'
    OR SHOP_ORD.ITEM ='3A2703'
    )  S2
ON S1.SHOP_ORDER = S2.SHOP_ORDER;

Answer: It is possible to put a subquery within the from clause. Try this:
SELECT S2.ITEM,
       S1.SHOP_ORDER,
       S1.OPERATION_NO,
       S1.START_DATE,
       S1.QTY_GOODS,
       S1.QTY_ENTERED,
       S1.QTY_MRB
FROM   (SELECT SHOP_ORD_RPT.OPERATION_NO,
               SHOP_ORD_RPT.SHOP_ORDER
        FROM   FLAME.SHOP_ORD_RPT
        WHERE  SHOP_ORD_RPT.OPERATION_NO = 110
                OR SHOP_ORD_RPT.OPERATION_NO = 370) S1,
      (SELECT SHOP_ORD.SHOP_ORDER
       FROM   FLAME.SHOP_ORD
       WHERE  SHOP_ORD.ITEM = '3A2375'
               OR SHOP_ORD.ITEM = '3A2703') S2
WHERE S1.SHOP_ORDER = S2.SHOP_ORDER;

SQL join subquery


Is the function $ \exp(2\pi i /\epsilon) $ equivalent to zero?

Question: Is the function
$$ f\left(\frac{x}{\epsilon}\right)=\exp\left(\frac{2\pi ix}{\epsilon}\right)=g(x) $$
equivalent to zero ? in the limit $ \epsilon \to 0 $ ?
If I take the derivative $$\frac{ g(x+\epsilon)-g(x)}{\epsilon} $$ is $0$ because the function $g(x)$ has a period 'epsilon'
Also if I take the integral of $g(x)$ is $0$ almost everywhere
So is this function equivalent to $0$ ??
Comment: Are you asking about the function itself or the pointwise limit?  Perhaps you could make the question clearer.
Comment: In fact, @Hurkyl's statement would follow immediately from the Riemann-Lebesgue lemma
Comment: For any $\epsilon\ne0$, the function $f(x/\epsilon)$ is not equivalent to zero. The limit of $f(x/\epsilon)$ as $\epsilon\to0$ does not exist, so there is no sense in asking whether the limit is equivalent to zero.
Comment: I suspect that if you actually mean to take a limit of *tempered distributions* rather than a limit of *functions* that the result might be zero. But the question you posted is definitely false, and the reasoning wrong.
Comment: I.e. in terms of ordinary functions, if $h(x)$ is *sufficiently nice* (e.g. being a schwartz function is probably good), I believe it is true that $$ \lim_{\epsilon \to 0} \int_{-\infty}^{\infty}  h(x) \exp(2 \pi i x / \epsilon) \, \mathrm{d}x = 0$$Pay attention to the fact this is taking a limit of the values of the integral, ***not*** the limit of $\exp(2 \pi i x / \epsilon)$.
Comment: am ok :/( i misunderstood that
Answer: You cannot take the derivative with the same $\epsilon$ as that in the function.
$$\lim_{\epsilon\to0}\frac{e^{2i\pi\epsilon/\epsilon}-1}\epsilon\ne
\lim_{\epsilon\to0}\lim_{\eta\to0}\frac{e^{2i\pi \eta/\epsilon}-1}\eta.$$
Answer: $|g(x)|=1$ for all real numbers $x$ and all $\epsilon >0$. How can $g$ be equivalent to $0$?


A bird flies for 8 seconds with a velocity of $|t-2|$ m/s in a straight line. Find distance covered by the bird.

Question: I have a tiny discrepancy which I knew how to solve, but seem to have forgotten.
$$x=\int t-2$$
I know we have to separate sovle the integral from 0 to 2 and then 2 to 8.
But in the second integral, do I put the lower limit as 2 or 3?
I tried putting 2 as the lower limit for the second integral, which gave me $16$, but the right answer is $2$
The things that's throwing me off is modulus. Because of that, the bird actually never travels in reverse, and after two seconds , the variation in velocity is linear
Comment: Try drawing the graph as this is a linear function , it would be easy to do so.
Comment: I think the right answer is 20 isn't it?
Comment: You need $\int_0^8|t-2|\mathrm{d}t$  You can't drop the absolute value sign.
Answer: Assuming the variable $t$ denotes the time in seconds since the bird has started flying, the distance $d$ in meters traveled is given by
$$d=\int_0^8|t-2|\,{\rm d}t.$$
The integrand $|t-2|$ is piecewise linear, and so indeed it makes sense to split the integral into two parts as you did:
$$\int_0^8|t-2|\,{\rm d}t=\int_0^22-t\,{\rm d}t+\int_2^8t-2\,{\rm d}t.$$
From here it is an elementary exercise in integration; we get
\begin{eqnarray*}
\int_0^22-t\,{\rm d}t&=&\left[2t-\tfrac12t^2\right]_0^2
&=&(2\cdot2-\tfrac12\cdot2^2)-(2\cdot0-\tfrac12\cdot0^2)&=&2-0&=&2,\\
\int_2^8t-2\,{\rm d}t&=&\left[\tfrac12t^2-2t\right]_2^8
&=&(\tfrac12\cdot8^2-2\cdot8)-(\tfrac12\cdot2^2-2\cdot2)&=&16-(-2)&=&18,
\end{eqnarray*}
so all in all we find that $d=2+18=20$.
Answer: Recall : $s=\displaystyle {\int} vdt$, where we have :
$t[sec]$, $v[m/s]$, and $s[m].$
$v_1(t)=2-t$ for $0 \le t \le 2;$
$v_2(t)= t-2$ for $2 \le t \le 8;$
$s= \displaystyle{\int_{0}^{2}}v_1(t)dt +\int_{2}^{8}v_2(t)dt$.
Can you finish ?


.Net Framework 3.5 reflection issues

Question: I'm using reflection to invoke a method from a dll, below the source code
ConfigurationObjectsImport configurationObjectsImport;

Assembly asm;
asm = Assembly.LoadFrom("AssemblyName.dll");
object obj;
Type TYP;
TYP = asm.GetType("CustomImport.Import");
obj = Activator.CreateInstance(TYP);
MethodInfo methodInf = obj.GetType().GetMethod("ExecImport");
object[] args = new object[1];
args[0] = configurationObjectsImport;
methodInf.Invoke(obj, args);

The class ConfigurationObjectsImport is duplicated in both current project and in dll with the same space name, but methodInf.Invoke(obj, args); throw an exception "cannot convert type Phenix_Import_Commun.Domaine.ConfigurationObjectsImport to type Phenix_Import_Commun.Domaine.ConfigurationObjectsImport".
Comment: If the types are in different assemblies, they are *not* the same type, even if they have the same name.
Comment: Why would you have a class with the exact same namespace in a dll AND in your project? That doesn't make any sense.
Comment: @bc004346 it does make sense if you think they're treated the same by the framework.  its a common misconception that if the types look the exact same that they are the same.
Comment: @bc004346 i'm saying its a common misconception.  I did not base my comment on what *you* would expect.  It's obvious from the question that the OP thinks the two types are the same because they look precisely the same.
Comment: You would have to get type definition for `ConfigurationObjectsImport` from the assembly as well.
Comment: @Amy, no I certainly would not expect the type with the same name to be treated the same when taken from the project and a DLL. What I don't understand is why would you want to have a class defined in a DLL and your project, while keeping the same class name and namespace. I know with `ananoymous` types those get to reuse the same definition even if you define it twice, but this example kinda puzzles me
Comment: Im using reflection to remove dependencie between my project and the dll . and i need to passe a complexe object  to the invoked methode.
Comment: @SoufianeToumlal So basically you both want a dependency (being able to create the object) and don't want it? You might want to move that object to a separate assembly. You will need to reference it from both.
Answer: I am assuming that configurationObjectsImport is of type Phenix_Import_Commun.Domaine.ConfigurationObjectsImport from the executing assembly, but that CustomImport.Import.ExecImport is expecting a type of the same name and namespace from AssemblyName.dll.  These are two different types that happen to have the same name (which is very undesirable).
If you really have two different types in two different assemblies with the same name, and you want to do this and/or don't have the ability to change this, you will need to create a Phenix_Import_Commun.Domaine.ConfigurationObjectsImport object using reflection from AssemblyName.dll and pass that in.
If on the other hand, you intend for them to be the same type, you will need to define that type in an assembly that is common to both assemblies (either a 3rd assembly that defines the type, or the executing assembly if AssemblyName.dll references it) and only have one type definition of that name.
Comment: thanks i will use a 3rd assembly that defines the type used by ddl and my project

.Net Framework 3.5 reflection issues


How to use YouTube API in a Windows Form for CefSharp Browser

Question: I am trying to make a web browser in CefSharp. I am also trying to make it have a web blocker for YouTube content, mostly for learning purposes on how the YouTube API works. Since there is so little documentation on the API for C#, I am confused on how I am supposed to do this. My code is located at GitHub. My code for the API is in Video.cs and Form1.cs. Here is the code for Video.cs:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Tools
{
    public class YouTubeServiceClient
    {
        private static YouTubeServiceClient instance;
        private Video video;

        public static YouTubeServiceClient Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new YouTubeServiceClient();
                }
                return instance;
            }
        }

        public Video Video { get => video; set => video = value; }

        public async Task Run(string videoId)
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var request = youtubeService.Videos.List("snippet");
            request.Id = videoId;

            // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
            var response = await request.ExecuteAsync();
            if (response.Items.Count == 1)
            {
                Video = response.Items[0];
            }
        }
    }
}

I used it and got a response sending me to Chrome to enter in my credentials.
After this I used my Form1.cs, here is the snippet that deals with it:
private async void OnBrowserAddressChanged(object sender, AddressChangedEventArgs e)
        {
            this.InvokeOnUiThreadIfRequired(() => searchBar.Text = e.Address);
            if (youtubeBlocker && Regex.IsMatch(e.Address, StringTools.WildCardToRegular("https://www.youtube.com/watch*")))
            {
                Uri addressUrl = new Uri(e.Address);
                string videoId = HttpUtility.ParseQueryString(addressUrl.Query).Get("v");

                MessageBox.Show(videoId);
                YouTubeServiceClient videoClient = new YouTubeServiceClient();

                try
                {
                    await videoClient.Run(videoId);
                }
                catch
                {
                    MessageBox.Show("FAILED");
                }

                foreach (string word in blacklistedWords)
                {
                    if (Regex.IsMatch(videoClient.Video.Snippet.Description.ToLower(), StringTools.WildCardToRegular(word)))
                    {
                        MessageBox.Show("BLACKLISTED");
                        break;
                    }
                }

            }
        }

Although I go to the right YouTube pages, my BLACKLISTED message does not pop up. I am really confused to why this might be, and been working on it for 2 days. Is there something wrong with my code? Do I need to use something else? Is there a better way? Thank you.
EDIT:
I keep on getting these errors:
[0227/083150.786:INFO:CONSOLE(0)] "The resource https://r8---sn-a8au-hp5l.googlevideo.com/generate_204 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.", source: https://www.youtube.com/watch?v=Ebp8T1HfiLk (0)

[0227/083150.789:INFO:CONSOLE(0)] "The resource https://r8---sn-a8au-hp5l.googlevideo.com/generate_204?conn2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it wasn't preloaded for nothing.", source: https://www.youtube.com/watch?v=Ebp8T1HfiLk (0)

Comment: You need to call the message boxes on the UI thread, which you are currently only setting searchbar.Text
Comment: If you are new to CefSharp then reading https://github.com/cefsharp/CefSharp/wiki/General-Usage#request-handling is recommended. There is now a default IRequestHandler implementation see http://cefsharp.github.io/api/63.0.0/html/T_CefSharp_Handler_DefaultRequestHandler.htm
Comment: I was able to view the video id from the message box, but I will try to use the UI thread. Thank you.
Answer: Turns out I was looking in the wrong place. The code for processing the description values was wrong. If you want to see how I instead used YouTube Explode, and how I fixed it, just look at the GitHub page above. Sorry if this was a stupid question, that was me just not understanding how to use the contains method. Sorry, thanks.


Is there a way to reorganize all my repeated VBoxes into a custom JavaFX tag?

Question: TL;DR is at the bottom.
I am building a Weather App in JavaFX and the set up I am using is to have 5 VBoxes displayed horizontally in a HBox that represent 5 days of weather forecast data. The problem is that all these VBoxes are virtually identical except for the actual data displayed inside them.
For example all have a Label for the date, an ImageView for the weather icon (cloudy, sunny, rainy ect.), a Label for the temperature ect. This makes my Controller class have A LOT of @FXML annotated Labels and Buttons, ImageVeiws, everything in multiples of 5.
Is there a way to organize all my elements in a custom tag called WeatherBox which would pretty much be a VBox that would house all the components for me? Instead of everything being repeated 5 times in my Controller class I would just have 5 WeatherBoxes. I've looked at some other questions extending Vboxes and HBoxes and I don't feel like I am getting the idea (or the problem they are addressing is fundamentally different). They all suggest making the WeatherBox class a Controller class with it's own FXML file and I am not sure how I would tie that all into my main fxml file that the WeatherBox tags would sit in.
Extending VBox does seem like the way to go but I don't understand how to do it properly and how to use it to solve my issue. Does anyone have some suggestions?
TL;DR I am building a weather app and I have 5 VBoxes that are all pretty much identical. They all have child Labels and ImageViews and what not. Its making my Controller class look ridiculous because there is 5 of everything (Not DRY at all). Can I/How do I reorganize everything into a custom tag extending VBox that that I can drop into my FXML that will have all the Labels, Buttons and ImageViews already built in?
package sample;

import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import sample.datamodel.DataUtils;
import sample.datamodel.Location;

import java.io.IOException;
import java.util.Optional;

public class Controller {

@FXML
private BorderPane borderPane;
@FXML
private VBox forecast1;
@FXML
private VBox forecast2;
@FXML
private VBox forecast3;
@FXML
private VBox forecast4;
@FXML
private VBox forecast5;
@FXML
private Label date1;
@FXML
private Label date2;
@FXML
private Label date3;
@FXML
private Label date4;
@FXML
private Label date5;
@FXML
private Label description1;
@FXML
private Label description2;
@FXML
private Label description3;
@FXML
private Label description4;
@FXML
private Label description5;
@FXML
private Label percipitation1;
@FXML
private Label percipitation2;
@FXML
private Label percipitation3;
@FXML
private Label percipitation4;
@FXML
private Label percipitation5;
@FXML
private Label temperature1;
@FXML
private Label temperature2;
@FXML
private Label temperature3;
@FXML
private Label temperature4;
@FXML
private Label temperature5;
@FXML
private ImageView img1;
@FXML
private ImageView img2;
@FXML
private ImageView img3;
@FXML
private ImageView img4;
@FXML
private ImageView img5;
@FXML
private Button details1;
@FXML
private Button details2;
@FXML
private Button details3;
@FXML
private Button details4;
@FXML
private Button details5;
@FXML
private Button otherLocsButton;
@FXML
private Button todaysWeatherButton;
@FXML
private Button fiveDayButton;
@FXML
private Button refreshButton;
@FXML
private ListView<Location> locListView;

public void initialize() {
    locListView.setItems(DataUtils.getInstance().getLocations());
    locListView.getSelectionModel().selectFirst();
    fiveDayButton.fire();
}

@FXML
public void refresh() {
    Location location = locListView.getSelectionModel().getSelectedItem();
    location.updateWeather();
    fiveDayForecast();

}

@FXML
public void fiveDayForecast() {
    Location location = locListView.getSelectionModel().getSelectedItem();
    location.updateWeather();
    Location.Day[] days = location.getDays();
    Location.Weather weather;
    VBox[] wthrPanes = {forecast1, forecast2, forecast3, forecast4, forecast5};
    Label[] dates = {date1, date2, date3, date4, date5};
    Label[] description = {description1, description2, description3, description4, description5};
    Label[] percipitation = {percipitation1, percipitation2, percipitation3, percipitation4, percipitation5};
    Label[] temp = {temperature1, temperature2, temperature3, temperature4, temperature5};
    ImageView[] images = {img1, img2, img3, img4, img5};

    for (int i = 0; i < days.length; i++) {
        weather = days[i].getWeather()[0];
        String date = days[i].getDate();
        String dateFormat = date.substring(5, 7) + "." + date.substring(8, 10);
        dates[i].setText(dateFormat);
        Image image = new Image("WeatherIcons/png/001-windy-2.png");
        images[i].setImage(image);
        images[i].setFitHeight(50);
        images[i].setPreserveRatio(true);
        String des = weather.getDescription();
        double tempMax = weather.getMaxTemp();
        double tempMin = weather.getMinTemp();
        double percip = weather.getPrecipitation();
        temp[i].setText(tempMax + "\\" + tempMin);
        percipitation[i].setText(Double.toString(percip));
    }
}

@FXML
public void addLocationDialog() {
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.initOwner(borderPane.getScene().getWindow());
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("newLocationDialog.fxml"));
    try {
        dialog.getDialogPane().setContent(loader.load());

    } catch (IOException e) {
        System.out.printf("New Item Dialog didn't load.");
        e.printStackTrace();
        return;
    }
    dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
    dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);

    Optional<ButtonType> result = dialog.showAndWait();
    if (result.isPresent() && result.get() == ButtonType.OK) {
        NewLocationController controller = loader.getController();
        Location location = controller.newLocation();
        location.updateWeather();
    }
}

@FXML
public void forecastDetails(Event event) {
    System.out.println(event.getEventType().getName());
    Button button = (Button) event.getSource();
    button.getId();
}

}
And here is that FXML file associated with Controller. Note that all the VBoxes are pretty much the same and not following the DRY principle.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.ImageView?>
<BorderPane fx:id="borderPane" xmlns="http://javafx.com/javafx/10.0.2-internal"
            xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">

        <GridPane fx:id="gridPane" alignment="TOP_CENTER" hgap="50" prefHeight="400.0" vgap="30" gridLinesVisible="true">
            <columnConstraints>
                <ColumnConstraints percentWidth="15"/>
                <ColumnConstraints percentWidth="15"/>
                <ColumnConstraints percentWidth="15"/>
                <ColumnConstraints percentWidth="15"/>
                <ColumnConstraints percentWidth="15"/>
            </columnConstraints>

            <VBox fx:id="forecast1" GridPane.columnIndex="0" GridPane.rowIndex="0" alignment="TOP_CENTER">

                <ImageView fx:id="img1"/>

                <Button fx:id="details1" text="Details" onAction="#forecastDetails"/>
            </VBox>

            <VBox fx:id="forecast2" GridPane.columnIndex="1" GridPane.rowIndex="0" alignment="TOP_CENTER">

                <ImageView fx:id="img2"/>

                <Button fx:id="details2" text="Details" onAction="#forecastDetails"/>
            </VBox>

            <VBox fx:id="forecast3" GridPane.columnIndex="2" GridPane.rowIndex="0" alignment="TOP_CENTER">

                <ImageView fx:id="img3"/>

                <Button fx:id="details3" text="Details" onAction="#forecastDetails"/>
            </VBox>

            <VBox fx:id="forecast4" GridPane.columnIndex="3" GridPane.rowIndex="0" alignment="TOP_CENTER">

                <ImageView fx:id="img4"/>

                <Button fx:id="details4" text="Details" onAction="#forecastDetails"/>
            </VBox>

            <VBox fx:id="forecast5" GridPane.columnIndex="4" GridPane.rowIndex="0" alignment="TOP_CENTER">

                <ImageView fx:id="img5"/>

                <Button fx:id="details5" text="Details" onAction="#forecastDetails"/>
            </VBox>
        </GridPane>

    <top>
        <VBox>
            <MenuBar>
                <Menu text="Location">
                    <MenuItem text="Change Location" />
                    <MenuItem onAction="#addLocationDialog" text="Add New Location" />
                </Menu>
            </MenuBar>
            <ToolBar>
                <Button fx:id="otherLocsButton" text="Other Locations" />
                <Button fx:id="todaysWeatherButton" text="Today" />
                <Button fx:id="fiveDayButton" onAction="#fiveDayForecast" text="5 day" />
                <Button fx:id="refreshButton" onAction="#refresh" text="Refresh" />
            </ToolBar>
        </VBox>
    </top>
    <left>
        <VBox>
            <ListView fx:id="locListView" />
        </VBox>
    </left>
</BorderPane>
Comment: Have you looked at tutorials on creating custom controls?  This can be accomplished in several ways.  Here is an example: https://noblecodemonkeys.com/javafx-custom-controls-and-scenebuilder/
Comment: The tutorial that taught me JavaFX left subclassing out. I did give youtube a cursory browse but I couldn't find anything about subclassing the layouts specifically. All seemed to be about JavaFX layouts in general. Think you provided looks promising though. I'm watching the  video now.
Comment: Of course this *could* be done extending an existing layout, but this is a quick and dirty approach, since the user of the class still has full access to the `children` list and could easily mess up the internals of your class by modifying that list. The better approach would be to extend `Control` and create the visual structure from the skin. This requires writing a bit more code though and makes integrating fxml much harder. Regardless of how you design the new node type, you should be able to use it as fxml element with the class name as name...
Answer: Here is an example:
main FXML:
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>

<?import sample.WeatherBox?>

<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <VBox prefHeight="200.0" prefWidth="294.0">
         <children>
            <Button mnemonicParsing="false" text="Button" />
               <WeatherBox dateText="example1" descriptionText="description1"/>
               <WeatherBox dateText="example2" descriptionText="description2"/>
         </children></VBox>
   </children>
   <columnConstraints>
      <ColumnConstraints />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints />
   </rowConstraints>
</GridPane>

WeatherBox.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<?import javafx.scene.image.ImageView?>
<?import javafx.scene.text.Font?>
<fx:root type="VBox" xmlns:fx="http://javafx.com/fxml">

    <ImageView fx:id="img"/>

    <Button fx:id="details" text="Details" onAction="#forecastDetails"/>
</fx:root>

WeatherBox.java
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;

import java.io.IOException;

public class WeatherBox extends VBox {

    @FXML
    private Label date;
    @FXML
    private Label description;
    @FXML
    private Label temperature;
    @FXML
    private Label percipitation;
    @FXML
    private Button details;
    @FXML
    private ImageView img;

    public WeatherBox() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("WeatherBox.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    @FXML
    protected void forecastDetails() {
        System.out.println("The button was clicked!");
    }

    public String getDateText() {
        return date.getText();
    }

    public void setDateText(String dateText) {
        this.date.setText(dateText);
    }

    public String getDescriptionText() {
        return description.getText();
    }

    public void setDescriptionText(String dateText) {
        this.description.setText(dateText);
    }
}

you have to use controller class in order to define how logic will work.
Comment: Sorry I haven't thanked you yet. Your solution was exactly what I was looking for and it worked like a charm. I suppose my main confusion why I have to load an fxml file to associate with the class and have the class function as a controller as well. Seeing it action as a solution to my problem made it all click. Thanks again!


Is the sum of conditionally independent random variables independent?

Question: Let's say I have three random variables $X,Y,Z$ such that  $X$ is independent of $Z$ and $Y$ is independent of $Z$.
Is it true that $X+Y$ is independent of $Z$?
Answer: No.
The classical example is to take $X,Y$ independent Bernoulli$(1/2)$ random variables (uniformly distributed on $\{0,1\}$), and set $Z\stackrel{\rm def}{=}X+Y \bmod 2$.
$X,Y,Z$ are pairwise independent (more than what you ask), yet $X+Y$ is clearly not independent of $Z$.
Comment: I didn't know about the \bmod command. Thanks!
Comment: For several seconds I was tempted to answer "yes" and then realized that when I looked at it rigorously it was a lot harder to prove than I thought.  Once as an undergraduate I wondered why I had trouble coming up with a routine $\varepsilon$-$\delta$ proof that if $f$ is differentiable on some interval containing $a$ and $f'(a)$ is positive then $f$ is increasing on some (posisbly smaller) interval containing $a$. Then I found a similar reason why that was harder than I thought!  If pairwise independence had been asked about I'd have thought of this example immediately. $\qquad$
Comment: The "b" stands for "binary" and it means that this "mod" is formatted according to the conventions for binary operators (such as a plus sign). $\qquad$
Comment: Yes, the spacing of $\mod 2$ always bugged me, I never realized it was simply because it was not the right operator for what I was trying to do...


"A Simple Proof of Zorn's Lemma" article. (explanation of a step)

Question: There is a short proof of Zorn's lemma by J.W.Lewin:
A Simple Proof of Zorn's Lemma.pdf
Summary:
I don't understand this step:
"Therefore if z is the least member of
$A\setminus P(B, y)$, we have $P(A, z) = P(B, y)$."
I'm interested in both  inclusions from left to right and from right to left.

A subset A of X is conforming if the following two conditions hold:

The order $<$ is a well order of the set A.
For every element $x\in A$, we have $x = f(P(A, x))$.

Theorem
 If A and B are conforming subsets of X and $A\neq B$, then one of these two sets is an initial segment of the other.
Proof We may assume that $A\setminus B\neq\emptyset$. Define x to be the least member of
 $A\setminus B$. Then $P(A, x) \subseteq B$. We claim that $P(A, x) = B$. To obtain a contradiction,
 assume that $B\setminus P(A, x)\neq\emptyset$, and define y to be the least member of
 $B\setminus P(A, x)$. Given any element $u\in P(B, y)$ and any element $v\in A$ such that
 $v < u$, it is clear that $v \in P(B, y)$. Therefore if z is the least member of
 $A\setminus P(B, y)$, we have $P(A, z) = P(B, y)$. (???)
Answer: $P(A,z)\subseteq P(B,y):$
if $\alpha\in P(A,z),$ then $\alpha\in A$ and $\alpha<z$ so $\alpha$ is in $A$ but $\textit{not}$ in $A\setminus P(B,y)$  (by definition of $z$), so in fact $\alpha\in P(B,y).$
$P(B,y)\subseteq P(A,z):$
if $\alpha\in P(B,y),$ then $\alpha\in B$ and $\alpha<y$ so $\alpha\in P(A,x)$ (by definition of $y$). Now, $\alpha \neq z$ (because $z\notin P(B,y)$). On the other hand, if $z<\alpha$, then since $\alpha\in P(B,y),$ we have $z\in P(B,y)$, which is a contradiction. Therefore, we have that $\alpha<z$ and $\alpha\in A.$ That is, $\alpha\in P(A,z).$
Comment: The only one step I don't understand. It is clearly proved that $z\notin B$ by $(z<y)$(transitivity z<a and a<y) and def of z. Now, how to show that $z\in B$? (In order to prove $z\in P(B,y)$)
Comment: I hope I added details to your answer in my answer, @Mathematleta . Maybe there exist a shorter proof. Our proofs of this particular case are identical, aren't they?
Answer: Here I want to clarify part of the
@Matematleta's proof which took some of my time.

On the other hand, if $<$, then since $\in (,)$, we have
  $\in (,)$, which is a contradiction.

We assume that $<$.
1) From $\in A\setminus (,)$, we obtain $z\in A \land [z\notin B\lor z\geqslant y]$
2) The second OR-case $z\geqslant y $ implies contradiction:
$z\geqslant y >\alpha>z$. That means that $z\notin B$.
3) $z \in A \land z\notin B$ implies $z\in A\setminus B$.
y is the least element of $A\setminus B$. So $y\leqslant z$.
4)Then $z<\alpha<x\leqslant z$ - contradiction.
That means that the assumption $<$ is false.
p.s. Proof of the 4th proposition:
$\alpha < x$ here is from $\alpha\in P(A,x)$.
In it's turn, this is from $\alpha\in B$ and $\alpha\notin B\setminus P(A,x)$. Proposition $\alpha\notin B\setminus P(A,x)$ is true because $\alpha\in B\setminus P(A,x)$ leads to a contradiction: $y\leqslant \alpha< y$.
Comment: Actually, $x$ is the least element of $A \setminus B$ right? Not $y$. The conclusion would be the same though... And thanks for this clarification.
Answer: Actually this proof is not correct!
Suppose that X is a partial order under ≤. Let Low(A) and Up(A) be respectively the sets of all strict lower bounds and all strict upper bounds of a subset A of X; and let P(A, x) be all strict predecessors of x in A, i. e. A ∩ Low({x}).
Let g a choice function that assigns to every non-empty set one of its elements; and let  f be a function that assigns to every chain C in X the strict upper bound f(C) = g(Up(C)).
Now suppose that x and y ∈ X are incomparable (not x ≤ y and not y ≤ x) and that A = {x} and B = {y} and that g(the union of A and Up(A)) = x and g(the union of B and Up(B)) = y. So x = f(P(A,x)) and y = f(P(B,y)).
Now the sets A = {x} and B = {y} are conforming as defined in Lewin's paper, because both are well-ordering and the second condition holds for both. But we supposed that x and y are incomparable; so are the sets A = {x} and B = {y}. So the whole lemma in the bottom of the first page of the paper is incorrect.
Comment: Two sets $A = \{a\}$ and $B=\{b\}$, with $a\neq b$, cannot be both conforming, because the choice function will select for at most one of $a$ and $b$ among $X$, which is the set of strict upper bounds of the empty set.


Find the fixed point for map and determine the stability

Question: Find the fixed points for the map  $x_{n+1}=x_n^2$
 and determinee their stability.
I did
$x_1=x_0^2$
$x_2=x_1^2=x_0^4$
and sketch a graph but couldnt continue
Answer: A fixed point is a point $x$ such that $x^2=x$, ie either zero or 1. Now, zero is stable, because if $|x_1|<1$ then $x_n \rightarrow 0$, but one isn't stable, because if $x_1$ is greater than 1 then repeated squaring will take $x_n$ to infinity, and if $x_1$ is a bit smaller than 1 then $x_n$ converges to zero.


SLES 10 Sp3 VMware tools error on install

Question: I installed SUSE enterprise server 10 SP3 on a Esx 4 server
The problem starts with the installation of vmware tools. "VmwareTools-4.0.0-193498.tar.gz"
The tools wont start: Unable to start services for vmware tools
Paravirtual ISCSI module: Failed
Guest vmxnet fast network device: Failed.
I fixed the guest vmxent ERROR by changing the NIC mode.
any hint? i cant be the only one with the same problem..
Answer: Have you tried to use the Operating System Specific Packages supplied by vmware?
http://www.vmware.com/download/packages.html
I have much better luck installing the binary package via rug than building from the tar file.
Give it a shot an see if it helps.
Answer: The OSPs from VMWare's repositories won't install either, they get halfway through and the transaction fails horribly, leaving you with several of the rpms install but two (the nox-mouse and nox-display-drv or something close to those) are installed halfway and can't be reinstalled/repaired or removed from your system cleanly.  It seems we really need VMWare to get off the ball and create some rpms that work on SLES 10 SP 3.
Note: the two that fail do so because of their scripts, you can force the removal of them if you've tried to load them via:  rpm -e --noscripts


Snappy - Wrong conversion from pixel to lat long

Question: I'm using snappy to try to find out what are the x,y coordinates in order to crop an image.
I've done a few tests using snappy functions but i've noticed that there is something wrong with them. I've converted a X,Y from the image to latitude and longitude and then,using those coordinates, I tried to convert them again into X,Y but i didn't get the same result.
The idea or final purpose is to get the LatLong coordinates from a geojson, read them, and using those coordinates get the X,Y in the image.
Notice that the path refers to a tiff file.
from snappy import ProductIO
from snappy import PixelPos, GeoPos
import numpy as np

path='/home/.../x.tiff'
###############################################################################
product = ProductIO.readProduct(path)
sg = product.getSceneGeoCoding()

def LatLon_from_XY(ProductSceneGeoCoding, x, y):
    #From x,y position in satellite image (SAR), get the Latitude and Longitude
    geopos = ProductSceneGeoCoding.getGeoPos(PixelPos(x, y), None)
    latitude = geopos.getLat()
    longitude = geopos.getLon()
    return latitude, longitude

latitude, longitude = LatLon_from_XY(sg, 11048, 1365)

print('LatLong from PixelPosition')
print(latitude)
print(longitude)
### 38.3976151718
### -5.47978868123

###############################################################################

def getPixelPosFromLatLong(source, lat,lon):
    if sg.canGetPixelPos() is not True:
        raise Exception('Cant''t get Pixel Position from this source')
    else:
        pos = GeoPos(lat,lon)
        pixpos = sg.getPixelPos(pos,None)
        X = np.round(pixpos.getX())
        Y = np.round(pixpos.getY())
    return [X,Y]

[X,Y] = getPixelPosFromLatLong(path, 38.3976151718, -5.47978868123)

print('Pixel Position from LatLong')
print(X)
print(Y)
### 10715.0
### 1143.0

Is there any other way to get the X,Y pixel from an image using lat long?
Answer: For those of you who are wondering about the same problem I find out this solution:
Change the path to refers not to a .tiff file but the folder .SAFE
Then, I write again my functions and now it looks like this:
from snappy import ProductIO
from snappy import PixelPos, GeoPos
import numpy as np

def LatLon_from_XY(ProductSceneGeoCoding, x, y):
    geoPos = ProductSceneGeoCoding.getGeoPos(PixelPos(x,y),None)
    lat = geoPos.getLat()
    lon = geoPos.getLon()
    return lat,lon

def XY_from_LatLon(ProductSceneGeoCoding, latitude, longitude):
    pixelPos = ProductSceneGeoCoding.getPixelPos(GeoPos(latitude, longitude),None)
    x = np.round(pixelPos.getX())
    y = np.round(pixelPos.getY())
    return x,y

###############################################################################

#Notice that the path does not refer to any file but to the folder .SAFE
path = '/.../X.SAFE'
product = ProductIO.readProduct(path)
sg = product.getSceneGeoCoding()
originalX = 13000
originalY = 13000

print('Original X,Y: ', originalX,originalY)

lat,lon = LatLon_from_XY(sg, originalX, originalY)
print(lat,lon)

x,y = XY_from_LatLon(sg,lat,lon)
print(x,y)

originalLat = 37.36475504265766
originalLon = -5.972416873450527

print('Original Lat,Lon: ', originalLat, originalLon)

x,y = XY_from_LatLon(sg, originalLat, originalLon)
print(x,y)

lat,lon = LatLon_from_XY(sg, x, y)
print(lat,lon)

This way, I get almost the same values (13000 ~ 13006)


What is Salon music?

Question: I have read that Chopins Minute Waltz was a great 'Salon' piece. What does this mean, for music to be 'Salon Music'?
Comment: From [wikipedia](https://en.wikipedia.org/wiki/Salon_music): Salon music was a popular music genre in Europe during the 19th century. It was usually written for solo piano in the romantic style, and often performed by the composer at events known as "Salons".
Comment: I concur with @hillin: the Wikipedia entry is a good place to start looking for an answer.
Comment: It means it's good music for drinking and carousing....    oops - sorry I thought you said _saloon_ music...
Answer: I suppose someone ought to make the comment into an answer!
Salon music was indeed popular in the 19th century in Europe, at events which were called 'salons'. It comprise usually short solo piano pieces, which were often virtuosic. Fantasia were played, often using popular operatic themes, which were played in ways trying to 'paint a scene'.
Chopin would have been in somewhere near the beginning of salon music, and Liszt would certainly have enjoyed playing at such events.
Comment: I've also heard of salon music also being an American phenomenon.
Comment: @Dekkadeci  - do you mean stuff played by a cowboy on an out of tune piano in a bar with the tumbleweed rollin' by?
Comment: Maybe. I think I've seen American waltzes and maybe even ragtime among the salon pieces.
Comment: @Dekkadeci - I reckon that's '*saloon'*...

What is Salon music?


java.lang.VerifyError during ejb method call

Question: When I try to call a method from a local ejb I have this error :
<code>java.lang.VerifyError: com/pwc/lu/ejb/hcfollowup/staff/HCFStaffManagerLocal.getPersonById(Ljava/lang/Integer;)Lcom/pwc/lu/mapping/hcfollowup/hibernate/global/Person;
</code>
HCFStaffManagerLocal is my local interface and getPersonById an ejb method. Person, the result type.
I can get my ejb but error occurs when trying to call getPersonById method.
I don't understand why it get an exception for Person class...
Any ideas ?
Comment: could be a bug in JDK 1.5 - which version you using?
Answer: This question on VerifyError has a lot of good answers - hope one leads to a solution!
There's a chance that the compiled Person class is corrupt and it's worth a try to recompile it with a different java SDK.
Comment: Do you think that ejb interface method getPersonById(Integer personId) and ejb method call : getPersonbyId(int) can be an issue ?
Comment: No. The Error indicates that the (binary) Person class is corrupt and can't be loaded into the virtual machine. The problem is outside the Java code.
Comment: Ok I will try to rebuild the entire project
Comment: I have news :

My application works with IceFaces jsf framework. To use it I have to inverse the classloader of the web module. When I don't do it, there is no problem with my ejb call.
Problems only occurs when the classloader is inversed...

I don't understand


Taxonomy view page for double nested terms

Question: I have a content type that has an entity reference to a taxonomy term. The referenced taxonomy term has furthermore taxonomy terms referenced to it.
On the taxonomy term view page, I would like the content appear, that refers to the terms nested inside first term reference.
The idea of double nested content and display on the taxonomy view page worked for me well, when I used for the first level nesting another content type instead of a taxonomy term. That way I could successfully apply following relationship and contextual filter on the view. I added a relationship to the entity reference field's content and applied it to the contextual filter.
Now, wanting to use a taxonomy term as first level reference, I am not able to get it work. I thought the following should work, but it does not:
What relationship do I have to apply, to get the desired result?
(I hope I was able explain my problem comprehensibly)
Edit:
The schema is following:
NODE 1 > TERM 1 > TERM 3
NODE 2 > TERM 2 > TERM 3
TERM PAGE (taxonomy/term/3)
SHOW: NODE 1 + 2

The nodes have the reference field "field_key_data" that references
the vocabulary "architecture". The terms in the vocabulary
"architecture" have a term reference field "field_style" (TERM 1 or
TERM 2) of another vocabulary.
The term in "architecture" may be different, but can reference to the same value in "field_style" (TERM 3).
If this is the case, the TERM PAGE for term 3 should show as
result NODE 1 and NODE 2.
Futhermore the result should be displayed with depth.
Answer: Show only grandchild nodes on Taxonomy term pages
In more words: Add nodes to Taxonomy term pages that are tagged with terms that reference the term shown on that page. This means that nodes that directly reference the TID will not be shown. Instead, we show nodes that have an additional Taxonomy link in between, a sort of grandchild connection.
We first introduce the "parent" connection (in your case it's "Architecture" from field_key_data). Then through it we bring in grandparent "Style" information from field_style. Since we want to show nodes that relate to that TID through that "lineage" we simply use Term ID Contextual filter with the "grandparent" Relationship.

Clone (Duplicate) the default Taxonomy term View (which is of Content type). It already has one Contextual filter (Has Taxonomy Term ID) that is responsible for showing all nodes tagged with that term. Remove it, we don't want parents, we're only interested in grandparent.
Add a Relationship Taxonomy term referenced from field_key_data.
Add another Relationship Taxonomy term referenced from field_style, it will use the first Relationship.
Add a new Contextual Filter Term ID, make it use the second Relationship, and configure it:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
Style (or whatever in your case)
Under Query settings choose Distinct because you'll see duplicated results because Relationships introduce many connections so to prevent it Distinct only shows each node once.

No need for Contextual OR BTW, we only have one Contextual filter anyway :)
BTW you can "require" both Relationships since this entire scheme relies on existence of grandchildren.
Comment: Thank you very much once again. With your explanation, I was able to display this grandchild relationship. But the reason I did not manage it by myself before is unfortunately the reason, why my problem is still not resolved: Before, I tried to use the contextual filter "has taxonomy ID (with depth)" (with the same relationship) as I furthermore need to display the results with depth. Is there a chance to display the depth of the grandchildren, too? (I added this to my question as it was only described on the screenshots)
Comment: By using the same relationship with the "has taxonomy ID (with depth), I get some strange - for me unexplainable – results: It shows some correct results, but not all and not for the whole depth.
Comment: What do you mean "displayed with depth"? The views results are nodes that are tagged with a specific term, it's just that the node is connected through 2 connection instead of a direct one connection. "With depth" can produce unexpected results with Relationships. My answers already introduces hierarchy information through Relationships. "With depth" is a different approach.
Comment: If TERM 3 ist the child of another TERM 4 of the same vocabulary, I would like the NODE 1 and 2 be also listed on the term page of TERM 4. I was able to achieve it by using another content type (NODE 1 > NODE other content type > TERM 3). The actual funcionality: https://imaginoso.com/t/modernism/brutalism (term modernism is the child of brutalism). But I would prefere to use a taxonomy (for several reasons) instead of another content type for the nesting.
Comment: That is exactly what this answers gives steps for. The node that is tagged with term 3 will be displayed on term 4 page if you configure it like in this answer. If you need something different you have to ask a different question and give all the relevant information.
Comment: Unfortunatly I do not get the desired result with the configuration above. The steps above give me following result: https://dev.imaginoso.com/t/modernism
The correct result must be following https://imaginoso.com/t/modernism. So obviously something of my description is not clear and comprehensivel. As I said TERM PAGE 3 shows the correct result (all nodes that are tagged with the grandchild term), but it does not work for the term one level above of the same vocabulary. But thank you for your efforts in any way.
Comment: I think adding "Contextual filter OR" and "Parent term" will maybe take me to a solution, I will only have to try out how to get the "grandparent term", "great-grandparent term".
Answer: Add cousin nodes to Taxonomy term pages
In more words: Add nodes to Taxonomy term pages that are tagged with terms that reference the term shown on that page.
Node > Original Term > Referenced term > Other nodes
Node is tagged with some term, that term has a field referencing another term, the other term also has nodes tagged with it. So it's kind of a cousin relationship between nodes.
What is required is a Contextual filter that filters out nodes tagged with a term, OR nodes tagged with a term that references the original term.
To do that we need to use Views Contextual Filters OR module.

Clone the default Taxonomy term View (which is of Content type). It already has one Contextual filter (Has Taxonomy Term ID) that is responsible for showing all nodes tagged with that term. You can leave that active.
The second Contextual Filter has to display nodes that have been tagged with terms that reference the "original" node. We have to add Relationships to introduce that new information into the Views.
Add a Relationship to Taxonomy terms (term).
Add another Relationship for the Taxonomy field referencing another Taxonomy field, it will use the first Relationship.
Add a new Contextual Filter for that same Field between Terms, make it use the second Relationship, and set it to display all results.
Under Query settings choose Contextual filters OR.

Now if your term 1 is referencing term 2, if you go to taxonomy/term/1/2 it will show all nodes tagged with term 1 AND also all nodes that are tagged with term 2.
Comment: First of all: Thank you so much that you take your precious time trying to understand my problem and help me find a solution. I am not 100% percent sure if I was able to explain my problem properly and if you understood it the right way. I could not resolve my problem with your solution, but I am also not sure if I applied it correctly, this is why I improved my original question.

As relationships I took "Taxonomy term referenced from field_key_data" and then
"Taxonomy term referenced from field_style". But I did not know what "same Field between Terms" means (I tryed several options).
Comment: Thank you for the clarification. Sometimes the structure can be difficult to explain. Your question now seems to be about second cousins, not cousins. I expect it will be a different approach, maybe even easier to solve. I'll add a new answer if I figure it out.


What is the biggest comeback recorded in competitive international soccer matches?

Question: On October 16, 2012, Sweden came back from 4-0 down to draw 4-4 with Germany in a World Cup qualifier. Purely in terms of goals, is this the record for the biggest comeback in a competitive international match (ie. ignoring friendlies and contests over two legs)? If not, which match holds the record?
(For avoidance of doubt, I'm interested in country vs country matches, not matches between clubs from different countries).
Answer: If we stick to a single game, VfL Bochum - Bayern München in 1976 (11 goals). Bochum were 3-0 up by the half-time whistle and 4-0 in 53th minute. In the next 20 minutes, Karl-Heinz Rummenigge and Gerd Muller took Bayern to an unbelievable 5-4 lead.
Kaczor put Bochum level on 5-5 in the 80th minute and that seemed to be it, but with a minute to go Uli Höness scored his second and Bayern's sixth for their most amazing win ever.
Over two legs, and I'm only including it because of how amazing it sounds, Bayer Uerdingen - Dynamo Dresden in 1986. A team of numerous East German stars built a 2-0 lead in the first leg at home and then ran away with a solid 3-1 lead at half time, seemingly clinching the tie in the return game at Krefeld. Dynamo were 5-1 ahead on aggregate, and the 1-3 scoreline stood until the 57 minute. The Icelander Gudmundsson won that dubious penalty kick, which Wolfgang Funkel converted. Six minutes later Gudmundsson himself made it 3-3. Then the unlucky forward Minge deflected a shot into his own net, and the Easterners found themselves utterly disoriented amidst roars from the partisan crowd. Bayer attacked in waves and the reserve Klinger brought the temperature to boiling point with the fifth goal 12 minutes from time.
5-5 on aggregate, but Dynamo were still ahead on the away-goals rule.
Schäfer was knocked down in the area and Wolfgang Funkel again scored from the spot, making it 6-3 only 23 minutes after the scoreboard had shown the humiliating 1-3. Before the final whistle, in the total confusion, Schäfer picked up the seventh goal, ending up on the shoulders of his mates and the fans who invaded the pitch.
Bayer Uerdingen - Dynamo Dresden (12 goals).
Source: The Top 20 Most Amazing Soccer Comebacks
Comment: Thanks for your answer. These are club matches though, and I was after international ones.
Comment: @Orangecrush Going by that, then the 4-4 draw shares the record with the USSR and Yugoslavia's 5-5 draw. I'm a little sceptical though as it rates more highly a comeback from 2-0 down, so it's clearly using metrics beyond simply goals scored and may well be missing comebacks by less illustrious nations.
Comment: @lins314159 That link has a list of internationals as well.
Answer: A real pity there aren't more complete databases out there, we Americans are spoiled with sites like http://basketball-reference.com/ for our sports.
I searched and searched.  But only came upon list after list.  But at least a list of a few decent ones could be cobbled together:

The previously noted 1952 Olympics group stage, where USSR came back
from 5-1 down to Yugoslavia to draw in the final 13 minutes, before
losing the replay.
http://russianfootballnews.com/ussr-yugoslavia-the-story-of-two-different-football-conceptions/
(or
http://www.fifa.com/tournaments/archive/mensolympic/helsinki1952/matches/round=197061/match=32383/index.html)
In 2010, Mali came back to draw from 4-0 down in the final 16
minutes against Angola... in Angola... to open the 2010 Africa Cup of
Nations.
http://www.cnn.com/2010/SPORT/football/01/10/africa.nations.angola.mali/

And a couple noteworthy junior internationals:

In the group stage of the 2003 U17 Championship, Cameroon came back from
5-0 in the final 20 minutes for a draw!
http://www.cameroon-info.net/stories/0,13091,@,portugal-and-cameroon-go-down-in-u-17-history.html.
And after all that... they were still one goal short of advancing in the
tournament.  They needed to win.
In the QF of the 1989 World Youth Championship, Nigeria came back
from 4-0 down against the USSR to tie the match, and then won the
shootout.
http://ezinearticles.com/?Flying-Eagles-of-Nigeria-Create-Football-History-at-Saudi-Arabia-1989&id=5161867

But still nothing bigger in senior team play that I could find.  Oh for a searchable database!
Answer: Germany came back from 3-0 down to beat Hungary 5-3 in 1930 in a friendly match in Dresden. Germany were trailing by three goals at half time, following a first-half hat-trick from József Takács, but scored five goals in a second-half comeback:
28.9.1930 Germany vs Hungary 5:3 (0:3)
The goals were scored as follows:
0:1 József Takács  (29.)  0:2 József Takács  (35.)   0:3  József Takács  (40.)  1:3     Richard Hofmann (59.)  2:3 Ludwig Hofmann (61.)  3:3 Johann Ludwig (74.)  4:3 Ludwig Lachner (78.)  5:3 Ludwig Hofmann (86.)
Comment: Welcome Brennich. Good find! I formatted the text and added a link to a page about the match. Please correct it if I got anything wrong.
Comment: @Fillet , good job :)
Comment: Hello Brennich , Welcome to [Sports SE](http://sports.stackexchange.com/), formatting the answer with meaningful sentences will be good.Please check [How to answer](http://sports.stackexchange.com/help/how-to-answer) for more help.


all finite start sequences of decimal representation of $\pi$ decidable?

Question: $L^1 \subset \{0,\dots 9\}^*$ consits of all finite start sequences of the decimal representation of $\pi$ (without comma). Is L decidable?
I guess it is not, but I do not know how to prove it. Help is much appreciated
Comment: @JohnDoe: By specifying an algorithm to do the decision; e.g. compute the leading digits of $\pi$ and check if they match the digits you were given.
Comment: Are you saying that $L$ contains `3`, `31`, `314`, `3141`, `31415`, and so on, but not `415926`? That would be clearly decidable.
Comment: @HenningMakholm yes. But how does one prove it? I am totally new to this topic
Answer: This is easily decidable by the following procedure:

Count the length of the input string.
Compute that many digits of $\pi$.
Accept if the digits you computed are identical to the input string; otherwise reject.

If you can't assume as a known fact that it's possible to compute digits of $\pi$, then the question becomes one about real analysis more than one about computability. There are then various possible approaches; a relatively simple one would be:
To ask whether, say, 3141592653521 is in your $L$ is to ask whether $\pi$ is between $\frac{3141592653521}{1000000000000}$ and $\frac{3141592653522}{1000000000000}$. (It can't be equal to either of these endpoints because we know $\pi$ is irrational). So what we need is to be able to compare $\pi$ to arbitrary rational numbers. We can do that by this procedure

If $x<3$ then $x<\pi$.
If $x>4$ then $x>\pi$.
Otherwise, if $\cos \frac x2 > 0$ then $x<\pi$, and if $\cos \frac x2<0$ then $x>\pi$.

For the last step we can compute the cosine from the power series:
$$ \cos x = 1 - \frac12 x^2 + \frac1{24}x^4 - \frac1{720}x^6 + \cdots + (-1)^n \frac{1}{(2n)!}x^{2n} + \cdots $$
After the first two terms (when $x<2$), this is an absolutely decreasing alternating series, which means that we can know the sign of the limit in finite time by finding the first time where we have just added something and yet the sum so far is negative, or we have just subtracted something and yet the sum so far is positive. Since we know the limit is not $0$ (the cosine of a rational number never is), this will happen sooner or later, and therefore our decision procedure terminates.
Note that all numbers encountered during this computation are rational, so we can keep everything as exact fractions throughout -- there's no floating-point arithmetic involved.


Q-Q plot interpretation

Question: Consider the following code and output:
<code>  par(mfrow=c(3,2))
  # generate random data from weibull distribution
  x = rweibull(20, 8, 2)
  # Quantile-Quantile Plot for different distributions
  qqPlot(x, "log-normal")
  qqPlot(x, "normal")
  qqPlot(x, "exponential", DB = TRUE)
  qqPlot(x, "cauchy")
  qqPlot(x, "weibull")
  qqPlot(x, "logistic")
</code>

It seems that that Q-Q plot for log-normal is almost the same as the Q-Q plot for weibull. How can we distinguish them? Also if the points are within the region defined by the two outer black lines, does that indicate that they follow the specified distribution?
Comment: This will not run on my computer as written. For example, qqPlot from the car package wants norm for normal and lnorm for log-normal. What am I missing?
Comment: @Tom, I was mistaken about the package. Evidently, it's the [qualityTools](http://cran.r-project.org/web/packages/qualityTools/index.html) package. Moreover, the example seems to be taken from [here](http://www.inside-r.org/packages/cran/qualityTools/docs/qqPlot).
Comment: I believe you are using the [car](http://cran.r-project.org/web/packages/car/index.html) package, aren't you? If so, you should include the statement `library(car)` in your code to make it easier for people to follow. In general, you may also want to set the seed (eg, `set.seed(1)`) to make the example reproducible, so that anyone can get exactly the same data points you have gotten, although it's probably not as important here.
Comment: An interesting alternative is the Cullen and Frey graph, see https://stats.stackexchange.com/questions/243973/is-my-data-gamma-distributed/305797#305797  for an example
Answer: There are a couple of things to be said here:

the shape of the CDF for the log-normal is similar enough to the shape of the CDF of the Weibull to make them harder to distinguish than the level of similarity between the Weibull and the others.
the outer black lines form a confidence band.  The use of the confidence band in inference is the same as any other standard form of Frequentist statistical inference.  That is, when values fall within the band, we cannot reject the null hypothesis that the posited distribution is the correct one.  This is not the same as saying that we know the posited distribution is the correct one.  (Note that this is a great example of what I discussed in another answer here of a situation where the Fisherian perspective on hypothesis testing would be preferable to the Neyman-Pearson.)
you need more data; your $N$ is only 20 here.
Comment: +1 on the small sample size. Using 300 samples would help to distinguish things a lot. Proton: No, you can't really distinguish distributions with a small sample. How could you? It's like trying to identify a face with 20 pixels.
Comment: There are tests for the goodness of fit of a dataset to a theoretical distribution, but I tend to think that they are inferior to qq-plots. Basically, you are not going to be able to distinguish between those distributions with $n=20$. If you think of this in terms of statistical power, your ability to reject each of the false nulls here is $\approx 5\%$. It may help you to read the answer I linked in point #2.
Comment: Is there ways for examining distributions for small sample sizes?
Comment: in fact it seems that the points lie in the confidence bands for all distributions. So we can't distinguish the distributions?
Answer:
It seems that that Q-Q plot for log-normal is almost the same as the Q-Q plot for weibull.

Yes.

How can we distinguish them?

At that sample size, you likely can't.

Also if the points are within the region defined by the two outer black lines, does that indicate that they follow the specified distribution?

No. It only indicates that you can't tell the distribution of the data as being different from that distribution. It's lack of evidence of a difference, not evidence of a lack of difference.
You can be almost certain that the data are from a distribution that is not any of the ones you have considered (why would it be exactly from any of those?).
Comment: Like the phrasing: "It's lack of evidence of a difference, not evidence of a lack of difference."

Q-Q plot interpretation


Verificando grupos com a API da Steam [PHP]

Question: Preciso descobrir qual dos GroupID's se refere a este grupo em específico http://steamcommunity.com/groups/NewSteamCommunityBeta
A lista de ID's dos grupos de um usuário eu consigo através desse request:
http://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=XXXXXXXXXXXXXXXXXXXXXXXX&steamid=76561198077945243
Como eu poderia fazer essa verificação em PHP ?
Answer: Só adicionar "memberslistxml/?xml=1" no final da URL.
Isso faz a página retornar um XML que você pode "puxar" com o cURL e XMLSimpleObject.
O link completo seria:
<code>http://steamcommunity.com/groups/NewSteamCommunityBeta/memberslistxml/?xml=1
</code>
@EDIT
Existem, na página do grupo, algumas tags que acabam por mostrar o id desse grupo:

Você pode tentar acessá-la do file_get_contents('urldogrupo'); e depois com um preg_match(); capturar essas informações.
Comment: O problema é que se eu fizer isso para cada gID ele retorna "Maximum execution time of 30 seconds exceeded" e não completa a verificação.
Comment: @RobertLang você pode tentar otimizar o seu código para rodar mais rápido ou aumentar o maximum execution time do PHP ou Fazer um banco de dados com as GroupIDs no seu servidor.
Comment: @RobertLang Acabei de procurar e, no código fonte da página, existem alguns locais que acabam mostrando o ID do grupo. Vou atualizar a resposta com essas informações.
Comment: Eu aproveitei essa ideia que você me falou de pegar as informações diretamente da página e eu vi que seria mais fácil eu verificar se o usuário é membro ou não através do botão de "Join Group" com um preg_match, o problema é que ele sempre retorna o "Join Group" mesmo quando eu já sou membro do grupo.


Basic Topology: Connectedness

Question: Suppose that E is a connected proper subset of R^n and that E is a proper subset of A which is a proper subset of the closure of E. Prove that A is connected.
I can't seem to really find a starting point. My general approach to showing a set is connected is to either reach a contradiction assuming it is disconnected or to show that the set is convex (and thus connected).
Hints are greatly appreciated!
Our definition of connectedness is: A set E is connected if and only if it cannot be separated by any pair of relatively open sets. Otherwise, it is disconnected.
Answer: The word 'proper' can be omitted at both places and the result is true in any topological space. Here is the proof: suppose $A=C\cup D$ where $C$ and $D$ are disjoint open sets in $A$. Then $E=(E\cap C) \cup (E\cap D)$. From the definition of subspace topology it is clear that $E\cap C$ and $E\cap D$ are open in $E$. By connectedness of $E$ we get $E\cap C$ or $E\cap D$ is empty. Suppose $E\cap C$ is empty. We claim that $C$ is empty in this case. Write $C=C\cap U$ where $U$ is open in the whole space. If possibel, let $x \in C$. Then $x$ is in the closure of $E$ and $U$ is an open set containing $x$. Hence there is a point $y$ in $E\cap U$. But then $y$ is in $E \cap C$ which is a contradiction. Thus $C$ is empty in this case. Similarly, in the remaining case $D$ is empty. We have proved that $A$ is connected.
Answer: Let $B_1$ and $B_2$ be two  open balls whose adherence are disjoint. $x_1\in B_1$, $E=B_1-\{x_1\}\cup B_2$, $A=B_1\cup B_2$, $E$ is a proper subset of $A$ and $A$ is a proper subset of the adherence of $E$ which is the disjoint union of the adherence of $B_1$ and $B_2$, but $A$ is not connected.
Comment: Thank you for the response, but I completely forgot to mention that E must be connected as well! Fixed now.
Answer: Suppose $f \colon A\to\{0,1\}$ is a continuous map.
The restriction of $f$ to $E$ is constant, without loss of generality we can assume $f(x)=0$ for $x\in E$.
Can it be $f(a)=1$, for some $a\in A$?

Basic Topology: Connectedness


Catch oledb Exception with a specific error code

Question: I'm trying to catch a duplicate key violation. I can see the System.OleDB.OleDBException in the Intellisense pop up, but the inner exception is null. How do I access the Error Code in the System.OleDB.OleDBException?
Greg
try
{
    MyData.ConExec(sSQL);
}
    catch (Exception ex)
{
OleDbException innerException = ex.InnerException as OleDbException;
if (innerException.ErrorCode == -2147217873)
{
    // handle exception here..
}
else
{
    throw;
}
}

Comment: Try catching the OleDBException instead of catching the general Exception.
Comment: The above code may null ref on `innerException.ErrorCode`
Answer: don't declare an instance of the exception. It will surely return empty if you do.
try
{
    MyData.ConExec(sSQL);
}
catch (OleDbException ex)
{
    // handle excpetion here...

    if (ex.ErrorCode == -2147217873)
    {

    }
}
catch (Exception e)
{
    // if other exception will occur
}

Comment: That got it. Thanks. Boy, I've been here before, but it has been a long time since I needed to trap a specific error. Thanks again. Greg


Loss to compare true labels to distribution?

Question: Say I have an input tensor like this:
# images = (?, 28, 28, 1)  # MNIST images

where the last dimension (the 1) is a pixel value (grayscale, so they're numbers on [0-255] for 256 total possibilties).
And, accordingly the last layer of the neural network outputs something like this:
# logits = (?, 28, 28, 256)

where the last dimension (256) contains the "probability" (log odds/logit)
for each color (so a number at index 256 would be the logit of white (255) being
the correct color for that pixel).
How can I write a loss function in that compares the distrubution
the model predicts (logits) to the single correct value in images?
High-level intuitions are perfectly fine (i.e., code not needed).

Optional Details.
Right now, essentially, I'm forming a 2D [BatchHeightWidthChannel, Distribution (256 cols)] tensor, and checking against a 1D tensor (images flattened). Sadly, the network always says that index zero (black) is the most probable value at test time.
import tensorflow as tf

images = tf.placeholder(tf.float32, shape=[None, 28, 28, 1])
# ...network goes here ...
logits = tf.placeholder(tf.float32, shape=[None, 28, 28, 256])

# Softmax Cross Entropy.
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
    logits=tf.reshape(logits, (-1, 256)),  # [BatchHeightWidthChannel, Distribution]
    labels=tf.to_int32(tf.reshape(images, shape=(-1,))  # [TruePixelValues]
))

If that ^ 'looks right', that's helpful too (suggests the problem is elsewhere).
Answer: I guess you are training some sort of auto-encoder, feeding it an image and checking if the reconstructed version of the image, encoded as 256 logits, is similar.
The naive thing to do would be simply encoding the image using 1-hot encoding, that means converting the image from int array of shape (28,28,1) to boolean array of shape (28,28,256), and then use this (possibly flattened) with cross entropy loss.
However, this approach has an obvious downside that it penalizes the network by the same amount whenever the pixel prediction is wrong, no matter how much wrong it is. E.g., if an original pixel is black (value 0) and gets predicted as white (value 255), it is penalized just as much as if it was predicted as nearly black (value 1) - it is still a different class.
Possibly much better way is simply changing the network to output a single number (i.e. the grayscale intensity) and use mean squared error.
Comment: There is an [implementation on git](https://github.com/anantzoid/Conditional-PixelCNN-decoder), you can use it as a reference. Btw, when linking to arxiv papers, link to the abstract instead of the pdf. People will appreciate it more :)
Comment: Hi. Thanks for the answer. I'm actually trying to implement a PixelCNN (see [here](https://arxiv.org/pdf/1606.05328.pdf)). The paper states that we want it to return a tensor of this form (in order to force it to build up a PMF for each pixel, I think...).


When does this extract change key? (Roman Numeral Analysis of Greene: 'Ode on St Cecilia's Day')

Question: Quick question regarding bar 3 in this figured bass exercise. We start off in D minor. The introduction of C naturals in bar 3, along with the fact we finish the piece in the relative FM, seems to suggest a switch to FM during said bar. I'm a bit stuck as to when this key change happens exactly
I have two sets of Roman numerals for bar 3. The first treats the III (FM) at the start of the bar as a pivot:
III/I (FM), Am (iii), dm (vi), Am (iii )BflatM (IV) FM (I) C7 (V7) FM (I).
I am not entirely happy with this answer, as the repeated use of iii chords seems strange? Also, there are many chords between the pivot and the V7 that consolidates the new FM tonality, which again seems unorthodox.
My second analysis (shown on the script) treats the Bflat M as the pivot:
Dm: III, AM (V), Dm (i), AM (V), BflatM (VI/IV FM), FM (I), C7 (V7), FM (I).
The III chord at the start of the bar is confusing, and the V7 back into F does not happen straight after the pivot, so I find this also a little strange.
So, when exactly do we move to the relative major?? Any superior Roman numerals will be gratefully received !
Answer: The essential problem is that the first chord in bar 3 is not FM; it, along with the following E, is part of a 6-5 suspension.
The pivot chord is on the third beat of bar 3. It is VI of the original Dm (i.e., a deceptive cadence) and IV of the new key, FM.
Comment: And that 6–5 suspension on the downbeat of m. 3 could also be a cadential six-four.


javaslang List of Tuples2 to Map transormation

Question: What is the most idiomatic way to transform a Stream<Tuple2<T,U>> into a Map<T,List> with javaslang 2.1.0-alpha?
    // initial stream
    Stream.of(
            Tuple.of("foo", "x"),
            Tuple.of("foo", "y"),
            Tuple.of("bar", "x"),
            Tuple.of("bar", "y"),
            Tuple.of("bar", "z")
    )

should become:
    // end result
    HashMap.ofEntries(
            Tuple.of("foo", List.of("x","y")),
            Tuple.of("bar", List.of("x","y","z"))
    );

Answer: @Opal is right, foldLeft is the way to go in order to create a HashMap from Tuples.
In javaslang 2.1.0-alpha we additionally have Multimap to represent Tuples in a Map-like data structure.
// = HashMultimap[List]((foo, x), (foo, y), (bar, x), (bar, y), (bar, z))
Multimap<String, String> map =
        HashMultimap.withSeq().ofEntries(
                Tuple.of("foo", "x"),
                Tuple.of("foo", "y"),
                Tuple.of("bar", "x"),
                Tuple.of("bar", "y"),
                Tuple.of("bar", "z")
        );

// = Some(List(x, y))
map.get("foo");

(See also HashMultimap Javadoc)
Depending on how the map is further processed, this might come in handy.
Disclaimer: I'm the creator of Javaslang
Comment: Now I know there's another tool in the toolbox. Thanks and congrats on the great library so far.
Comment: Thank you, at your service!
Answer: Not sure if this is the most idiomatic but this is job for foldLeft:
Stream
   .of(
      Tuple.of("foo", "x"),
      Tuple.of("foo", "y"),
      Tuple.of("bar", "x"),
      Tuple.of("bar", "y"),
      Tuple.of("bar", "z")
   )
   .foldLeft(
      HashMap.empty(),
      (map, tuple) ->
         map.put(tuple._1, map.getOrElse(tuple._1, List.empty()).append(tuple._2))
   );

Comment: I am learning the API, and missed the fold operations. Thanks


Como atualizar Gem no windows?

Question: Meu problema é que não consigo atualizar as gem
Baixei o rubyInstaller tentei rodar o comando para atualizar:
gem update rails --no-document

Mas infelizmente não atualiza dá o erro:
gem update rails --no-document
Updating installed gems
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)

Procurei online, mas nenhuma ajuda foi clara! Será que alguém conhece algum tutorial de como fazer funcionar?
Aprecio a ajuda!
Comment: Qual a sua versão do gem? (`gem --version`)
Answer: Quando tive esse problema resolvi usando esse tutorial, mas hoje em dia para Windows eu prefiro usar JRuby, muito menos dores de cabeça.
Comment: Esse link pode ser uma boa sugestão, mas sua resposta não terá validade se um dia o link deixar de funcionar. Além disso, é importante para a comunidade ter conteúdo aqui no site mesmo. Seria melhor incluir mais detalhes na sua resposta. Um resumo do conteúdo do link já ajudaria bastante! Saiba mais sobre o assunto neste item do nosso FAQ da Comunidade: [Queremos respostas que contenham somente links?](http://meta.pt.stackoverflow.com/q/42/74)
Answer: Acredito que o seu problema seja resolvido ao reinstalar o rubygems:

Baixe o RubyGems no formato zip
Acesse o diretório onde você descompactou o rubygems
Execute ruby setup.rb
Teste executando a atualização gem install --system

Fiz também a instalação do DevKit.

Baixar, descompactar e acessar a pasta.
Executar os comandos ruby dk.rb init e ruby dk.rb install dentro da pasta em que foi descompactado o DevKit.

Como atualizar Gem no windows?


How to get co-ordinates from address(with postcode) Swift - IOS?

Question: I have a list of addresses with postcodes, which I need to display on a map (pin point).
So far I know to use co-ordinates to show pin points on map with core-location framework. Is there any other way of doing it? Like getting co-ordinates from address or use address to show pin points on map?
The main purpose is to calculate distances between locations.
Please guide me here. Thanks
Comment: Please try to search before asking. [How can I plot addresses in Swift, converting address to longitude and latitude coordinates?](http://stackoverflow.com/questions/24706885/how-can-i-plot-addresses-in-swift-converting-address-to-longitude-and-latitude)
Comment: Thank you, some times you don't have right search string when looking for any answers..Appreciate your time and guidance
Answer: To create an annotation from an address you need to use CLGeocoder's method geocodeAddressString:
let address = "5th Avenue, New York"
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
    if let placemarks = placemarks {
        if placemarks.count != 0 {
            let annotation = MKPlacemark(placemark: placemarks.first!)
            self.mapView.addAnnotation(annotation)
        }
    }
}

If you only want to get the coordinates for the location:
...
        if placemarks.count != 0 {
            let coordinates = placemarks.first!.location
        }
...

Comment: Thank you..will try this now.
Answer: Here is the simple code snippet that shows how to show the pin on the map for the given array of address.
let geocoder:CLGeocoder = CLGeocoder()

for eachAddress in addressArray {
    geocoder.geocodeAddressString(eachAddress) { (placemarks:[CLPlacemark]?, error: NSError?) -> Void in
    //Assuming it has the data without any error
    let placemark = MKPlacemark(placemark: (placemarks?.first)!)
    self.mkMapView.addAnnotation(placemark)
    }
}


Iron Router and post.find() conditions from the database

Question: I've been trying to find a way to dynamically throw in a find() condition that comes from the database through Iron Router and a controller, is this possible? For example:
.. ..

HomeController = PostsListController.extend({
data: function() {
    return {
        posts: Posts.find({ likeDrinks: {$in: ['soda','juice']} }, this.findOptions()),
    };
}

});

.. ..

The above code works as something static. The ['soda','juice'] part is what I want to come from the database, particularly from the Meteor.user() object and in the .profile.likesSoda property. Basically, I want to filter results based on values saved in the user's profile. Unfortunately, I haven't been having much luck. When I do use Meteor.user() or Meteor.users.findOne( _id: Meteor.userId()), they're initially undefined (and eventually something comes up) so they cause errors.
Any idea why Meteor.userId() is readily accessible vs. Meteor.user() within the data() function?
Answer: Data function runs inside a reactive computation, so it will be rerun whenever Posts.find is changed or Meteor.user() is changed.
Below example shows how to safely run Posts.find without worry about undefined issue.
data:function(){
  var user = Meteor.user();
  var likesSoda = user && user.profile && user.profile.likesSoda;
  if(likesSoda){
  return   {
             posts: Posts.find({ likeDrinks: {$in: likesSoda} }, this.findOptions()),
           };
  }else{
    return {posts:[]};
  }
}

Comment: Ah dude, that's awesome! It finally works without throwing me any of those app breaking errors.