iOS:How to add a view on searchBar in UISearchDisplayController and I want the view on top of _UISearchDisplayControllerDimmingView

Question: How to add a view on searchBar in UISearchDisplayController and I want the view on top of _UISearchDisplayControllerDimmingView?
I add the view by [self.searchDisplayController.searchBar insertSubview:view3 atIndex:0];. But it was under _UISearchDisplayControllerDimmingView.
I show U the pic:

If someway to dismiss the _UISearchDisplayControllerDimmingView will help me also!
Answer: If you really want it on the top of dimView put your view on the window of Application.
UIView *view = [[[UIApplication sharedApplication]windows]objectAtIndex:0];

and add your view as subview.
Comment: Thx,U resolved my problem, but there is a small issue with your answer, which is "UIView *dim_view = [[[UIApplication sharedApplication] windows] lastObject];"
Comment: The real question is this:http://stackoverflow.com/questions/37199934/iosi-wanner-to-realize-this-search-function-bellow-and-how-to-do


showing an image field from solr index on custom solr search page

Question: I use the Apache Solr Views module to create a View that displays only items from a specific content type.
I would like to include an image as well on the view. I managed to get the images on my site indexed in solr using a custom module (field is called ss_field_image_uri). They show up in the solr index and I can add the image field in my custom solr view. So far so good.
The problem is that the field outputs as "public://folder/imagename.jpg". My question is how how I could I get the view to output not the link but the image itself?
Should I somehow rewrite the output of the image field in the view? Or use a custom php field and add some code? I cannot figure out how to do it. I am not a programmer but any pointers as to how to proceed would be very much appreciated.
Best,
Gerben
Answer: We managed to solve this with help from user Gaele Strootman.
There are three steps to solve this:
1) add the image to the solr index using a custom module
2) add the image field to your apache solr view
3) add a template file for the image field that displays the actual image
ad 1) create a custom module to add images to the solr index.
You only need two files, my_module.info and my_module.module. We name the image field ss_field_image_uri.
my.module.info:
name = Apache Solr Image
description = Add image field to the solr index so we can display images in search results
package = Apache Solr
core = 7.x

dependencies[] = apachesolr_search

my_module.module:
<?php
/**
 * Add field_image uri to apache solr index, so that we can later display image in search results or custom apache solr views page.
 * @see apachesolr.api.php
 */

function apachesolr_image_apachesolr_index_document_build($document, $node, $namespace) {
  if (isset($node->field_image['und']['0']['uri'])) $document->addField('ss_field_image_uri', $node->field_image['und']['0']['uri']);
}
?>

ad 2) add the image field to your apache solr view
First re-index solr so the images actually get indexed and show up. Then add the image field to your view.
ad 3)  add a template file for the image field that displays the actual image
This is the template we added. Since the field is called ss_field_image_uri the template name is: views-view-field--ss-field-image-uri.tpl.php. This is the code:
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php
/**
 * For additional parameters see
 * http://api.drupal.org/api/drupal/modules!image!image.field.inc/function/theme_image_formatter/7
 */
?>
<?php $variables = array('item' => array('uri' => $row->{$field->field_alias})); ?>
<?php $variables['image_style'] = 'thumbnail'; ?>
<?php print theme_image_formatter($variables); ?>

Now clean your caches and the images should show up in your apache solr view. Note that you can change the image style in the code from 'thumbnail' to whatever image style you like.
Hope this helps anyone!


Elasticsearch leaderboard with player ranking

Question: I'm trying to find the best solution to implement a leaderboard with Elasticsearch.
I store the following data in elastic: playerId, challengeId and score.
Now I want to add "position" column (based on score) but cannot find which is the most efficient way to do this in elastic.
Use case: when I get "all players by challengeId" I want to have "position" field in a response whose value is based on "score" value.
At first look documentation provides many ways to do this: aggregation, Evaluation API, feature datatype and features datatype.
Did anybody use any of these things in elastic? Can I choose one of them for ranking players in leaderboard?
Thanks in advance.
Answer: You can achieve it simply by using sort on your score field. For a better explanation, I created an index with some sample data according to your example. More info on sort feature with an example can be found in ES doc.
Index mapping
{
    "mappings": {
        "properties": {
            "pid": {
                "type": "integer"
            },
            "cid" :{
                "type" : "integer"
            },
            "score" :{
                "type" : "integer"
            }
        }
    }
}

Index sample docs

POST /_doc/1
{
   "pid" : 1,
   "cid" :1,
   "score" : 10
}
POST /_doc/2
{
   "pid" : 2,
   "cid" :1,
   "score" : 9
}
POST /_doc/3
{
   "pid" : 4,
   "cid" :1,
   "score" : 6
}
POST /_doc/4
{
   "pid" : 4,
   "cid" :2,
   "score" : 10
}
POST /_doc/5
{
   "pid" : 5,
   "cid" :2,
   "score" : 8
}

Sample query to fetch record based on cid aka challengeID and sort results based on score of pid aka playerid.
Search query
{
    "sort": [
        {
            "score": {
                "order": "desc" --> notice `desc` order on `score` field
            }
        }
    ],
    "query": {
        "term": {
            "cid": 2
        }
    }
}

The output of the above search query
"hits": {
      "total": {
         "value": 2,
         "relation": "eq"
      },
      "max_score": null,
      "hits": [
         {
            "_index": "leaderboard",
            "_type": "_doc",
            "_id": "4",
            "_score": null,
            "_source": {
               "pid": 4,
               "cid": 2,
               "score": 10
            },
            "sort": [
               10
            ]
         },
         {
            "_index": "leaderboard",
            "_type": "_doc",
            "_id": "5",
            "_score": null,
            "_source": {
               "pid": 5,
               "cid": 2,
               "score": 8
            },
            "sort": [
               8
            ]
         }
      ]
   }

Notice, search query returned 2 docs which have cid=2 and player ids are sorted in desc order of their score.


Get node id of saved node

Question: I want a function/hook to be called at a point just when my custom node type is saved, I want to get the generated node id in that function, as I have to perform some operations based on nid.
I know one solution is which form alter hook is defined and I give a custom submit function to it and that function is called just when form is submitted, but in that case node is not yet saved at that point so there is no nid.
Comment: Can you specify Drupal version?
Comment: its drupal 7, sorry for late mentioning
Comment: So just google for D7 equivalent of db_last_insert_id
Comment: but the point is where would i call this db_last_insert_id, I need a hook function for that which is called after the node submit
Answer: You can use hook_node_update().
In Drupal 6, you can easily get the last node ID by calling db_last_insert_id().

Get node id of saved node


How to use taxonomy fields with Views and avoid duplicates?

Question: I have content type 'sports venue' which is related to taxonomy vocabulary 'activity'. So a simple View of venues and activities might look like this:

Park : football, hockey, running
Pool: swimming, diving
Stadium : athletics, running

I add an image field to the taxonomy terms to show an icon for each activity. Then I want the same View as above, but showing the activity icon instead of the term name.
In the View I add a relationship to the taxonomy vocabulary and add the taxonomy icon field.
Now the View has duplicates; 3 entries for park, 2 entries for pool etc. I only want a simple list as above.
Sometimes I can get close by using grouping and aggregation settings, but it gets quite messy. Am I missing something obvious here?
Note: This comment from Merlinofchaos is relevant, but refers to D6. Now that we can add fields to taxonomy terms in D7 core, I wonder if there are more options?
Answer: I don't know if this will help, but it seems similar. (Drupal is still pretty confusing to me, so I am sorry if this is not helpful.)
I eliminated duplicate rows in my view by changing the filter criteria. I could filter with two different criteria and get the same view, but one view had duplicates and one didn't.
The filter criterion that gave me duplicates was "Content: Producer_category (taxonomy vocabulary 5)."  Producer_category is the name of a field. With this filter, if the content had multiple terms of the vocabulary applied, it appeared multiple times.
The filter that worked was "Content: has taxonomy term". After choosing this, I was prompted to select a vocabulary, and then to select term(s). I used the dropdown to display the terms. Also, Since I only selected one term for my display, i did NOT check "reduce duplicates", but I guess if you choose multiple terms you should.
Also, FYI, I was getting multiple errors when using Views since updating to Drupal 7, and I figure I probably did something wrong in the update process; all my Fields disappeared, among other things. So I ended up re-building the View from scratch. It seems like there are a bunch of new settings and options, and my view had some old, obsolete settings, and it just seemed better to start over and eliminate any hidden errors.
Good luck.


how to show error when trying to add/upload data to firebase in flutter when user is offline?

Question: I am basically trying to show an alert dialog when a user try to add a document or upload an image to firestore cloud/firebase storage. I tried that with try and catch blocks as well as .catchError() but it did not work, and it basically do this after getting an internet connection. what i want to do is to show an alert dialog and cancel the process even the user gets a connection back (he have to repeat the process of uploading again). here is a sample of my code:
this is for picking and uploading an image:
<code> Future _getImage(bool isCamera) async {
    var pickedImage;
    try {
      if (isCamera)
        pickedImage =
            await picker.getImage(source: ImageSource.camera, imageQuality: 20);
      else
        pickedImage = await picker.getImage(
            source: ImageSource.gallery, imageQuality: 20);

      if (pickedImage != null) {
        _uploadAndSetUrl(File(pickedImage.path));
      }
    } catch (e) {
      print('error here');
    }
  }

  Future _uploadAndSetUrl(File image) async {
    try {
      _uploadingStatus(true);
      StorageUploadTask uploadTask = _bookImageRef.putFile(image);
      StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
      String downloadAddress = await _bookImageRef.getDownloadURL();
      _uploadingStatus(false);
      setState(() {
        _imageUrl = downloadAddress;
      });
      print(_imageUrl);
    } on PlatformException catch (e) {
      print('error: $e');
    } catch (e) {
      print('No image added');
    }
  }

</code>
and there is another method for adding a document into firestore cloud. is there any way to do that?
thank you in advance!
Answer: try this,
<code>import 'dart:io';

Future _getImage(bool isCamera) async {
    var pickedImage;
    try {
      if (isCamera)
        pickedImage =
            await picker.getImage(source: ImageSource.camera, imageQuality: 20);
      else
        pickedImage = await picker.getImage(
            source: ImageSource.gallery, imageQuality: 20);

      if (pickedImage != null) {
      try {
        final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty)
        _uploadAndSetUrl(File(pickedImage.path));

    } on SocketException catch (_) {
    showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text("Connection Error !"),
            content: Text("Please connect to the internet."),
          )
      );
 }

      }
    } catch (e) {
      print('error here');
    }
  }
</code>
Comment: let me know if this helps


TBXML Linker Error and ARC Error

Question: I'm trying to purse a XML file with TBXML I have done to following steps to use TBXML

Click on your project main folder inside of XCode 4.0
Click on the target
Open tab called "Build Phases"
Open up "Link Binaries With Libraries"
Click "+" find the libz.dylib file
Copy the needed files (TBXML.h, TBXML.m, NSDataAdditions.h, NSDataAdditions.m) into a group in my project
added the #import "TBXML.h" on top of the page I'm going to use the library

after I add the following line (taken from the TBXML Guides) it comes up with an error that I should not use retain if I'm using Automatic Reference Counting.
TBXML * tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.w3schools.com/XML/note.xml"]] retain];

After I remove the retain I end up with
TBXML * tbxml = [TBXML tbxmlWithURL:[NSURL URLWithString:@"http://www.w3schools.com/XML/note.xml"]];

When I try to run the App it shows the Following Errors:
"_OBJC_CLASS_$_TBXML", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture i386

clang: error: linker command failed with exit code 1 (use -v to see invocation)

What should I do and how can I fix it?
Thank you
Comment: Is the "Target Membership" checkbox set for the added .m files?
Answer: Make sure that you have included your file in target i.e. it is check marked in target membership tab
Full screen image
Comment: Worked perfectly, thanks
Just for people's future reference use "-fno-objc-arc" in the compiler flag to disable ARC on TBXML.m
Answer: This error means that the linker cannot find the compiled code for TBXML - most likely because it's not actually being compiled.
Select the TBXML.m file in the navigator, then open the "Utilities" panel on the right and make sure that your target is checked under "Target Membership".
Comment: Worked perfectly, thanks Just for people's future reference use "-fno-objc-arc" in the compiler flag to disable ARC on TBXML.m

TBXML Linker Error and ARC Error


Rename x tick marks not numeric (POSIXct) ggplot

Question: I want rename the x ticks marks with name localtimeat my graphic, which is  "POSIXct" "POSIXt"
My original localtime is in Portuguese, and I want to rename to English
Dez = December
Jan = January
Fev = February
Mar = March
ps: I can't make an real example to have the similar result of plot because have more than 2000 localtimes.
dt = data.table(localtime= as.POSIXct(c("2016-10-24 12:45:06", "2016-10-24 12:46:13", "2016-10-24 12:47:02", "2016-10-24 12:48:27", "2016-10-24 12:52:39", "2016-10-24 12:55:11", "2016-10-30 21:08:02", "2016-10-30 21:18:27", "2016-10-30 21:30:13","2016-10-24 23:27:21", "2016-10-26 06:54:29")),
depth_range = c("shallow", "deep"),
dmean = c(30, 50, 200, 76, 467, 87, 98, 10, 240, 176, 89))

ggplot(dt, aes( x=localtime, xend= localtime, y=0, yend= dmean, color=depth_range))+
  geom_segment( size=1)+
  scale_colour_manual(name = "Dive category", values = c("grey70", "orangered3")) +
  scale_y_reverse()+
  xlab("Time")+
  ylab ("Dive depth (m)")+
  ggtitle("Whale ID 172001_17")+
  theme_bw()

The real plot of my data

And I tried somethings:
scale_x_discrete(labels=c("Dez"="December","Jan"="January", "Fev"="February", "Mar"= "March"))

scale_x_discrete(labels = c("December", "January", "February", "March"))

scale_x_discrete(breaks=c("Dez", "Jan", "Fev", "Mar"),
          labels=c("December", "January", "February", "March"))

scale_x_continuous(breaks=c("Dez", "Jan", "Fev", "Mar"),
                 labels=c("December", "January", "February", "March"))

scale_x_continuous (names= c("December", "January", "February", "March"))

leg2<- c("December", "January", "February", "March")
scale_x_continuous(labels = leg2)

leg2<- c("December", "January", "February", "March")
scale_x_discrete(labels= leg2)

theme(axis.text.x = c("December", "January", "February", "March"))

theme(axis.text.x = element_text("December", "January", "February", "March"))

#I tried too to convert localtime to factor, but the plot didn't work well
ggplot(dt, aes( x=factor(localtime), xend= factor(localtime), y=0, yend= dmean, color=depth_range))+

Shows that error:

Erro: mapped_discrete objects can only be created from numeric vectors

How can I fix this??
Comment: Try `+ scale_x_datetime(date_labels="%b")`, it'll label every tick with just the short month abbreviation. This will repeat month labels when the x span is short (as in this example), so other options to `scale_x_datetime` allow you to specify where to place the ticks (`breaks=` or `date_breaks=`).
Comment: but the problem is because my original data is in Portuguese, and I want to rename to English. I edited the post
Comment: One of: (1) use `scale_x_datetime(breaks=..., labels=...)`; or (2) look at `Sys.getlocale()` (in order to save the current value), then `Sys.setlocale("LC_ALL", "English")` and try the plot. (Then you may want to set it back to what it was before.) I've seen others suggest `Sys.setenv(LANG="English")`, not sure if it will affect this.
Comment: the (1) and (3) didn't rename... the (2) shows: `Warning message:
In Sys.setlocale ("LC_ALL", "English"):
   SO informs that the request to define the locale as 'English' cannot be honored`
Comment: Try `Sys.setlocale(locale="English_United States.1252")` (gathered from my answer).
Answer: I'm already in English, so I'll demonstrate by plotting into Portugeuse :-)
First, I'll save my current locale, because I don't speak Portuguese and sometimes R's errors can be confusing enough in my own language:
Sys.getlocale()
# [1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
Sys.setlocale(locale="Portuguese")
# [1] "LC_COLLATE=Portuguese_Brazil.1252;LC_CTYPE=Portuguese_Brazil.1252;LC_MONETARY=Portuguese_Brazil.1252;LC_NUMERIC=C;LC_TIME=Portuguese_Brazil.1252"

Now, I plot, adding scale_x_datetime:
ggplot(dt, aes( x=localtime, xend= localtime, y=0, yend= dmean, color=depth_range))+
  geom_segment( size=1)+
  scale_colour_manual(name = "Dive category", values = c("grey70", "orangered3")) +
  scale_y_reverse()+
  xlab("Time")+
  ylab ("Dive depth (m)")+
  ggtitle("Whale ID 172001_17")+
  theme_bw() +
  scale_x_datetime(date_labels = "%b %d")

I included "%d" because your sample data only spanned a few days; you should be able to use just "%b" (determined by ?strptime).
Note: this highlights one possibly flaw: ggplot2 doesn't know that the labelling format "%b" is no more resolute than "1 month", so if I don't include %d (day of month) in the format, ggplot2 will happily show out   out   out on the x-axis. In your real data, this might not be a problem. You can play with other options such as date_breaks="1 month" to make sure that the x axis ticks are no more frequent than 1 month ... but using that here results in no ticks, since I believe it is defaulting to the first of the month and this sample has nothing on that date. You may need to hard-code breaks= in your scale call in order to fix where they go, and/or use a function for breaks to control where the breaks go.
Comment: thank you, this code run well, but didn't rename :/. Here is `Sys.getlocale()
[1] "pt_BR.UTF-8/pt_BR.UTF-8/pt_BR.UTF-8/C/pt_BR.UTF-8/pt_BR.UTF-8"`
Comment: What happened when you tried `Sys.setlocale(locale="English_United States.1252")` before the plotting code?
Comment: just doesnt  rename the ticks
Comment: I don't know what to say. On my system, I show English, change the locale, then show Portuguese, so the premise is solid, perhaps something else with your data?
Comment: What about just `Sys.setlocale(locale="English")`? The two are synonymous on my (windows) system, perhaps they're different-enough for you?


Apache ProxyPassReverse with parameters from request

Question: I've a situation where I want to redirect everything that starts with /app to an internal server. Basically the idea is that Apache will work as a reverse proxy doing the following conversion:
http://external/app -> http://myserver:1082/myapp

I was able to do it using Rewrite, as follows:
  RewriteCond %{REQUEST_URI} ^/app
  RewriteRule ^/app(.*)$ http://myserver:1082/myapp$1 [L,P]

  ProxyPassReverse /app http://myserver:1082/myapp

It works fine. The issue is that now I'm gonna have a language preffix on the URL, but no on the application. So I need the following redirection:
http://external/app -> http://myserver:1082/myapp
http://external/en/app -> http://myserver:1082/myapp
http://external/pt/app -> http://myserver:1082/myapp

While this can be done with the rewrite, I have a problem with the proxyPassReverse. Because basically I need to do a dynamic ProxyPassRever that, depending on the actual URL request by the user, changes the Location
ProxyPassReverse /en/app http://myserver:1082/myapp
ProxyPassReverse /pt/app http://myserver:1082/myapp
ProxyPassReverse /app http://myserver:1082/myapp

It would be something like
ProxyPassReverse ${preffix}/app http://myserver:1082/myapp

Is it possible to do that?
Answer: From ProxyPathReverse:

When used inside a  section, the first argument is omitted and the local directory is obtained from the .

From Location:

The URL may use wildcards. In a wild-card string, ? matches any single character, and * matches any sequences of characters.
  Extended regular expressions can also be used, with the addition of the ~ character.

So you should be able to use:
<Location /[a-z]+/app>
    ProxyPathReverse http://myserver:1082/myapp
</Location>

Comment: Actually, that does not work, since it replaces "http://myserver:1082/myapp" for the literal string "/[a-z]+", instead of using the actual path that matched the regular expression
Comment: On the affected headers on the response.
Comment: Where does it do this replacement?


How can I alter (theme) the default content feed?

Question: How can I alter (theme) the default content feed on the front page (the list of node teasers) so that my 'thumbnail' image style is used instead of my 'medium' style for the images contained in the nodes.
All I can think of is to create my own page--front.tpl.php file or use is_front in node.tpl.php. Either way it means creating a custom listing for the front page.
Thanks.
Answer: The best way to do this if you're running stock D7 is in config: you'll want to change the default field dislpay settings by clicking "manage display" on the Article content type in admin/structure/type.
Click the gear icon to adjust the display type:


Wildcard SSL certificate not working with Chrome's built-in Flash player

Question: I'm currently working on a system that has a Flash Client talking to a remote application server via RTMPS.  The Flash Client and the app server handshake using an SSL wildcard certificate.  For instance, if my app server is on the host "blah.test.mysite.com", the SSL certificate I have (via DigiCert) is for *.test.mysite.com.  I have tested this setup and it works on IE9, Firefox 3/4 and Safari 5 with the Flash 10.2 r154 plugin, but it does not work on Chrome 10.
I believe the problem is Chrome's built-in Flash player.  In Chrome, if I go to "about:plugins", click the "Details" button on the right and click "disable" next to the Flash player plugin located at "C:\Users\\AppData\Local\Google\Chrome\Application\10.0.648.205\gcswf32.dll" and try again (using the system plugin located at "C:\Windows\SysWOW64\Macromed\Flash\NPSWF32.dll"), everything works.  But whenever I enable Chrome's built-in Flash player, my SSL handshake from my Flash client to my application server ALWAYS fails.  The two Flash players (Chrome built-in and Windows installed) are the exact same version.
Does Google modify their built-in Flash player in any way that could cause this?  Does Chrome treat the built-in Flash player differently than the one installed in the OS proper?  Any ideas at all as to what could cause this?
Thanks!
Comment: Seeing the same issue with non-wildcard SSL certificate - it appears to be a problem with RTMPS in general. Thanks for replying with your further findings, you saved me time.
Comment: So for anyone who runs into this, it has to do with how Chrome sandboxes the Flash player.  If Chrome is run with the "--disable-flash-sandbox" command line argument, the issue disappears.  No solution yet, but I'll post when I find one.
Comment: Still an issue for me on Ubuntu, adobe link https://bugbase.adobe.com/index.cfm?event=selectBug&CFGRIDKEY=3057375
Answer: So after a long discussion and a silent period, I've gotten confirmation that this is actually a bug in the current Flash Player and is being worked on.


If $a_n \to a < 0$, then $\lim \inf a_nb_n = a \lim \sup b_n$

Question: I got this proof that I can't show for some hours now. Does anyone have a hint?
If $a_n, b_n$ are bounded sequences and $\lim_{n\to\infty} a_n = a < 0$ then
$$\liminf_{n\to\infty} a_nb_n = a \cdot \limsup_{n\to\infty} b_n$$
Thanks!
Comment: Related posts: http://math.stackexchange.com/questions/768011/product-of-lim-sups
http://math.stackexchange.com/questions/776517/product-of-limitsuperior-of-bounded-sequences
http://math.stackexchange.com/questions/947822/if-limsup-x-n-x-lim-y-n-y-x-n-y-n-0-then-does-limsup-x-n-y
Answer: I would try something like this:
Let $\varepsilon > 0$. Then there exists $n_0 \in \Bbb{N}$ s.t.
$$
n \geq n_0 \implies a - \varepsilon < a_n < a + \varepsilon
$$
Now if $n \geq k_0$
\begin{align*}
(a - \varepsilon) \sup_{k \geq n} b_k & \overset{(*)}{=} \inf_{k \geq n} ( (a - \varepsilon)b_k) \\
&\leq \inf_{k \geq n} (a_k b_k) \\
& \leq \inf_{k \geq n} ((a+\varepsilon)b_k) \\
&\overset{(*)}{=} (a+\varepsilon) \sup_{k \geq n} b_k
\end{align*}
Then by taking the limit $n \to \infty$ we'd get
\begin{align*}
(a-\varepsilon) \limsup_{n \to \infty} b_n &\leq \liminf_{n \to \infty} (a_n b_n) \leq (a + \varepsilon) \limsup_{n \to \infty} b_n \\
\iff -\varepsilon \limsup_{n \to \infty} b_n &\leq \liminf (a_nb_n) - a \limsup_{n \to \infty} b_n \leq \varepsilon \limsup_{n \to \infty} b_n \\
\iff \left| \liminf (a_nb_n) - a \limsup_{n \to \infty} b_n \right| &\leq \varepsilon |\limsup_{n \to \infty} b_n|
\end{align*}
The sequence $(b_n)$ is bounded, so $|\limsup b_n| < \infty$, and the result follows.
The $(*)$ equalities feel right, but need some more justification.
Comment: Thanks! I guess for the (*) equalties I could use that -sup(A)=inf(-A) and sup(c*A)=c*sup(A). However I have to choose the E such that a+E<0 so that the second (*) equation is right.
Comment: I don't quite see how the last line is equal to what I want to prove?
Comment: Oops, had an error. Fixed it now.
Comment: I am also not quite sure by which theorem the last line is equal to what I want to prove. How do I see the equalit yin this inequality?
Comment: It's basically the [squeeze theorem](http://en.wikipedia.org/wiki/Squeeze_theorem). Our $\varepsilon$ was arbitrary, so we can take the limit $\varepsilon \to 0$.
Comment: Can we really do this since we said that E>0?
Comment: Define $A = \limsup b_n$ and $B = \liminf a_n b_n$ Then for all $\varepsilon > 0$ we have $aA - \varepsilon a \leq B \leq aA + \varepsilon A$. Equivalently $- \varepsilon a \leq B - aA \leq \varepsilon a \iff |B-aA| \leq \varepsilon a$.


Data in multiple dropdowns

Question: I have a form which contains 10 dropdown controls.  Each control will be populated with the same 20 rows of data which are selected from a db table.
What I want to do is ensure that when the final choice is made there are no duplicates.
I could easily just do some error checking when I save the data, but maybe there is a slick way of hiding or graying out the items once they are chosen with javascript.
Has anyone done anything like this?
Answer: You could remove items from the other dropdowns when an item is selected in one. So other dropdowns want have that item for selection.

Data in multiple dropdowns


For real square matrices $A_0,A_1$ with $(A^{T}_0+A_0)+(A^{T}_{1}+A_1)\leq{-\gamma{I}}$, is it possible to prove the following inequality?

Question: For real square matrices $A_0$ and $A_{1}$ with $A^{T}_0+A_0+A^{T}_{1}+A_1\leq{-\gamma{I}}$, where $\leq$ denotes the negative semi-definiteness of the left argument with respect to the right, $\gamma>0$ and $I$ is the identity matrix of suitable dimension.
Is it possible to show that
$x^T\Big(e^{A^{T}_{1}}*e^{A^{T}_{0}}*e^{A_{0}}*e^{A_{1}}\Big)x\leq\|x\|^2$ for a non-zero vector $x$? I know if $A_0$ and $A_1$ are normal matrices and $A_0, A_1$ are commutative to each other, the mentioned claim holds immediately. But for the case when these matrices are not normal and do not commute, does the claim hold?
My approach:
$x^T\Big(e^{A^{T}_{1}}*e^{A^{T}_{0}}*e^{A_{0}}*e^{A_{1}}\Big)x\leq\|x\|^2\|e^{A_0}*e^{A_1}\|^2\leq\|x\|^2\|e^{A_0}*e^{A_1}\|_F^2=\|x\|^2~\|e^{A_0}\|_F^2\|e^{A_1}\|_F^2=\|x\|^2\text{Tr}\left(e^{A^T_0}e^{A_0}\right)\text{Tr}\left(e^{A^T_1}e^{A_1}\right)\leq\|x\|^2\text{Tr}\left(e^{A^T_0+A_0}\right)\text{Tr}\left(e^{A^T_1+A_1}\right)$ by virtue of equation (1.3) of
 https://epubs.siam.org/doi/pdf/10.1137/0609012.
But I do not see a way forward. Any hints or suggestions are greatly appreciated.
Comment: Can't one just assume $\gamma=0$ by a continuity argument?
Comment: Yes. That's possible.
Answer: Let $A$ and $B$ be such that $A$ and $B$ are symmetric and $2A \leq -2B$ but $e^{2A} \leq e^{-2B}$ does not hold. For example, following this post one can set
$$A=\begin{pmatrix}0.5 & 0 \\ 0 & 1\end{pmatrix},~B=\begin{pmatrix}-1-\epsilon & -0.5 \\-0.5 & -1.5\end{pmatrix},$$
where $\epsilon>0$ is small enough. Also let $A_0=A_0^T=0.5A$ and $A_1=A_1^T=0.5 B$. Then we have $A_0+A_0^T+A_1+A_1^T=A+B\leq 0$. The desired inequality is equivalent to the claim that $\|e^{A_1^T}e^{A_0^T}e^{A_0}e^{A_1}\|_{op}\leq 1$. We prove this is false for our choice of $A_0$ and $A_1$. Since $A_0$ and $A_1$ are symmetric (hence normal):
$$\| e^{A_1^T}e^{A_0^T}e^{A_0}e^{A_1}\|_{op}=\|e^{A_0^T}e^{A_0}e^{A_1}e^{A_1^T}\|_{op}=\|e^{A}e^{B}\|_{op}.$$
So suppose on the contrary that $\|e^Ae^B \|_{op} \leq 1$, and so $\|e^Ae^Bx\|\leq \|x\|$ for all $x$. Therefore, $\|e^A(e^Bx)\|\leq \|e^{-B}(e^Bx)\|$ for all $x$. Since $e^B$ is invertible, it follows that $\|e^Ax \|\leq \|e^{-B}x\|$ for all $x$. Equivalently, $\langle e^{2A}x,x\rangle \leq \langle e^{-2B}x,x \rangle$ for all $x$ and so $\langle (e^{2A}-e^{-2B})x,x \rangle \leq 0$. But then $e^{2A}-e^{-2B}\leq 0$, which is a contradiction.
Comment: Thanks. But $2A\leq{-2B}$ does not imply $e^{2A}\leq{e^{-2B}}$ unless they are commutative to each other. Take a look at https://math.stackexchange.com/questions/2622620/is-it-possible-to-show-that-expa-expb-is-negative-definite-provided-a-b-is
Comment: @jbgujgu, this actually might be used to cook up a counterexample.


HostListener and Angular Universal

Question: I'm trying to listen to a MessageEvent sent with postMessage in my Angular 2 component.
My first attempt was simply doing:
window.addEventListener("message", this.handlePostMessage.bind(this));

And then in ngOnDestroy:
window.removeEventListener("message", this.handlePostMessage.bind(this));

However this didn't work as expected. If I navigated to another route and back, there would be two event listeners registered.
So instead I've been trying to decorate the method with HostListener, but I can't get this working when using prerendering (Angular Universal with .NET Core using the asp-prerender-module).
@HostListener('window:message', ['$event'])
private handlePostMessage(msg: MessageEvent) {
    ...
}

That gives me the following error on page load:
Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: MessageEvent is not defined

Is there a workaround for this?
Comment: Just updated my answer. See Edit #2 to see if it helps you!
Answer: You're getting this error because MessageEvent is not defined. You must import whatever file defines this.
My @HostListeners look like this:
@HostListener("window:savePDF", ["$event"]) savePDF(event) {
    this.savePDFButtonPushed();
}

and you can read more about them here:
https://angular.io/guide/attribute-directives
However, I'm currently experiencing the same issue you are -- that if I navigate to another route and back, I now receive two events. And that is using @HostListener. :-(  However I haven't upgraded Angular in a while (currently using 4.4.6), so maybe they've fixed it since that release.
**Edit: Just upgraded to Angular 5.1.0. The 'duplicate events' @HostListener issue remains. :-(
Edit #2: I tried also using window.addEventListener like you tried, and also had the same issue, despite using window.removeEventListener in ngOnDestroy().
This lead me to dig a little deeper, where I found some code I had added to listen to messages from a child iFrame. Any chance you have something similar in your code?
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

                // Listen to messages from child window ("unsign" and "savePDF") and pass those along as events to Angular can pick them up in its context
        eventer(messageEvent,function(e) {
            window.dispatchEvent( new Event( e.data ) );
        },false);

This had been in my page's constructor. I protected it so it only executed the first time the page was constructor, and now all is well.

HostListener and Angular Universal


Save Windows.UI.Composition.CompositionDrawingSurface to file

Question: I am creating object using following code:
<code>CompositionDrawingSurface uiElementBitmapSurface;
            using (var canvasBitmap = CanvasBitmap.CreateFromBytes(
                    canvasDevice, pixels,
                    bitmap.PixelWidth,
                    bitmap.PixelHeight,
                    DirectXPixelFormat.B8G8R8A8UIntNormalized,
                    dpi)
            )
            {
                var areaToRender = new Rect(100, 100, Control.ActualWidth, Control.ActualHeight);
                Windows.UI.Composition.CompositionDrawingSurface surface = compositionDevice.CreateDrawingSurface(
                                        new Size(areaToRender.Width, areaToRender.Height),
                                        DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);

                using (var session = CanvasComposition.CreateDrawingSession(uiElementBitmapSurface))
                {
                    session.DrawImage(canvasBitmap, 0, 0, areaToRender);
                }
            }
</code>
Please help to convert uiElementBitmapSurface object to file.
Comment: Could you please tell  what file format you want to save to?
Comment: @SunteenWu-MSFT want to save it to .png or .jpg
Answer: Call this:
https://microsoft.github.io/Win2D/html/M_Microsoft_Graphics_Canvas_CanvasBitmap_SaveAsync.htm
I have not tried this myself by the way, I just googled the documentation. But it sure looks like what you are looking for.
Comment: given link helps in saving canvasbitmap to file but my requirement is to save conpositionDrawingSurface to file


PHP download large file to server with size bigger than 1gb

Question: I am trying to download a video file directly on my server using the bellow php-curl script, but it stops downloading after getting around 120mb of file, the files are more than 500mb and some of them are 1gb and 1.5gb in size. I searched a lot but got nothing to resolve. I am running on a shared hosting.
if ($url) {
    $file_loc = 'moviez/' . $name;
    $fp = fopen($file_loc, 'w+');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 0);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}

Comment: you should check the `upload_max_filesize` setting in your `php.ini`, see [here](http://stackoverflow.com/questions/2184513/php-change-the-maximum-upload-file-size)
Comment: since m running on a shared hosting, i don't have permission to change this. I have also asked the administrator to increase the connection time but they denied and asked me to find any alternative idea.
Comment: download shall be upload, since you are putting it "on the server" :)
Comment: well i don't have access to php.ini, also in simple word my problem is that m trying to save a video file to my server from youtube.com which is more than 1gb in size. But after fetching  around 100mb's my script returns this error...."Request Timeout

This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'."
Answer: I suspect that maybe the script is timing out. The default is 30 seconds if I remember correctly. Your host may be limiting your script run time as well. You can use ini_set('max_execution_time', nnn) to increase the timeout.
Edit: Better yet, use set_time_limit(), which will throw an error:
Warning: set_time_limit(): Cannot set time limit in safe mode
if your host is limiting you.
Comment: i have already added set_time_limit(0), but no error regarding this.
Answer: As Luke said, your script is timing out before your download completes. The problem with setting max_execution_time is that only affects uploads.
Your solution should be handled by readfile() or file_get_contents(). Great source is found here: http://www.ibm.com/developerworks/library/os-php-readfiles/index.html?ca=drs
Edit: Minor confusion between Max_execution_time and max_input_time.
Edit Two: Example,
<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

Download the batman

Comment: but this will start download on browser side, instead i want to save the content on server.
Comment: Ohhh, I was confused by the word "download" in your question! You're looking to upload to your server.

You will be looking at max_input_time in your php.ini. Here: http://www.php.net/manual/en/info.configuration.php#ini.max-input-time
Comment: well i don't have access to php.ini, also in simple word my problem is that m trying to save a video file to my server from youtube.com which is more than 1gb in size. But after fetching around 100mb's my script returns this error...."Request Timeout This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'."
Comment: That now sounds like an max_execution_time problem because the script would be continuously retrieving the file. Without access to the php.ini file, I am not entirely certain how to proceed. Sorry, bud.
Answer: Check this script. It worked well for me to download file larger than 500mb.
Light Weight PHP Script To Download Remote File To Local Server

<?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'files/';
$url = $_POST['url'];
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
  $newf = fopen ($newfname, "wb");
if ($newf)
  while(!feof($file)) {
    fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
  }
}
if ($file) {
  fclose($file);
}
if ($newf) {
  fclose($newf);
}
?>


Busca em tabela relacionada

Question: Tenho um script de busca que varre até três campos de uma tabela chamada produtos, agora preciso fazer uma pesquisa em uma tabela chamada marca, a tabela produto tem o id_marca que se relaciona com a tabela marca, mas não estou conseguindo implementar.
A pesquisa está assim:
$pesquisa = $_REQUEST['s'];
$pesquisa = (strtolower($pesquisa));

// Agrupando campos no concat.
$campo = 'CONCAT(descricao, " ", resumo, " ", detalhes, " ", codigo_msb)';
// dividindo as palavras pelo espaço
$palavras = explode( " ", $pesquisa );
// eliminando ítens vazios
$palavras = array_filter($palavras);

// Inicializando a variável
$where = '';
$cola = 'WHERE ';

foreach ($palavras as $palavra) {
  // Removendo espaços em branco
  $palavra = trim($palavra);
  $palavra = mysql_real_escape_string($palavra, $conexao);
  $where .= $cola.$campo.' LIKE "%'.$palavra.'%" ';
  $cola = 'AND ';
}

mysql_select_db($database_conexao, $conexao);
$query_rsBusca = "SELECT
                      produtos.id_marca,
                      marca.descricao AS marca
                    FROM
                      produtos
                      INNER JOIN marca ON (produtos.id_marca = marca.id_marca) ".$where." ";
$rsBusca = mysql_query($query_rsBusca, $conexao) or die(mysql_error());
$row_rsBusca = mysql_fetch_assoc($rsBusca);
$totalRows_rsBusca = mysql_num_rows($rsBusca);

A tabela produtos tem o id_marca que se relaciona com a tabela marca e preciso fazer uma busca pelo nome da marca.
O erro que está ocorrendo é esse:
Column 'descricao' in where clause is ambiguous

Comment: A dúvida é sobre alguma lógica do PHP ou sobre o comando SQL? Se é sobre SQL, você pode deixar a pergunta mais clara mostrando apenas o código SQL. Além disso, escreva o que você já tentou até agora e os problemas encontrados.
Comment: Olá @Caffe, sim, minha dúvida é sobre SQL, estou fazendo um um Join mas o mesmo está falhando.
Comment: Onde está o JOIN então? Não aparece no código que você postou. E o que quer dizer com "está falhando"? Dá algum erro?
Comment: Acabei de atualizar a pergunta com o Join, mas como uso o concat para fazer a busca nos campos da tabela produtos sem referência a tabela marca o erro ocorre.
Answer: O erro está lá no começo do seu código (a explicação é o que o Fernando disse, tem mais de uma coluna com o mesmo nome envolvida na query):
$campo = 'CONCAT(descricao, " ", resumo, " ", detalhes, " ", codigo_msb)';

A solução depende de qual descrição você quer usar no WHERE. Supondo que seja a do produto:
$campo = 'CONCAT(produtos.descricao, " ", resumo, " ", detalhes, " ", codigo_msb)';

Sobre seu último comentário, isto:
WHERE produtos CONCAT(...

deveria ser:
WHERE CONCAT(...

Comment: Olá @bfavaretto, não consigo entender, sempre que altero a referência, ou seja o alias continuo com o erro, veja a mensagem:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONCAT(produtos.descricao, " ", resumo, " ", detalhes, " ", codigo_msb) LIKE "%s' at line 6
Comment: O echo está assim: SELECT p.id_marca, m.descricao AS marca FROM produtos as p INNER JOIN marca as m ON (p.id_marca = m.id_marca) WHERE produtos CONCAT(produtos.descricao, " ", resumo, " ", detalhes, " ", codigo_msb) LIKE "%sofa%"
Comment: @adventistapr Editei a resposta.
Answer: O erro que você postou já está dizendo explicitamente qual é o erro. É o seguinte a tabela produtos também deve conter uma coluna chamada descricao, certo? Então como você não está utilizando alias em sua consulta, está ocorrendo esse erro: Column 'descricao' in where clause is ambiguous, como você postou na pergunta. Pois o banco de dados não sabe de qual tabela você quer utiliza a coluna descricao, já que ela está nas duas tabelas.
Então o que você deve fazer é o seguinte:

Colocar alias na consulta em suas tabelas;
Utilizar os alias para indicar de qual tabela você deseja a coluna explicitamente;

Segue o código modificado:
// modifique seu `where` que é o que está causando o problema
// coloquei como alias "p ou m", pois não sei de qual tabela você quer
$where .= $cola.'p ou m'.$campo.' LIKE "%'.$palavra.'%" ';

// adicione o alias a sua consulta
$query_rsBusca = "SELECT
                      p.id_marca,
                      m.descricao AS marca
                    FROM
                      produtos as p
                      INNER JOIN marca as m ON (p.id_marca = m.id_marca) ".$where." ";

Ou como percebi que ao invés de alias você estava utilizando o nome da tabela que funciona similar ao alias. Você simplesmente pode no where adicionar o nome da tabela para especificar de qual é a coluna do where:
// coloquei como alias "produto ou marca", pois não sei de qual tabela você quer
$where .= $cola.'produto ou marca'.$campo.' LIKE "%'.$palavra.'%" ';

Eu para evitar esse tipo de problema, já me acostumei por default a sempre utilizar alias, em minhas consultas para todos os campos mesmo que não sejam ambíguos.

Sua segunda duvida(nos comentários), é como @bfavaretto, citou:
WHERE produtos CONCAT(...

deveria ser:
WHERE CONCAT(...

Código (segunda duvida) retirado da resposta do @bfavaretto
Criei um exemplo iterativo da solução completa, aqui.
Comment: Olá @Fernando, muito obrigado por ter respondido, fiz as alterações conforme seu modelo, agora estou recebendo uma mensagem, veja:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONCAT(descricao, " ", resumo, " ", detalhes) LIKE "%anc%"' at line 6
Comment: @adventistapr, agora parece ser um erro de SQL, de um echo em `$query_rsBusca` antes de executar a `query`, e poste o SQL completo que está sendo executado, para pode tentar lhe ajudar.
Comment: Olha o echo:SELECT p.id_marca, m.descricao AS marca FROM produtos as p INNER JOIN marca as m ON (p.id_marca = m.id_marca) WHERE produtos CONCAT(descricao, " ", resumo, " ", detalhes) LIKE "%anc%" You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONCAT(descricao, " ", resumo, " ", detalhes) LIKE "%anc%"' at line 6
Comment: Essa sua segundo duvida é conforme o @bfavaretto, citou, você deve remover o "produtos " antes do CONCAT. Fiz um [exemplo online de seu problema](http://sqlfiddle.com/#!2/b0a684/1) para ajudar a entender sua estrutura, de uma olhada no seu SQL corrigido.
Comment: @adventistapr, editei a resposta, complementando com as informações referentes a essa sua segunda duvida.

Busca em tabela relacionada


How would you frame this as a machine learning problem?

Question: I have a trading software that buys and sells loans. There's an auction site where borrowers ask for some money and lenders bid on them until the borrower is fully funded and the auction ends. There's lots of information on each loan request. My trading bot always bids at the highest possible interest rate, if it is outbid, then it just re-bids slightly lower. Once I win the loan parts, I can sell them at a markup. Right now, I sell at the minimum markup, so that with fees I barely make a profit.
What I'm not sure is what markup I should sell? The lower the markup the faster my loan parts sell, but I will get less profit too. On what loans should I bid? Should I bid on a loan auction with a higher interest rate, but which is not going to end for several days, thereby leaving my money stale, or should I bid on an auction with a lower interest rate, but which is going to end very soon. Sometimes in the former case, the borrower might decide to take the loan and not wait until the end of the auction, thereby I could secure a better interest rate than just bidding on the loan auction due to end soon.
I was thinking of framing this problem as reinforcement learning, but I'm not sure how to do it. My goal is to maximiz the profit I make from trading loans. Any ideas?
Comment: This looks like a very exciting problem to solve. but, i think there are too many problems you can solve.
so, the first step is to fix on one or two key problems. and, then determine the factors which will be essential to solve that problem. i don't think we should talk about any model till then.
Answer: As the user above points out, this is not simply an issue of choosing a machine learning method and letting it go wild on the data. Particularly, the introduction of decision theory (even in a basic form) is vital. While the inclusion of something like "decision theory" might seem a bit complex, this really only means in your case that you are not simply estimating a quantity and figuring out if you are right; that is, not every wrong solution is "equally wrong", in the sense that you'll need to take into account your profit and your funds left in reserve.
A general approach is difficult to recommend without intimate knowledge of the data. However, it sounds like you'll need to formalize the aspects of your model. Think about the following questions as you decide on your model:

What is the quantity I am trying to predict? (In this case, it sounds like you are looking for the particular markup at which you should sell, and/or the price at which to buy so that a profit can be made, which is just as much optimization as it is machine learning).
What examples can I use to train my model, and what are my inputs? What market factors can I train my model with to predict the quantities in (1)?

As a final point, it is really quite unlikely that reinforcement learning is the approach you'll want to take in this case. Reinforcement learning is quite powerful in certain situations, but is somewhat unpredictable (depending on the particular formulation), and tends to make an awful lot of errors before it gets anything right (something that likely is not an option when there is money on the line). As I said, try to figure out which quantities you want to estimate, then figure out what market factors might affect those quantities.
Answer: Your problem would seem to be much more than a Machine Learning exercise which is primarily concerned with building a model (supervised or unsupervised) for your data.  The issues you are exploring would appear to need Game Theory, and Decision Theory.
Comment: That's true, I'm still at the problem definition stage. You have any ideas? I was thinking of Markov Decision Process, but I mostly have background in regression, so not sure.


Integrating in spherical polar coordinates

Question: Given a function  $f(r,\theta,\phi)$ expressed in polar coordinates, would its integral over a sphere of radius $R$ centered at the origin be:
$$\int_0^{2\pi}\int_0^{\pi}\int_0^R f(r,\theta,\phi)\,\color{red}{r^2\sin\theta}\;\mathrm{d}r\,\mathrm{d}\theta\,\mathrm{d}\phi\,?$$
I am not sure whether the volume element should be incorporated given that $f$ is already in polar coordinates.
Comment: No, your formula would be wrong. The factor $r^2\sin\theta$ comes from transforming the volume element $dV$, not the scalar field $f$.
Answer: If you integrate on the ball of radius $R$ the term $r^2\sin\theta$ has to appear: assume $f=1$ (you can consider it as a function expressed in polar coordinate), then integrating the constant function $1$ on the sphere you expect to obtain the volume of the sphere, and this happen only if you have $r^2\sin\theta$. If you are integrating on a volume you need a volume element: in cartesian coordinate it is $dx\ dy\ dz$, in spherical coordinate it is $r^2\sin\theta\ dr\ d\theta\ d\phi$.
If you integrate on the sphere of radius $R$ you need an area element, i.e. $R^2\sin\theta \ d\theta\ d\phi$ and your integral becomes:
$$\int_0^{2\pi}\int_0^{\pi} f(R,\theta,\phi)\ R^2\sin\theta d\theta\ d\phi\ .$$


Let $A$ be a square matrix such that $A^T$ is a positive transition matrix. Show that $\lambda = -1$ fails to be an eigenvalue of $A$.

Question: Question states:
Consider a square matrix $A$ such that all entries are positive and the sum of the entries in each row is $1$, i.e. $A^T$ is a positive transition matrix. Show that $\lambda = -1$ fails to be an eigenvalue of $A$.
I am not sure how to prove this. I know that all eigenvalues of $A$ has their absolute values less than or equal to 1, and that 1 is an eigenvalue.
Answer: Perron-Frobenius would imply all eigenvalues (except $\lambda=1$) have absolute value strictly less than $1$.
Comment: Without invoking such theorem, could you answer my question in simplest terms and with enough mathematical rigor?
Answer: Let $S$ be the set of $n\,{\times}\,n$ matrices with positive real entries such that the sum of the entries in each row is $1$.

Suppose $A \in S$ has $\lambda = -1$ as an eigenvalue.

Out goal is to derive a contradiction.

Let $x = (x_1,...,x_n)$ be a nonzero real $n$-vector such that $Ax = -x$.

Let $m = \text{min}(x_1,...,x_n)$, and let $M = \text{max}(x_1,...,x_n)$.

If $m = M$, then $x_1 = \cdots = x_n$, but then from $A\in S$, we would get $Ax = x$, contrary to the assumption that $Ax = -x$.

Thus, we must have $m < M$.

Let $A^2x = y = (y_1,...,y_n)$. Then
$$y = A^2x = A(Ax) = A(-x) = -Ax = -(-x) = x$$
But $A \in S$ implies $A^2 \in S$, hence $A^2x = y$ implies that each of $y_1,...,y_n$ is a strict convex combination of $x_1,...,x_n$. It follows that $m < y_1,...,y_n < M$, contrary to $y=x$.
Comment: Thanks. What is a strict convex combination?
Comment: By "strict convex combination", I mean a convex combination with all positive weights. A strict convex combination of $n$ real numbers $x_1,...,x_n$ must yield a number which is strictly between $\text{min}(x_1,...,x_n)$ and $\text{max}(x_1,...,x_n)$, unless $x_1 = \cdots = x_n$.


prove tan(a+b) identity

Question: How do I prove the addition formula for $\tan(a+b)$?
I have $$\displaystyle \frac{\sin(a+b)}{\cos(a+b)}=\frac{\sin(a)\cos(b)+\cos(a)\sin(b)}{\cos(a)\cos(b)-\sin(a)\sin(b)}$$ but that's way more complicated than the result I need, which is $$\displaystyle \frac{\tan(a)+\tan(b)}{1-\tan(a)\tan(b)}$$
Am I on the right track? What should I do next?
Answer: You are almost there. Notice that you have two terms on the top and bottom, and so does the answer. Is there something you could divide by to achieve this result? Hint, look at the bottom left term!
Comment: damn. it was right there the whole time! if i divide by cos(a)cos(b), then it turns into 1, and the sin(a)sin(b) turns into tan(a)tan(b)

prove tan(a+b) identity


SmartArray P400 Create Logical Drive Erase Data?

Question: Does create logical drive on a Smart Array P400 erase existing data?
I have a disk that was from a RAID1 set on a IBM server. It's currently plugged in a HP server in order for me to read the data. Since P400 does not have JBOD feature, I am wondering if I just need to create a logical drive (e.g. RAID0) in order for the OS to recognize it.
Thank you!
Answer: This will not work.
What are you expecting this to do? The IBM controller and the HP Smart Array controller have different on-disk RAID formats. As there is no passthrough or JBOD mode available on the HP controller, creating any logical drive, even a RAID0, will delete the existing data on the drive.


RStudio keeps bugging me with the "cacheKey" error

Question: Even before updating RStudio to its lattest version, I am constant (like every 5 minutes) getting this error message
<code>"Error in exists(cacheKey, where = .rs.WorkingDataEnv, inherits = FALSE) :
  invalid first argument
Error in assign(cacheKey, frame, .rs.CachedDataEnv) :
  attempt to use zero-length variable name"
</code>
The only thing that seems to work is quitting RStudio and opening again.
That is very annoying becase I lose all my previous stuff that I need to continue my analyses.
Does anyone know how to get this fixed?
Answer: Apparently this is fixed in RStudio versions 2023.06.1-524 and later.
Refer https://github.com/rstudio/rstudio/issues/13188.


Pitchers with postseason home run

Question: Can you please list all pitchers who have hit a home run in the history of MLB playoffs?
Bonus: Include position players who started a postseason game as the pitcher and hit a homerun
Comment: This is a pretty broad trivia piece. Consider that you have over 100 years of history to pull from. I don't think there is a reasonable limiter here.
Comment: Another close vote came in after I answered.  Based on [this](http://meta.stackexchange.com/a/223458), "it's a safe bet that the question is not too broad".
Answer: The Baseball-Reference.com Batting Game Finder has data going back to 1903.  To get the list of pitchers who have hit home runs in the postseason, make the following setting changes on that page:

select "Find Players with Most Matching Games in Multiple Years"

select "Postseason"

for "Batter's Defensive Position", make sure only "P" is checked (this will include any position player who hit a home run in a game that he made an appearance as a pitcher)

under "Select Additional Criteria Games Must Match", add a criteria for "HR >= 1"

After you click on "Get Report", you will find 19 pitchers who have hit postseason home runs.  But it only shows 10 of those names, since you have to subscribe to see the entire list.  Just go back to the search form, click the "Use ascending order" box, and click "Get Report" again to see the rest of the names.
The 19 pitchers are:

Dave McNally (hit 2 postseason home runs)
Bob Gibson (hit 2 postseason home runs)
Kerry Wood
Bucky Walters
Rick Sutcliffe
Jeff Suppan
Jose Santiago
Rosy Ryan
Mickey Lolich
Ken Holtzman
Jesse Haines
Don Gullett
Mudcat Grant
Mike Cuellar
Steve Carlton
Lew Burdette
Joe Blanton
Jack Bentley
Jim Bagby

Edit: Since the original answer, 3 more pitchers have had postseason homeruns:

Travis Wood
Jake Arrieta
Brandon Woodruff
Comment: Added the edit section for the missing 3 pitchers since you posted your answer. I was able to see them on baseball-reference.com as well, but had to change year span to look from 1969 to 2019 and look for the results on both ascending and descending order. Didn't add those 3 guys to your list as you can't see all of them by the procedure you mentioned to find since there is more than 20 players to achieve the feat now. Using the Wikipedia link I added as my reference (which has been created after you posted your answer) works much easier now.

Pitchers with postseason home run


Como registrar dll .net usando Inno Setup

Question: Tenho uma DLL escrita em C# e não consigo registra-la utilizando o Inno Setup.
Um exemplo de como executar esse processo seria útil.
Comment: Pode postar como você tentou até o momento?
Answer: Utilize a seguinte sintaxe em seu script do Inno Setup:
[Run]
Filename: "{dotnet20}\Regasm.exe"; Parameters: "{nome da dll} /codebase"; WorkingDir: "{app}"; Flags: runhidden; StatusMsg: "Registrando DLL"

No lugar do código {dotnet20}, pode ser alterado para a versão do NET Framework em questão, por exemplo: {dotnet30}, {dotnet40}, {dotnet4.5}.
O parâmetro "WorkingDir" refere-se ao local onde está a respectiva dll.
Obviamente o NET Framework precisará estar instalado. Então este comando deve ser executado somente após a instalação do mesmo.
Answer: Um assembly (.dll) do .net precisa ser registrado de forma diferente das demais .dll's. O Inno Setup não saberá distinguir isso quando você marcar a .dll como regserver.
Neste caso, tente colocar no final do seu script (após a descompactação da instalação):
[Run]
Filename: "c:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe"; Parameters: "/codebase [CaminhoParaSuaDllAqui]"

(Baseado nesta resposta do SO Inglês)


Intuition for "identification" and "generalization" (computability theory)

Question: I am trying to decipher page 68 of Hermes' book on computability theory.  One paragraph I am having trouble with is

Let $Q$ be an n-ary predicate ($n \geq 2$).  Let $1 \leq i < k \leq n$.  Then $P$ [a predicate] is called the $(i, k)$ identification of $Q$, if $P$ is $(n-1)$-ary and if for all $x_1, \dots, x_{k-1}, x_{k+1}, \dots, x_n$, $$P x_1 \dots x_{k-1} x_{k+1} \dots x_n \iff Q x_1 \dots x_{k-1} x_i x_{k+1} \dots x_n.$$

What does "identification" mean intuitively and what does it correspond to in more concrete terms?
There's also another paragraph I don't understand,

Let $Q$ be an n-ary predicate.  Let $1 \leq i \leq n$.  The (n-1)-ary predicate $P$ is called the ith generalization of $Q$, if for all $x_1 \dots x_{i-1}, x_{i+1}, \dots, x_n$, $$P x_1 \dots x_{i-1} x_{i+1} \dots x_n \iff \wedge_{x_i} Q x_1 \dots x_n.$$

On the right hand side, what is different between different terms of the conjunction?  Isn't $Q x_1 \dots x_n$ the same no matter what the value of $x_i$ is?  Also, what does "generalization" mean in intuitive terms?
Thanks :)
Answer: For the first, here are three simple cases. Suppose we define
$$P(x) \Leftrightarrow Q(x, x)$$
or
$$P'(x,y,z) \Leftrightarrow Q'(x,y,z,y)$$
or
$$P''(x,y,z,w) \Leftrightarrow Q''(x,y,z,x,w)$$
So in each case we get an $n-1$-place predicate from an $n$-place predicate by filling two slots in the $n$ place predicate in the same way. Hermes is just giving a general description of this operation.
For the second, that isn't a conjunction in Hermes but a universal quantification. In more familiar notation, examples would be where we define
$$P(x) \Leftrightarrow \forall yQ(x, y)$$
or
$$P(x, y) \Leftrightarrow \forall zQ(z, x, y)$$
getting an $n-1$-place predicate by quantificationally binding one place in an $n$-predicate.
[It is nice to see a mention of Hermes's old book: it taught me a lot when I read it as a student when the English translation was newly published -- so I could reach for it still on my shelves!]
Comment: Hey, thanks for your help!


The splitting field of $(x^3 + x^2 +1)(x^3 + x +1)(x^2 + x +1)$ over $F_2$

Question: Let f(x) = $(x^3 + x^2 +1)(x^3 + x +1)(x^2 + x +1)$ over $F_2$. I know that the factors of f are irreducible over $F_2$ since they have no root in $F_2$. How can I compute the splitting fields?
Comment: You may want to say " I know that the factors of f are irreducible over $F_2$ since they have no root in $F_2$ ***and they have degree $2$ or $3$***".
Answer: The splitting field of an irreducible polynomial of degree $n$ over $F_{p}$ is the field $F_{p^n}$ with $p^n$ elements.
So the splitting field must contain $F_{2^2}$ and $F_{2^{3}}$. Then it is $F_{2^6}$, as $F_{p^h} \subseteq F_{p^k}$ iff $h \mid k$.
Answer: I'm piggybacking off of the Andreas' response. Let $\alpha$ be a root of $x^3+x^2+1$. Since the polynomial is irreducible, we know that $[F(\alpha):F]=3$. Since $F(\alpha)$ is a vector space over $F$ with dimension $3$, we have that $F(\alpha)$ has $2^3$ elements. Now let's show that this field actually has roots for the other two polynomials. We use the fact that $1+1=0$ in $F$.
\begin{align*}
(\alpha+1)^3+(\alpha+1)+1&=\alpha^3+3\alpha^2+3\alpha+1+\alpha+1+1\\
&=\alpha^3+\alpha^2+1\\
&=0
\end{align*}
You will find that the six new elements of $F(\alpha)$ are roots of the first two polynomials. To show that all the roots of the cubics are in $F(\alpha)$, it's probably easier to note that $(x^3+x^2+1)(x^3+x+1)(x+1)x=x^8-x$! In other words, your cubics do actually split in $F(\alpha)$
You still have no roots of the quadratic; it remains irreducible in $F(\alpha)$. The splitting field of your eighth degree polynomial is $F(\alpha,\beta)$, where $\beta$ is a root of $x^2+x+1$. The degree is $[F(\alpha,\beta):F]=6$.
Answer: It is the same as the splitting field of  $(x^3+x+1)(x^2+x+1)$.
Indeed if $\omega$ satisfies the equation $x^3+x+1=0$, then $\omega^2+1$ satisfies the equation $x^3+x^2+1=0$ since
\begin{align}(1+\omega^2)^3+(1+\omega^2)^2+1&=(1+\omega^2+\omega^4+\omega^6)+(1+\omega^4)+1\\
&=1+\omega^2+\omega^6=1+\omega^2+(1+\omega)^2=0
\end{align}
Thus the splitting field is the compositum of the splitting fields of $x^2+x+1$ and of $x^3+x+1$.
Answer: Let be $\alpha$ root of polynomial $f(x)=x^3+x+1$ then $\mathbb Z_2[x]/(f(x)) \cong \mathbb Z_2(\alpha) $ then $\{ 1,\alpha,\alpha^2\} $ basis of  $\mathbb Z_2(\alpha)$ over $\mathbb Z_2$, Where $$\mathbb Z_2(\alpha)=\{ 0,1,\alpha,\alpha^2,1+\alpha,1+\alpha^2, \alpha+\alpha^2, 1+ \alpha+\alpha^2 \} $$
and $f(x)=(x-\alpha)(x^2+\alpha x+1+\alpha^2 )$ where $\alpha^2, \alpha+\alpha^2 \in \mathbb Z_2(\alpha)$ are roots of $x^2+\alpha x+1+\alpha^2 $ then $\mathbb Z_2(\alpha)$ is splitting field of  $x^3+x+1$ over $\mathbb Z_2$.
We note that $1+\alpha,1+\alpha^2,1+\alpha+\alpha^2 $ are roots the polynomial $x^3+x^2+1$, then $\mathbb Z_2(\alpha)$ is splitting field of  $x^3+x^2+1$ over $\mathbb Z_2$.
we note that $\mathbb Z_2(\alpha)$ doesnot have root of polunomial $x^2+x+1$ then let be $\beta$ root of polynomial $g(x)=x^2+x+1$ then $\mathbb Z_2[x]/(g(x)) \cong \mathbb Z_2(\beta) $ then $\{ 1,\beta \} $ basis of  $\mathbb Z_2(\beta)$ over $\mathbb Z_2$, Where $$\mathbb Z_2(\beta)=\{ 0,1,\beta,1+\beta \} $$
and $g(x)=(x-\beta)(x+\beta+1)$ where $\beta+1\in\mathbb Z_2(\beta)$ root of $(x+\beta+1) $ then $\mathbb Z_2(\beta)$ is splitting field of  $x^2+x+1$ over $\mathbb Z_2$.
Finally  the splitting field of $(x^3+x^2+1)(x^3+x+1)(x^2+x+1)$ over $\mathbb Z_2$ is $\mathbb Z_2(\alpha,\beta)$.


Reviving activity state in Android

Question: I want to write an android app which logs all the photos taken by making an entry into a text file with the photos uri, time-stamp and geo location stamp. This Should happen as and when a photo is clicked.
For this I'm running a Service which uses a FileObserver on the default photos directory. (I know this is not fool proof).
The user is initially greeted by a GUI which will let him select a file name and a start button to start recording. When the user presses start recording, the background Service is started and the user goes back to take some photos,1 when he comes back he should have an option to stop recording which ends the background service.
Now my problem is this,
1. how does the activity know when the service is running and when it is not?
2. How does the previous state of the Activity get revived and reconnect to the particular service? As in how does the association of the Activity to Service happen when i revive the Activity? (consedring some kind of association is necessary if my Activity has to stop the Service)
Here is my code for reference : [ExperienceLoggerService is an inner class of MainActivity]
public class ExperienceLoggerService extends Service
/* This is an inner class of our main activity, as an inner class makes good use of resources of outer class */
{

    private final IBinder mBinder = new LocalBinder();
    File file;
    FileOutputStream fOut;
    OutputStreamWriter fWrite;
    /** Called when the activity is first created. */
    private void startLoggerService()
    {
        try
        {
            //initialise the file in which to log
            this.file = new File(Environment.getExternalStorageDirectory(), "MyAPPNostalgia");
            System.out.println("1:"+Environment.getExternalStorageDirectory()+ "MyAPPNostalgia");
            file.createNewFile();
            fOut = new FileOutputStream(file);
            fWrite = new OutputStreamWriter(fOut);
        }
        catch(Exception e)
        {
            System.out.println("Error in logging data, blame navjot");
        }
        FileObserver observer = new MyFileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/100MEDIA");
        observer.startWatching(); // start the observer
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        //mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        startLoggerService();

        // Display a notification about us starting. We put an icon in the
        // status bar.
        //showNotification();
    }

    public void onDestroy()
    {
        try
        {
            //close the file, file o/p stream and out writer.
            fWrite.close();
            fOut.close();
        }

        catch(Exception e)
        {
        }

        super.onDestroy();

    }

    class MyFileObserver extends FileObserver
    {
        public MyFileObserver(String path)
        {
            super(path);
        }

        public void onEvent(int event, String file)
        {
            if(event == FileObserver.CREATE && !file.equals(".probe"))
            { // check if its a "create" and not equal to .probe because thats created every time camera is launched
                String fileSaved = "New photo Saved: " + file +"\n";
                try
                {
                    ExperienceLoggerService.this.fWrite.append(fileSaved);
                }
                catch(Exception e)
                {
                    System.out.println("Problem in writing to file");
                }
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return mBinder;
    }

    public class LocalBinder extends Binder
    {
        ExperienceLoggerService getService()
        {
            return ExperienceLoggerService.this;
        }
    }

}

Answer: You don't need a "connection" to the service to stop it from an activity. You can just do:
Intent intent = new Intent(this, ExperienceLoggerService.class);
stopService(intent);

I'm not sure you really need to know if your service is running or not. If you really need to do this, you can do it using ActivityManager.getRunningServices(), see http://developer.android.com/reference/android/app/ActivityManager.html#getRunningServices%28int%29
EDIT: Note regarding bound services
You didn't post the code where your activity binds to the service, but after looking at your source code again, I see that you are using a bound service. In that case, your activity can just call unbindService() passing it the same ServiceConnection object that you used when calling bindService(). Once the service has no bound clients, it will shut itself down.
Comment: But my service is already running (which i would have started earlier), when i come back to my app. what i don't get is how will creating a new intent this way and calling stopService on it stop my earlier service?
Comment: That's how you stop services. By calling `stopService()` and passing an `Intent` that describes the service you want to stop.
Comment: Sorry, I didn't realize you were using **bound services**. I've updated my answer to reflect that. There are different ways to use services and `startService()/stopService()` is one of them. You can also use `bindService()/unbindService()`.

Reviving activity state in Android


How do I get an APP ID for Facebook on my web site?

Question: First of all, my simple purpose is to add a Facebook login button to my web site.  So I go to the login button description.
I must be thick headed, but I cannot get an APP ID.  Under the "Authentication" writeup it says, "The JavaScript SDK requires that you register your website with Facebook to get an App ID (or appId)."  Clicking on "Register Your Website" takes me to the APPS page. And since the login button is indicated under "Websites", I click that and it just takes me to another page that says I must register my website.  I am ready to pull out what hair I have left.
What am I missing?  Do I have to create a "new" app?  I can't call it login since apparently that already exists.
Answer: You need to create an app here:
http://developers.facebook.com/
Click on Apps -> Create New App
Give the app a name etc the you will need to add your websites URL into the Website section.
Comment: What if I don't have a website of my own, can I just give a random website ?


Pass a Parameter to an onClick Function

Question: I created a React single page application with the API from the NASA Picture of the Day and I added in a drawer a list with the history of the images displayed and it's is showing only its dates.
I have a Material-UI list item and I want to pass to its onClick function a parameter. I want that when I click on a specific date on the drawer to show me the image from that specific date.
Here I want to pass the parameter index:
pushDate = () => {
    menu.dates.push(this.state.image.date);
    index = menu.dates.indexOf(this.state.image.date);
    menu.menuItems.push(
        <List>
            <ListItem onClick={this.handleClose} primaryText={this.state.image.date} leftIcon={<ImagePhoto />} />
        </List>
    );
}

And here is the handleClose function :
handleClose = (date) => {
    this.setState({
        open: false,
        controlledDate: moment(menu.dates[index]),
    });
    this.getImage(moment(menu.dates[index]));
}

Answer: It should be onClick={() => this.handleClose(this.state.image.date)}

Pass a Parameter to an onClick Function


Custom View Async Task

Question: ublic class SectionsList extends LinearLayout implements OnOffChangeListener,OnClickListener,MessageListener{

private Context mContext;
private Dialog dialog;
private List<TextView> tList = new ArrayList<TextView>();
private List<EditValueButton> editList = new ArrayList<EditValueButton>();
private List<OnOffButton> onOffList = new ArrayList<OnOffButton>();
private List<String> sectionNames = NewsReader.getInstance().getSectionNamesListWithFunStories();
private final int ChangeBannerDeliveryBetweenTimeDialog_ID = 1;
private final int ChangeBannerDeliveryBetweenDateTimeDialog_ID = 2;
private Handler mHandler;
private EditValueButton editButton;
private long startTime;
private View setView;
private OnOffButton Id;
private Boolean sectionOn = false;
private Boolean setOff;
private Boolean checkSection = false;
private String activeSection;
private OnOffButton onOff;
private boolean cancel;
private TextView sectionName;
private TableLayout table;
private Resources resources;
private int textNormalColor;
private HashMap<String, Time> getSectiontime;
private HashMap<String, Time> hm = new HashMap<String, Time>();

@Override
public boolean handleMessage(Message msg) {
    boolean ret;
    Bundle  bundle = msg.getData();
    switch ( msg.what)
    {
    case Constants.message_SetBannerTime:
        startTime = bundle.getLong(Constants.KEY_ARG_1);
        setDisplayDuringLabel(startTime, setView);
        ret = true;
        break;
    case Constants.message_setOff:
        cancel = bundle.getBoolean(Constants.KEY_ARG_1);
        if(cancel){
        setOff();
        ret = true;
        break;
    }
    default:
    {
        ret = false;
        break;
    }
}
    return ret;
}

public SectionsList(Context context) {
    super(context);
    mContext = context;
    init(context, null);
}

public SectionsList(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    init(context, attrs);
}

private void init(Context context,  AttributeSet attrs) {

    //new CustomTask().execute();

    Log.d("secnames", "section names" + sectionNames);
    getSectiontime = PersistedScheduledBannerStore.getInstance().getScheduledBanners();
    resources = context.getResources();
    textNormalColor = resources.getColor(R.color.app_button_normal_text_color);
    if(getSectiontime != null){hm = getSectiontime;}
    LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    layoutInflater.inflate(R.layout.sectiontable, this, true);
    table = (TableLayout) findViewById(R.id.mainTable);
    for(int i =0; i< sectionNames.size();i++){
                TableRow tr = new TableRow(context);
                View line = new View(context);
                line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
                line.setBackgroundColor(textNormalColor);
                line.setPadding(0, 10, 0, 10);

                layoutInflater.inflate(R.layout.sectiontablerow, tr);
                table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
                table.addView(line);

                setIds(tr);
                setTagstoViews(i);
                addViewstoList();
                setListeners();
                checkIfSectionIsOn(i);
                tList.get(i).setText("sai ram");
            }

}

private void loopThroughViews(Context context, LayoutInflater layoutInflater) {

}

private void checkIfSectionIsOn(int i) {
    if(getSectiontime.containsKey(sectionNames.get(i))){
        String key = sectionNames.get(i);
        Time value = getSectiontime.get(key);
        editList.get(i).setText(DateFormat.format("h:mm a", value).toString());
        onOff.setOn(true);
    }else{
        editList.get(i).setText("-:-");
    }
}

public void onOffChanged(OnOffButton button, boolean isOn) {
    setView = button;

    if(isOn){
        sectionOn = true;
    }
    else if (!isOn){
        sectionOn = false;
        makeSectionActive(button);
        hm.remove(activeSection);
        getSectiontime.remove(activeSection);
    }
}

 protected Dialog onCreateDialog(int id) {
        switch (id) {
        case ChangeBannerDeliveryBetweenTimeDialog_ID:
        {
            long            curStartTime = 0;
            dialog = new ChangeBannerTimeDialog(getContext(), curStartTime, mHandler,0);
            break;
        }
        case ChangeBannerDeliveryBetweenDateTimeDialog_ID:
        {
            long            curStartTime = 0;
            dialog = new ChangeBannerdateTimeDialog(getContext(), curStartTime, mHandler, 0);
            break;
        }
        default:
            dialog = null;
    }
    return dialog;
}

private void setDisplayDuringLabel(long startTime, View v){
    changeTimeText(v, DateFormat.format("h:mm a", startTime).toString());
    Time time = new Time(startTime);
    if(sectionOn){
        hm.put(activeSection, time);
    }

}

@Override
public void onClick(View v) {
    setView = v;
    if(v.getId() == R.id.sectionOnOff){
        if(sectionOn){
            TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
            String secName = tt.getText().toString();
            showDateTimeDialogIfHoroscopes(secName);
            setOff = true;
            Id = onOffList.get(Integer.parseInt(v.getTag().toString()));
            Id.setOn(true);
            makeSectionActive(v);
        }
    }
    else if(v.getId() == R.id.editTime){
        setView = v;
        Id = onOffList.get(Integer.parseInt(v.getTag().toString()));
        if(Id.isOn()){
        TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
        String secName = tt.getText().toString();
        showDateTimeDialogIfHoroscopes(secName);
        setOff = false;
        Id.setOn(true);
        makeSectionActive(v);
        }
    }
}

private void showDateTimeDialogIfHoroscopes(String secName) {
    if(secName.equals("Horoscopes")){
        onCreateDialog(ChangeBannerDeliveryBetweenDateTimeDialog_ID).show();
    }else{
        onCreateDialog(ChangeBannerDeliveryBetweenTimeDialog_ID).show();
    }
}

private void setOff() {
    if(setOff){
        Id.setOn(false);
    }
    else if(!setOff){
        Id.setOn(true);
    }
}

private void setIds(TableRow tr){
    onOff = (OnOffButton) tr.findViewById(R.id.sectionOnOff);
    editButton = (EditValueButton) tr.findViewById(R.id.editTime);
    sectionName = (TextView) tr.findViewById(R.id.sectionName);
}

private void setTagstoViews(int i){
    onOff.setTag(""+i);
    editButton.setTag(""+i);
}
private void setListeners(){
    editButton.setOnClickListener(this);
    onOff.setOnOffChangeListener(this);
    onOff.setOnClickListener(this);
}

public HashMap<String, Time> getBannerSectionwithTime(){
    return hm;
}
private void addViewstoList(){
    onOffList.add(onOff);
    editList.add(editButton);
    tList.add(sectionName);
}

private void makeSectionActive(View v){
    TextView tt = tList.get(Integer.parseInt(v.getTag().toString()));
    activeSection = tt.getText().toString();
}

private void changeTimeText(View v, String text){
    EditValueButton tt = editList.get(Integer.parseInt(v.getTag().toString()));
    tt.setText(text);
}

public  boolean checkSectionOn(){
    return checkSection;
}

private class CustomTask extends AsyncTask<String, Void, Boolean>{
    private ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        dialog=ProgressDialog.show(getContext(), "", "Loading...");
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        dialog.dismiss();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return null;
    }

}

}
I want to use Async task to put all Ui in postexecute and loops in doinbackground?
In loop i have my table row which consumens 5secs to 8sec to load so can we somehow add the loop in do in background? Any help would be appreciated. Please provide code sample for better understanding
Comment: What happens while this `loop` runs? Is the user able to do anything else?
Answer: First define what is your time consuming task. If you want creation of your Table to be in asyncTask here is a hint how to do it. First you need to create entire Table off screen and then add it to your Layout
private TableLayout table;

private void init(){
    new CustomTask().execute();
}

private class CustomTask extends AsyncTask<String, Void, Boolean>{
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog=ProgressDialog.show(getContext(), "", "Loading...");
}

@Override
protected Boolean doInBackground(String... params) {
    // Here is the part where you create your table and do extensive work
    // For example
    for(int i =0; i< sectionNames.size();i++){
            TableRow tr = new TableRow(context);
            View line = new View(context);
            line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
            line.setBackgroundColor(textNormalColor);
            line.setPadding(0, 10, 0, 10);

            layoutInflater.inflate(R.layout.sectiontablerow, tr);
            table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
            table.addView(line);

            setIds(tr);
            setTagstoViews(i);
            addViewstoList();
            setListeners();
            checkIfSectionIsOn(i);
            tList.get(i).setText("sai ram");
        }
    return null;
}

@Override
protected void onPostExecute(Boolean result) {
    super.onPostExecute(result);
    //And now add your tableLayout in your Layout
    layout.addView(tableLayout);
    // Adjust layout params per need
    dialog.dismiss();
}

}

Adjust all of this according to your needs.
Hope this helps and enjoy your work.

Custom View Async Task


Subconscious Plagiarization in Music Production

Question: I have effectively no training in music theory, and have only ever produced a handful of "songs" (unpublished files on my hard drive, resulting from aimless experimentation with production software).
While I attempt to be as original as possible, I invariably realize, long after I've finished a piece, that it shares a significant component with an existing song.  I subconsciously copied something major from another song, while under the impression I was creating it from scratch.  I understand the truism that good artists copy, and great artists steal, but the similarities are too great to remain satisfied with my piece as an original work.
Is this is a common psychological barrier in music production?  Are there any solutions to help ensure the time spent producing is actually yielding original content?
Comment: "I understand the truism that good artists copy, and great artists steal" -- I would be interested to know how you interpret this oft-cited piece of wisdom. The only way it makes sense to me as anything other than a platitude is that when you copy something, you copy it from someone else, but when you steal it you make it your own.
Comment: There is nothing new under the sun. Just write/play what you enjoy!
Comment: @DavidBowling - perhaps Beethoven had something like this in mind when he mischievously told his publisher that his string quartet opus 131, the _Sturm und Drang_ one, was "stolen together out of various bits of this and that".
Answer: The music we create is often a fusion of bits a pieces created from inspiration - whether consciously or subconsciously. The satisfied ear doesn't care that a chord progression has been used in thousands of pop songs.
If you want to spice things up a little bit you could try reharmonisation. That's fun, and you can end up with a completely different feel and sound. I often take MIDI files from old games (Donkey Kong ... David Wise) and reharm them. The end result is nothing like the original and is a unique track in its own right.
Answer: One thing you could try (which works for me) is to make the melody one of the last things you write. In most circumstances, the melody is the only non-lyrical part of a composition that can be copyrighted. So it's the main thing that will make your song sound like another.
I usually have the style, beat, chord progression, and lyrical idea before I ever start working on the melody. And then, I try not to go with the first melodic idea that comes to me (because I probably heard it before, or it's obvious enough to have already been used).
I used to be in the same boat as you, but since I developed this process I have never felt that any of my compositions significantly reminded me of anything I'm at least familiar with.
Answer: This is how people learn in all aspects of life, by imitation.  What you digest will eventually get fused in your brain and come out as something "new" and creative.  In my opinion the only way to avoid it is to not listen to music.  But this would effectively turn you off.  We are feedback loops, listening to each other and repeating what we hear with slight variations.  I'd argue that one could avoid direct plagiarism by listening to a wide variety of music.  This broadens the scope of your data input and you will likely create a fusion that is truly new.
It happens to me all the time, riffs from my favorite bands creep up when I least expect it.  When we were young my friend (a bassist) and I (a guitarist) would spend hours trying to come up with "original" jazz chord progressions.  After learning enough about substitution it became apparent that the ones we liked were actually variants of a standard progression.  We rediscovered the wheel.
I would strive to understand the way humans learn and embrace it.  Open up to all the musical sources you can, even ones that would make you cringe.  Like I said the variety will keep you on your creative tones.
Comment: "the only way to avoid it is to not listen to music" – [relevant](https://www.youtube.com/watch?v=jQqK1CjE9bA).
Comment: I did say "in my opinion".  Thanks for the culture lesson.
Answer: I write Celtic tunes on my mandolin, and run into the same issue. Sometimes I rewrite an existing tune in its entirety! One trick I use is to run my composition (play it) into an iPhone app called Tunepal, which attempts to recognize Celtic pieces, and provides a list of possibilities which I can listen to. There may be other apps (Shazam comes to mind) that do this for pop songs.


Como atrelar uma variavel de titulo em uma função de plotagem de grafico?

Question: CODIGO:
def cria_grafico (x,y,titulo):

  plt.figure(figsize = (10,8))

  sns.boxplot(x=x,y = y, data=dados,order=renda_ordenada)

  plt.title()

Na parte plt.title() como devo informar a variável título?
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Para criar um título usando a variável da sua função, apenas adicione a variável dentro do campo,  o seu caso titulo:
plt.title(titulo)

Veja aqui na documentação do matplotlib
https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/titles_demo.html#sphx-glr-gallery-text-labels-and-annotations-titles-demo-py


Bird's Probabilities

Question: Please, could somebody help me to figure this exercise?
You collect data on the wing lengths $(Y_i)$ of $50$ bald eagles in one sample.  The average wing length ($Y$ sample average) is $89$ cm and the variance ($s^2$) is $16$ cm.

What is $P(Y \leq 85)$?
What is $P(Y \geq 97)$?
What is $P(82 \leq Y \leq 98)$?

If you could sample $n=50$ birds $10$ times (that is, $N=10$), what do you expect the sample average to be?
What is the standard error of the mean?
Comment: (-1) It is not such a good idea to post a bunch of questions without giving any ideas you have about them, or what methods you think you need to use or what you need help with . It makes potential answerers think that you are lazy and just want others to do your work for you.
Comment: The unit of the variance in this case is cm$^2$. The unit of standard deviation is cm.
Comment: It's a fair your comment Fortuon Paendra. However, it is not the case!
Answer: The first thing you will have to understand is that since you are collecting data on 50 birds, the distribution of this sample is normal, regardless of the distribution of the wing lengths of the birds.
Now, if you know that, then the sample mean, denoted typically by $\mu_\bar{x}$ is
$$\mu_\bar{x} = \frac{\overbrace{89 + 89 + 89 + ... + 89}^{\text{50 times}}}{50} = 89
$$
And the sample variance, denoted by $\sigma_{\bar{x}}^2$ is
$$\sigma^2_\bar{x} = \frac{16}{50} = 0.32
$$
I'll leave it to you to complete the question.

Bird's Probabilities


How do I set the opacity of a vertex in OpenGL?

Question: The following snippet draws a gray square.
glColor3b(50, 50, 50);

glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();

In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque?
Comment: related http://stackoverflow.com/questions/1617370/opengl-alpha-transparency
Answer: In the init function, use these two lines:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

And in your render function, ensure that glColor4f is used instead of glColor3f, and set the 4th argument to the level of opacity required.
glColor4f(1.0, 1.0, 1.0, 0.5);

glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();

Comment: Saving lives even 11 year later.
Answer: glColor4f(float r,float g, float b, flaot alpha);
(in your case maybe clColor4b)
also make sure, that blending is enabled.
(you have to reset the color to non-alpha afterwads, which might involve a glGet* to save the old vertexcolor)
Answer: You can set colors per vertex
glBegin(GL_QUADS);
glColor4f(1.0, 0.0, 0.0, 0.5); // red, 50% alpha
glVertex3f(-1.0, +1.0, 0.0); // top left
// Make sure to set the color back since the color state persists
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();

Answer: Use glColor4 instead of glColor3.  For example:
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glColor4f(1.0f,1.0f,1.0f,0.5f);

Comment: Thanks. Hmm, doesn't seem to be working for me, what could I be doing wrong?


Trying to replace spaces with dashes using ng-model

Question: I'm new to AngularJS and trying to create a simple app that will allow me to upload files to my Laravel driven website. I want the form to show me the preview of what the uploaded item will look like. So I am using ng-model to achieve this and I have stumbled upon the following:
I have an input with some basic bootstrap stylings and I am using custom brackets for AngularJS templating (because as I mentioned, I am using Laravel with its blading system). And I need to remove spaces from the input (as I type it) and replace them with dashes:

<input type="text" plaeholder="Title" name="title" class="form-control" ng-model="gnTitle" />

And then I have this:
[[gnTitle | lowercase]]

And my app.js looks like this:
var app = angular.module('neoperdition',[]);

app.config(function($interpolateProvider){
    $interpolateProvider.startSymbol('[[').endSymbol(']]');
});

app.filter('spaceless',function(){
    return function(input){
        input.replace(' ','-');
    }
});

I get the following error:
TypeError: Cannot read property 'replace' of undefined
I understand that I need to define the value before I filter it, but I'm not sure where to define it exactly. And also, if I define it, I don't want it to change my placeholder.
Comment: Welcome to Stackoverflow! There's no need for tags in titles. Please read http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles for more information.
Answer: There are few things missing in your filter. First of all you need to return new string. Secondary, regular expression is not correct, you should use global modifier in order to replace all space characters. Finally you also need to check if the string is defined, because initially model value can be undefined, so .replace on undefined will throw error.
All together:
app.filter('spaceless',function() {
    return function(input) {
        if (input) {
            return input.replace(/\s+/g, '-');
        }
    }
});

Demo: http://plnkr.co/edit/5Rd1SLjvNI18MDpSEP0a?p=preview
Answer: Bravi just try this filter
    for eaxample {{X | replaceSpaceToDash}}
 app.filter('replaceSpaceToDash', function(){
                var replaceSpaceToDash= function( input ){

                        var words = input.split( ' ' );
                         for ( var i = 0, len = words.length; i < len; i++ )
                             words[i] = words[i].charAt( 0 ) + words[i].slice( 1 );
                         return words.join( '-' );
                     };
                     return replaceSpaceToDash;
            });

Answer: If you are using a new(er) Angular version and [(ngModel)]="title", you can use getter and setter like so:
private _title: string = '';

public set title(title: string) {
    this._title = title.replace(/\s+/g, '-');
}
public get title(): string {
    return this._title;
}

But there are many ways to deal with this, like using form controls with events, or directives to name a few.
Answer: First, you have to inject your filter in you module by adding it's name to the array :
var app = angular.module('neoperdition',['spaceless']);
Secondly, the function of the filter have to return something. The String.prototype.replace() return a new String. so you have to return it :
app.filter('spaceless',function(){
    return function(input){
        return input.replace(' ','-');
    }
});

Edit: dfsq's answer being a lot more accurate than mine.
Comment: Are you sure? I thought I could only inject other modules in there and not filters. And plus I'm actually getting a new error now that 'spaceless' is not a module...
Comment: No, you're right. dfsq's answer is much more accurate and precise.


Solution of the following PDE

Question: How to solve the following pde: $$u_{xy}=u_{x}u_{y}$$ with $$\begin{cases}
u(0,0)=c\ :c\in \mathbb{R}\\
u(x,0)=f(x)\\
u(0,y)=g(y)
\end{cases}$$
Any hints are appreciated.
Comment: Sorry, I meant to type $c = f(0) = g(0)$, but I understand that no such condition is given. I believe I know the solution, and will write it up, when $c = f(0) = g(0)$. Otherwise the boundary conditions are inconsistent, and I'm not sure what happens...
Comment: Does $c = f(0) g(0)$?
Comment: No, that is not given.
Answer: I'm going to describe a solution for the special case where $c = f(0) = g(0)$. When this condition is not obeyed, the boundary conditions are inconsistent and discontinuous at $(x,y) = (0,0)$. I'm not sure what happens then.
We perform the following steps, starting with the original PDE as stated:
\begin{align*}
u_{xy} &\;=\; u_x \, u_y\\[0.1in]
\frac{u_{xy}}{u_y} &\;=\; u_x\\
\frac{\partial}{\partial x} \ln\left(u_y\right) &\;=\; \frac{\partial}{\partial x} u\\[0.1in]
\ln\left(u_y\right) &\;=\; u \;+\; w(y) \qquad\qquad (1)
\end{align*}
In the last line above, $w(y)$ is an as-yet-unknown function of $y$ alone. We apply one of the boundary conditions by taking $x\rightarrow 0$ in Eq. (1) to yield an expression for $w(y)$:
\begin{equation*}
\ln\left(g'(y)\right) \;=\; g(y) \;+\; w(y) \quad\rightarrow\quad
w(y) \;=\; \ln\left(g'(y)\right) \;-\; g(y) \qquad (2)
\end{equation*}
We exponentiate both sides of Eq. (1) and use Eq. (2) as follows:
\begin{align*}
\frac{\partial}{\partial y} u &\;=\; e^u \, e^{w(y)}\\
&\;=\; e^u \, \exp\Bigl[\ln\left(g'(y)\right) \;-\; g(y)\Bigr]\\
\left(\frac{\partial}{\partial y} u\right) \; e^{-u} &\;=\; g'(y) \, e^{-g(y)}\\
\frac{\partial}{\partial y}e^{-u} &\;=\; \frac{\partial}{\partial y} e^{-g(y)}\\
e^{-u} &\;=\; e^{-g(y)} \;+\; a(x)\\
u(x,y) &\;=\; -\ln \left[e^{-g(y)} \;+\; a(x)\right] \qquad (3)
\end{align*}
Here $a(x)$ is an arbitrary function of $x$ alone.
By an entirely-analogous argument, we can also obtain
\begin{equation*}
u(x,y) \;=\; -\ln \left[e^{-f(x)} \;+\; b(y)\right] \qquad (4)
\end{equation*}
for some unknown function $b(y)$. Combining Eqs. (3) and (4) then implies that
\begin{equation*}
u(x,y) \;=\; -\ln \left[e^{-f(x)} \;+\; e^{-g(y)} \;+\; K\right] \qquad (5)
\end{equation*}
Here $K$ is an unknown constant. By enforcing either boundary condition ($u(x,0) = f(x)$ or $u(0,y) = g(y)$) in Eq. (5) and using the fact that $c = f(0) = g(0)$, we find that $K = -e^{-c}$, in which case the final solution is:
\begin{equation*}
u(x,y) \;=\; -\ln \left[e^{-f(x)} \;+\; e^{-g(y)} \;-\; e^{-c}\right]
\end{equation*}
It is straightforward algebra to check that this solution obeys the original PDE as well as all of the boundary conditions.

Solution of the following PDE