Does finite variance imply on a finite mean?

Question:
Assume that a random variable has a finite variance. Does it mean it also has a finite mean?

My approach: I think since it has a finite variance, it means it is in $\mathcal{L}_2$ space of the probability measure $\mu$. Therefore, it should be in $\mathcal{L}_1$ space of the probability measure $\mu$ and thus the mean is finite.
IS that correct?
Comment: How can you define the variance, i.e. $$\mathbb{E}[(X-\mu)^2],$$ without knowing the expected value $\mu=\mathbb{E}[X]$?
Comment: Anyway, by Jensen's inequality $$\mathbb{E}[X]^2\leq \mathbb{E}[X^2].$$
Comment: The variance is not defined if the mean is not finite. As pointed out above, if the second moment is finite then the mean is finite.
Comment: My answer to your first part: the mean may exist but it can go to infinity, right? However, E[X^2]-E[X]^2 may be still finite. I agree with the second part
Comment: Thanks. My argument about L1 and L2 spaces are correct?
Comment: @JackD'Aurizio: You can still define it as $\inf_{a \in \Bbb R} \Bbb E[(X-a)^2]$, and in some books I've seen this done before proving that if said quantity is finite then the mean is finite (by Jensen) and that the infimum is achieved at $a = \mu$.
Comment: Yes, I think your argument is correct because probability spaces are finite measure spaces, $\mu(\Omega) < \infty$.
Answer: You just restated the problem. To prove it, use Cauchy Schwarz Inequality: $(E|X|)^2\leq EX^2$ for any r.v. $X$.Thus $E|X|\leq (EX^2)^{1/2}<\infty$ hence you have finite mean of $|X|$. Therefore, $EX^{+}<\infty, EX^{-}<\infty$ so $EX=EX^{+}-EX^{-}$is finite.
Comment: You proved that if $\operatorname{E[X^2]}$ is finite, then $\operatorname{E[X]}$ is finite too; but this is not what is asked here.
Answer: By definition, we know$\def\Var{{\textrm{Var}}\,}
\def\Cov{{\textrm{Cov}}\,}
\def\Corr{{\textrm{Corr}}\,}
\def\E{{\textrm{E}}\,}$ $\Var(X) = \E ( X - \E(X))^2$. Hence if variance is finite, $\E(X)$ has to be finite.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: If Var(X)=E[X^2]-E[X]^2, how do we know that it can't be possible that $E[X^2]=E[X]^2=\infty$ but they are different infinites so somehow their difference is finite?


How to append a div and an image dynamically?

Question: I wanted to ask that is there a way by which I can append a div and an image inside it using javascript?
So basiclly, images are stored in an array. displayAllImages function() appends the images to the div #images but I want that function should append a div and within the new div there should be the image may be as a background or an image contained in a div. This should repeat for all images as in 3 images should be display as 3 divs containing 3 different images/elements of the array. Try to stick to array implementation only. Thanks!
Jsfiddle : http://jsfiddle.net/1qk3voxq/

    var gallery= new Array();

    gallery[0]="http://s6.tinypic.com/1zd1a47_th.jpg";
    gallery[1]="http://s6.tinypic.com/2ngh9ty_th.jpg";
    gallery[2]="http://s6.tinypic.com/29zy5qf_th.jpg";

    var x= $("#images");

    function displayAllImages() {
        var i = 0,
            len = gallery.length;
        for (; i < gallery.length; i++) {

           x.append("");
        }
    };

    $(function() {
        displayAllImages();
    });
    #container {
     width:600px;
     height:600px;
     background-color:#000;
     }

    .roll {
        margin:4px;
      }

Comment: http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery?rq=1
Comment: When creating the code snippet, did you happen to notice that there were separate sections for JavaScript, HTML and CSS? You should put all the code in one snippet.
Answer: You mean like this?
x.append("

");

Updated Fiddle
Comment: actually it works! I'll figure out the rest! Thanks!!
Comment: This seems to work but if I add a class to just created div and apply css to it (width and height) then that doesn't work. Moreover, why aren't they appearing in a row?
Comment: Because divs are block-level elements by default, if you want them to appear in a row, you need to set the inner div css to "display:inline-block;" [like this](http://jsfiddle.net/1qk3voxq/2/). I'm not sure what you mean about the classes.
Comment: http://jsfiddle.net/1qk3voxq/6/
 check this. Why there is no effect of width and height?
Comment: No problem, let me know if you run into any other issues.
Comment: http://jsfiddle.net/1qk3voxq/7/ What if I need to align the image in the center of the div. Sorry, I am an amateur.
Comment: You want the entire image to be visible, or just to center what is visible?
Comment: You can make the entire image visible by setting `max-width:100%;` on the image, [like this](http://jsfiddle.net/1qk3voxq/8/). Not sure what you mean. I'm off to lunch but will be back later.
Comment: @Yomesh - Horizontal center align is `text-align:center;` in CSS
Comment: @Yomesh - And if I may just give some other advice: `var i = 0;` followed by `for (; i < gallery.length; i++) {` really doesn't save that much resources or speed. I'd say just use `for (var i=0; i<gallery.length; i++) {` (but maybe that's just me)
Comment: @Yomesh & APAD1 - But what isn't just me is this: `len = gallery.length;` followed by `for (; i < gallery.length; i++) {`... You are storing the array-length into a variable, but then you go and just reference the array directly in the for-loop. You never use the `len` var.
Comment: @APAD1 - Actually I am using this as thumbnails for my slider/lightbox. So, when user hovers over any image then some event should trigger may be a caption should appear or some effect. See this : http://jsfiddle.net/yomesh/1qk3voxq/13/ Can you please suggest some effects and ways to implement them on hover. Thank you :)
Comment: @myfunkyside - yes I know. I'll delete the repeating/useless code once I am done with what I want to achieve.
text-align:center to align images in the center of div wasn't working.
Check out the latest fiddle I posted and tell me if my method of lightbox is decent or not and if you can suggest some ways to make thumbnails look better then it would be great!
Comment: @Yomesh - Oh also, this `$(function() {displayAllImages();});` is really not necessary. You can just call `displayAllImages();` directly, does not need to be wrapped in a function.
Comment: @myfunkyside if in the fiddle http://jsfiddle.net/yomesh/1qk3voxq/15/ I delete the " len " then the pics just disappear. Any idea why?
Comment: @APAD1 if in the fiddle http://jsfiddle.net/yomesh/1qk3voxq/15/ I delete the " len " then the pics just disappear. Any idea why
Comment: @Yomesh - Because now (if you did what I think you did) the line above that looks like this: `var i = 0,`. You need to remove that comma and close it with a `;`
Comment: @myfunkyside : Ya. I didn't notice that. Did you see the whole code? Thanks!
Comment: @Yomesh - I'm looking at your version 13 now. It's got quite a few errors. It's probably better to start a new question for your new problem. Here: **http://jsfiddle.net/1qk3voxq/18/**, I added some comments to your code to get you started.


How to hide index in Pandas dataframe to JSON function DataFrame.to_json() using 'columns' orientation

Question: Eg. My results are returned in this format
    "name": {
      "1": "bill",
      "2": "mike",
      "3": "dave"
    },
    "age": {
      "1": 20,
      "2": 21,
      "3": 40
    },

but I would prefer the following format
    "name": [
     "bill",
      "mike",
      "dave"
    ],
    "age": [
      20,
      21,
      40
    ],

Comment: if you are exporting the dataframe to `JSON` ?  if yes then give `index=False` while exporting
Comment: I've tried that but 'index=False' is only valid when 'orient' is 'split' or 'table'
Comment: Use `to_dict()` with `orient='list'` then convert dict to JSON with double quotes.  See my answer for details.
Answer: The Pandas function DataFrame.to_dict() has an option orient='list' that outputs the layout you want.
The only difference is that it outputs a dict with single quote instead of JSON with double quotes.  You can further convert the dict to JSON, e.g. as follows:
class dict2JSON(dict):
    def __str__(self):
        return json.dumps(self)

    def __repr__(self):
        return json.dumps(self)

result =  dict2JSON(df.to_dict(orient='list'))

Demo
data = {'name': {1: 'bill', 2: 'mike', 3: 'dave'}, 'age': {1: 20, 2: 21, 3: 40}}
df = pd.DataFrame(data)

print(df.to_json(orient='columns'))

# Old Output
{"name":{"1":"bill","2":"mike","3":"dave"},"age":{"1":20,"2":21,"3":40}}

# Run new codes:
class dict2JSON(dict):
    def __str__(self):
        return json.dumps(self)

    def __repr__(self):
        return json.dumps(self)

result =  dict2JSON(df.to_dict(orient='list'))

print(result)

# New Output
{"name": ["bill", "mike", "dave"], "age": [20, 21, 40]}


Wiring switched receptacles

Question: I just moved to into a house and was trying to wire a new USB receptacle to an receptacle that is controlled by a switch. The old receptacle has the brass tab broken and the red wire is wired to the top brass terminal. The USB receptacle has only two terminal screws, so there's no way to wire the red wire to the switch. My question is, can I wire the USB receptacle to this outlet box without the red wire? Should I just nut/tape it off?
I do have a switch can controls overhead light, so I don't really need the switch to control that receptacle.
Comment: Thanks guys. Capped and taped off the red wire, kept the switch but labeled it for the next owner whenever that would be. Everything is working good.
Answer: You cannot "split" your new outlet. It must all be constant-on or switched. As you suspected, you need to connect only one of the hots (probably the black) and cap off the other. Do not try to connect both. At best, you'll bypass the switch for everything. At worst, you'll trip a breaker or, if the breaker fails, start a fire!
Answer: You are correct.  Simply cap off the switched red will be fine.

Wiring switched receptacles


UIView transitioning to the same view

Question: I have a UITableView controller displaying static tableview. I have to update the project providing a secondary mode where this tableview is supposed to flip and to show different data. My approach would be to put all the static cells of both modes in one big static tableview, to perform a flip and to hide the cell which are not required at that specific moment. The flip should be performed only on the tableviewcontrollerview,so not affecting the navigationbar or the main tabbar. The code I've been trying to use so far for realising this simple magic trick is:
// Transition using a page flip.
    [UIView transitionFromView:self.tableview
                        toView:self.tableview
                      duration:0.7
                       options:UIViewAnimationOptionTransitionFlipFromLeft
                    completion:^(BOOL finished) {
                        if (finished) {
                           /* HIDE NOT REQUIRED CELL */

                        }
                }];

Unfortunately the result is a black screen. Any idea how to fix it?
Comment: I can suggest only to use custom transition using CGAffineTranform matrix.
Answer: Try using the below code instead:
[UIView transitionWithView:self.tableView
                   duration:0.7
                   options:UIViewAnimationOptionTransitionFlipFromLeft
                   animations:^{
                          /* any other animation you want */
                  } completion:^(BOOL finished) {
                          /* hide/show the required cells*/
                  }];

Comment: I believe the issue here (which I just ran into without transitioning to the same view) is caused by other animations canceling or in some other way interfering with the transition. It's possible for the transition to become cancelled, leaving it in a state in which the completion block is NEVER CALLED. For me this resulted in the black screen because my completion block was manipulating my root view controller of the App to transition from the on-boarding experience to the main user experience. Hope this helps someone!
Answer: I think the main problem is, that views can have max one superview. Which means a view can not be in two places in the same time. I would try capture the view as image and add it on its superview just before animation and remove the real tableview from its superview. And then you can animate between two different views (image view and table view). In completion block just remove the image view.
How to capture the view :How to capture current view screenshot and reuse in code? (iPhone SDK)
Comment: this looks quite a ninja technique,but I will give a try. If you find the time for posting some sample code would be much appreciated ;)
Answer: I've accomplished this using a slightly different technique. Perhaps it's useful for you. the basic structure is that there is a MainContainerView and inside that is a MapView (in your case a table view). When I do the flip animation I grab the view of a separate view controller (list view) and add it as a subview to the MainContainerView and remove the MapView from the subview. When I want to flip back I do the opposite.
-(void)listViewButtonHandler:(id)sender
{
    if (_isMap) { //transition to view 2

        self.listViewController.view.frame = self.mainContainerView.bounds; //grab the view of a separate VC

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                               forView:self.mainContainerView
                                 cache:YES];
        [self.mapContainerView removeFromSuperview];
        [self.mainContainerView addSubview:self.listViewController.view];

        [UIView commitAnimations];
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"mapButton"] target:self action:@selector(listViewButtonHandler:)]; //change the button to another title

        _isMap = NO;
    } else {
        //transition to view 1
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                               forView:self.mainContainerView
                                 cache:YES];
        [self.listViewController.view removeFromSuperview];
        [self.mainContainerView addSubview:self.mapContainerView];

        [UIView commitAnimations];
        _isMap = YES;
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"actualListButton"] target:self action:@selector(listViewButtonHandler:)]; //change the button back

    }
}

I hope this is helpful and that it can apply to your situation!
Comment: Hey,thanks for your quick answer.Gonna try immediately, I'll let you know if it works...
Comment: The trick part adapting your code is that you have a main container view on which you apply the animation during which you remove the subview. I don't have a subview but just the tableview. Not sure if I'm clear
Comment: Right, you can restructure you code to have a `UIView` which is the `MainContainerView` and inside that put your `TableView`. In a separate `viewcontroller`you can have your second `TableView`???

UIView transitioning to the same view


Do Spartan Ops Missions Go Away?

Question: I purchased and played Halo 4 when it was released last winter. I only played one Spartan Ops mission. I had only downloaded the first episode at that point (it was the only one out at the time), so I'm not caught up on the current missions.
Can I still download and play all the older missions, even this long after original release?
Comment: The first 5 Episodes are on-disc content, they just unlocked them one week at a time.  You'll have access to all 5 of these Episodes without doing anything else.
Answer: Yes, all the Spartan Ops missions are available still.  The "second season" is free DLC, so you might have another download if you want to play past the 5th Episode.
All the ops are available in single player, splitscreen, and party play, but the chapters featured in online matchmaking rotate.  The experience gain from the online matchmaking is far greater, and you can play with random people on the internet, but otherwise they are identical.
Comment: Thanks! I'm not really interested with the Spartan Ops Matchmaking - more interested in the storyline than anything else.
Answer: Like most Shooters, special missions are available throughout their release and here after. There are no 'expiry dates' on these Op missions so you are able to play these if and when you desire.

Do Spartan Ops Missions Go Away?


How to collect to a List using streams returning my own List implementation?

Question: How to collect a stream into a list that is a subtype that I specify?
In other words, I'd like this test to pass.  What should I do on the commented line to convert a stream to a MyList instance?
import org.junit.*;
import java.util.*;
import static java.util.stream.Collectors.*;
import static junit.framework.Assert.*;

@Test
public void collectUsingDifferentListType() {
    List<String> aList = new ArrayList<>();
    aList.add("A");
    aList.add("B");
    List<String> list1 = aList.stream().collect(toList());
    MyList<String> list2 = aList.stream().collect(toList(MyList::new));  // this doesn't exist, but I wish it did

    assertEquals(aList, list1);
    assertEquals(ArrayList.class, list1.getClass());
    assertEquals(aList, list2);
    assertEquals(MyList.class, list1.getClass());
}

Comment: The first assertion is wrong. The returned list of `toList()` happens to be an `ArrayList` in Oracle's current implementation, but there is no specification guaranteeing you this. On the other hand, the second assertion is not of much use, as the operation fails with a `ClassCastException` if `list2` is not of `MyType` much earlier (unless you consider the possibility of a spurious subclass creation)… and you have a copy&paste error there.
Answer: Assuming the MyList type is a Collection, you can use Collectors.toCollection:
MyList<String> list2 = aList.stream().collect(toCollection(MyList::new));

Comment: This also assumes MyList is mutable.
Comment: @bowmore Well, if the `add` method throws an `UnsupportedOperationException`, there's not much sense in collecting a Stream into it, right?
Comment: @bowmore: so does the OP in the question, apparently.
Comment: I'm just adding to the answer, it may be obvious to you, it may not be to the OP.


event.stopPropagation() is not worknig?

Question: I have implemented click event on window and on specific element. I want to stop window click  event propagation on particular element click as mentioned below but it is not working. I am not sure what wrong I am doing here.
$('.dropdown-container').click(function(event){
  event.stopPropagation()
  var selectElement = '.dropdown-container > select';
  if($(selectElement).hasClass('actionDD')){
    $(selectElement+'.actionDD').toggleClass('special');
  }
  else if($(selectElement).hasClass('countryDD')) {
    $(selectElement+'.countryDD').toggleClass('special');
  }
  $('.fa-chevron-down.importC, .fa-chevron-down.exportC ').removeClass('special');
});

$(window).click(function(event){
  console.log('window event clicked');
  $('.dropdown-container, .fa-chevron-down.importC, .fa-chevron-down.exportC').removeClass('special');
});

Comment: TYPO: `e.stopPropagation()` to `event.stopPropagation()`
Comment: As above, or `.click(function(e) {`
Answer: Apart from the typos, if your selects are not nested just do this
$('.dropdown-container').on("click", "select", function(e){
  e.stopPropagation()

  if($(this).is('.actionDD') || $(this).is('.countryDD')) {
    $(this).toggleClass('special');
  }
  $('.fa-chevron-down.importC, .fa-chevron-down.exportC ').removeClass('special');
});

$(window).on("click", function(e){
  console.log('window event clicked');
  $('.dropdown-container, .fa-chevron-down.importC, .fa-chevron-down.exportC').removeClass('special');
});

Please post your HTML since this works:

$('.dropdown-container').on("click", "select", function(e) {
  e.stopPropagation()
  if ($(this).is('.actionDD') || $(this).is('.countryDD')) {
    $(this).toggleClass('special');
  }
});

$(window).on("click", function(e) {
  console.log('window event clicked');
});
.special {
  background-color: red;
}

  <select class="actionDD">
    <option>Click</option>
  </select>

Comment: Yes, it is working indeed. Thanks mplungjan
Comment: It is not working, still I am getting "window event clicked" on console.
Comment: Please see my update. We need to see your HTML

event.stopPropagation() is not worknig?


How to convert images selected to string for storing?

Question: I have images in Assets.xcassets named city_00,city_01,...,city_10
I stored them in an array
 let cityImages: [UIImage] = [UIImage(named: "city_00")!,UIImage(named: "city_01")!,.....UIImage(named: "city_10")!]

Then I call them using collectionview in my project and allow users to select any city they like
 var imageSelected = [UIImage]()
 var cityImage:UIImage?

   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        collectionView.allowsMultipleSelection = false
        cityImage = imageSelected[(indexPath as NSIndexPath).row]
}

I like to save the selected image in database by converting them back into string. How do I do this?
Comment: Then just store the name string (`city_00 `,...), what's the real problem?
Comment: Take more space? its like few more bytes, it's not like you store the whole images...., if you don't want to waste some bytes then store Int is fine, store 00, 01,...
Comment: name strings takes more space than integers, that is why I was wondering
Comment: @Tj3n, my problem is now that I have no idea how to convert selected image into its string literals
Comment: Convert `cityImages` to array of strings, then use it on cellForRow to set it to image view
Comment: `let cityImagesNames: [String] = ["city_00", ""city_01",...]` `cityImage = [UIImage(named: cityImagesNames[(indexPath as NSIndexPath).row]]` or something like this?
Answer: let cityImageData = UIImagePNGRepresentation(cityImage)
let imageString = cityImageData?.base64EncodedString()

Comment: I have an attribute called storedImage of type string in model, I am getting this fatal error "reason=Source and destination attribute types are incompatible"
Comment: are you using core data? however, your question was about converting an image to string, if you alt + click imageString you'd find that it's of type string, I'm not sure about your model's attribute, maybe you can. send more code snippets so I can help
Comment: Appreciate it. Please see edited question. I am using core data.
Comment: I am sorry @leaner122 , I don't know much about core data, I don't use it for storing data, instead I use user defaults, maybe you can post another question that's related to core data so others can help with this issue


Unable to connect from django to mysql database

Question: I have created the database on XAMPP mysql which is up and running.
The database is created,

I am now trying to connect from django with the following connection parameters,
DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': "djangoproject",
            'USER': 'root',
            'PASSWORD': '******',
            'HOST': 'localhost',
            'PORT': ''
        }
    }

I am getting the following error when executing python3 manage.py runserver and python3 manage.py migrate
django.db.utils.OperationalError: (1049, "Unknown database 'djangoproject'")

I have read a solution to create the database from mysql shell using the create database statement. My question is why i am not able to connect to the database already created on XAMPP mysql.
Comment: try connecting with mysql client via command line first. If it works then your django should work.

mysql -uroot –p  djangoproject

If this work fine then issue with django else issue is in mysql.

This is just clue to debug your issue and not the solution.
Comment: Do you have multiple mysql instances installed on your computer? If yes, you may be connecting to the wrong one.
Comment: @shadow I don't believe I do though i did execute pip3 install mysqlclient.
Comment: @sopan So i logged in mysql and used 'show databases;' The djangoproject database is not there in the list.
Comment: The databases i see when executing 'show databases;' are information_schema, mysql, performance_schema and sys.
Comment: @Ayubx Try to create it `CREATE DATABASE djangoproject` and try again.
Comment: @GiorgosMyrianthous Yes i assume that will work but what I would like to understand in that case is the purpose of the creating the database as i did via XAMPP. Phrased differently why am i not able to connect to the database created via XAMPP. Thank you.
Comment: These all just confirm my initial theory of you connecting to a different mysql server with your python code.
Answer: You've missed the port. By default, MySQL is listening to 3306:
DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': "djangoproject",
            'USER': 'root',
            'PASSWORD': '******',
            'HOST': 'localhost',
            'PORT': '3306'
        }
    }

Comment: Thank you, tried that. Did not work. Fyi i just installed XAMPP and created the database there. I did not install mysql separately.


How is melee combat experience calculated in Morrowind?

Question: In The Elder Scrolls III: Morrowind, I am having difficulty selecting a weapon to use. I have several with higher base damage and not-so-useful enchantments, and several with lower base damage and very effective enchantments. I want to use one which is enchanted with Fire Damage and has lower base damage, but I still want to efficiently gain Blunt Weapon levels.
Would leveling up be slowed down by using a weapon with lower base damage?
Is damage from enchantments accounted for in experience in the appropriate weapon skill, or is experience calculated in a different way entirely (per successful hit)?
Answer: According to the UESP Wiki, weapon skills are trained regardless of damage inflicted. Each successful hit yields 1.0 EXP Points


Problems with permissions in GCLOUD

Question: I have created an Organization and a Folder with the company's development email account.
The idea is to have sufficient permissions so that by API you can create projects, link these to dialogflow.
I would also use an API to create several DialogFLow projects without creating it on the Google console side
Comment: what issues you are facing?
Comment: When a use the Dialogflow API to create Agent i only can create a agent by project.
Answer: In order to create projects via API in GCP you need to have Project Creator role (resourcemanager.projectCreator) at the Organization level. You can find more information here on how to grant this permission.
Then you can create agents in Dialogflow using projects.agent API method. In this documentation You will learn aboutthe necessary Dialogflow permissions.

Problems with permissions in GCLOUD


What type of grout and mortar should I use for the compartment around my wood stove?

Question: I would like to tile around the inside of my fireplace but I am unsure what type of grout I should use. My only problem is the stove can produce an extreme amount of heat, therefore, causing the tiles to fall off if I use the wrong type of grout.
Is there a type of grout, cement or adhesive that is resistant to extreme heat?
Note: the tiles of which I will be using are fire and heat resistant.
Below is an image of the area within my fireplace of which I am tiling: (note: at the time of tiling the wallpaper will be removed)

Thanks.
Comment: Grout and cement (mortar) are not the same thing. Are you asking about one or the other or both? Also, if your fireplace hasn't caused that wallpaper and wooden baseboard to burst into flame, there's probably no concern with ordinary tile mortar and grout.
Answer: Yes, they have special epoxy mortar for heat sensitive locations.
To me, mortar is what is installed on the back of each tile that fastens the tile to the wall. Grout is what is used to "fill" the joint between each tile. (BTW, this is exactly opposite of terms used for laying concrete block walls...grout is what fills the cells and mortar is what goes in the joint.)
Each "stove" manufacturer have requirements for "non-combustible" clearances between the stove and combustible materials. You'll need to get the manufacturer's installation instructions (possibly from the internet).
BTW, you asked about the wall, but you'll need a non-combustible hearth too. Verify if your current wood floor can remain.
Also, verify the size of your existing flue is acceptable, depending on fuel type, (i.e.: wood, gas, etc.)
Comment: Thanks for your answer! The stove in the picture was used just for illustration. I have already purchased a hearth and I've had an expert visit to install the flue and sweep out the chimney. It will be hard to find manufacturer instructions with this particular stove as it's from the 1930's but I'm sure it'll be okay as there will be no combustible materials close by.


Ubuntu 16.04 'Suspend when inactive for...' and 'Turn screen off when inactive for...' doesn't work when on battery power

Question: Ubuntu 16.04 Suspend when inactive for... and Turn screen off when inactive for... doesn't work when system is on battery power.
Both of these work when plugged in and I can manually suspend (systemctl suspend) the system and wake it up again.
It's a Lenovo Ideapad U530 dual Win10 & Ubuntu 16.04.
Comment: I narrowed down the problem, but still don't have a solution. While trying to watch Netflix on battery I noticed that every 20 seconds the Netflix video menu pops up and the mouse pointer becomes visible. I unplugged the USB mouse and disabled the track pad and the touch screen, but still every 20 seconds something is causing a tiny mouse movement and this in turn causing the laptop not be able to sleep/suspend.
Answer: The latest Linux kernel update (linux-image-4.13.0-26 and a dozen or so more packages) received on 2018-01-10 fixed my problem.
Since that updated both 'Suspend when inactive for' and 'Turn screen off when inactive for' work when system is on battery power!


Lightdm crashes at seemingly random intervals

Question: I installed ubuntu 12.04 LTS around a month ago, and it's a great experience. Except for one thing: Lightdm crashes at seemingly random times, on average 2 times on a normal working day. I have no idea why, and I don't see a pattern. I've obviously looked through askubuntu and other resources but can't seem to find a solution, or even a clue as to what might be wrong.
Details:

When a crash occurs the screen freezes, but the mouse cursor still moves freely. I can move the mouse around, but I can't click on anything.
I see no discernable pattern in user behaviour when a crash occurs. I often have VLC media player open, and almost always a browser. At first I thought it might be the browser, so I switched from Chromium to firefox. The problem remained. So it isn't seemingly related to any one program.
I can press CTRL-ALT-F2 to bring up a commandline, then run sudo lightdm stop and sudo lightdm start. This kills lightdm and starts it again, but I lose everything I was working on at the time. (this is also why I presume it's lightdm that's the problem - it might not be though)

Here are some clues about the system I'm running.
Hardware

Hardware is a lenovo T60 with 2GB ram.
The battery is dead, so it only runs on mains
I did a memory check of the RAM, and it's OK.
The CD-drive doesn't work
Dual screen setup with laptop monitor and an external 1920x1080 screen driven by the T60's external screen output
3G Internet. Crashes happen both when I have the 3G USB dongle connected directly to the computer, and when I connect via wi-fi.
The T60 is in a dock.
External standard USB mouse and keyboard

Other clues

Installed programs (on top of base installed programs): VLC, libre office, mysql, nginx, php-fm, firefox, blender, arduino IDE, GNU emacs.
I sometimes at random times see the laptop monitor (never the external monitor) blink for what looks like a frame or two.

at startup I see "TMP drive not mounted, would you like to wait" which I do, and it keeps on booting (not exact wording but pretty close)
There is no pattern as to when the screen freezes. No particular action seems to trigger it.

I'm fairly new to ubuntu and linux, so I'm quite clueless as to what this might be.
Any ideas, and pointers would be much appreciated!
Answer: Try using 'GDM' instead of 'LightDM.'
<code>sudo apt-get install gdm
sudo dpkg-reconfigure gdm
</code>


Looking for a paper of A.bella in 1987

Question: Looking for a paper:

Bella A. Remarks on the metrizability degree[J]. Boll. Un. Mat. Ital. A (7), 1987, 1(3): 391-396.

Could you help me?
Comment: I do not see why this has a close vote. Finding papers can be difficult, and asking here is a good idea.
Comment: (To answer the question, you could try e-mailing A. Bella? His e-mail address can be found on his [arXiv papers](http://arxiv.org/find/math/1/au:+Bella_A/0/1/0/all/0/1).)
Answer: The journal this citation is taken from is Unione Matematica Italiana. Bollettino. A.  The electronic text of this bulletin is not available online.  If you are based at Cambridge, Glasgow or Edinburgh Universities then you can find a copy in their University libraries.
If you go to this link you can find the closest library to you that has a copy.
Otherwise, it's on Google books at http://books.google.co.uk/books/about/Bollettino_della_Unione_matematica_itali.html?id=LcTxAAAAMAAJ&redir_esc=y , which might give you more information on how you might get a copy.

Looking for a paper of A.bella in 1987


Equality case in Dirichlet's approximation theorem

Question: In its strong form, Dirichlet's approximation theorem (for dimension one)  states that for $\alpha\in{\mathbb R}$, and an integer $n\geq 1$, we have
$$
\min_{1\leq k\leq n}\| k \alpha \| \leq \frac{1}{n+1}
$$
where $\|x\|$ denotes distance from $x$ to the closest integer.
This strong form is shown here on MSE for example.
My question: how to prove or disprove that equality is reached (in other words $\min_{1\leq k\leq n}\|k \alpha\|$ is equal to $\frac{1}{n+1}$) iff $\alpha$ is a reduced fraction with denominator $n+1$ ?
One of the directions is easy : if $\alpha=\frac{j}{n+1}$ with $j$ coprime to $n+1$, then there is a $k\in[1,\ldots, n]$ such that $jk\equiv 1  (\mod  n)$, and we then have $\| k\alpha \| = \frac{1}{n+1}$ ; furthermore, all the other $\lbrace k'\alpha \rbrace$ for $k'\neq k$ are (not necessarily reduced) positive fractions with denominator $n+1$, so that $\|k'\alpha\| \geq \frac{1}{n+1}$.
Update 01/02/2023 In the other direction, suppose that $\min_{1\leq k\leq n}\| k \alpha \|=\frac{1}{n+1}$ and that this min is attained at some $k_0\in [1,\ldots, n]$. Then $\|k_0 \alpha \|=\frac{1}{n+1}$ means that there is an integer $q$ such that $k_0\alpha = q \pm \frac{1}{n+1}$, or $\alpha=\frac{q(n+1)\pm 1}{k_0(n+1)}$. The goal is then to show that either $k_0$ divides the numerator, or else $\|k\alpha\| \lt \frac{1}{n+1}$ for some $k$. We have thus reduced the problem to a purely arithmetic question, and I'm therefore adding the [modular-arithmetic] tag.
Answer: Here is a proof for the "only if" direction.

Suppose for $\alpha\in{\mathbb R}$, and an integer $n\geq 1$, we have $\min_{1\leq k\leq n}|| k \alpha || = \frac{1}{n+1}$.
Let ${x}$ be the fractional part of $x$, i.e., ${x}=x-\lfloor x\rfloor$. Consider $\{\alpha\},\{2\alpha\},\cdots,\{n\alpha\}$. Sort them into a (weakly) increasing sequence $a_1,a_2,\cdots,a_n$. In other words, $a_i\le a_{i+1}$. $\ a_i=\{k_i\alpha\}$, where $k_1,k_2, \cdots, k_n$ is a permutation of $1,2,\cdots, n$.
Since $a_{i+1}-a_i=(k_{i+1}\alpha-\lfloor k_{i+1}\alpha\rfloor)-(k_i\alpha-\lfloor k_i\alpha\rfloor)=(k_{i+1}-k_i)\alpha-b_i$, where $b_i=\lfloor k_{i+1}\alpha\rfloor-\lfloor k_i\alpha\rfloor$ is an integer, we have
$$\|a_{i+1}-a_i\|=\|(k_{i+1}-k_i)\alpha\|$$
Since $1\le |k_{i+1}-k_i|\le n$, $\|(k_{i+1}-k_i)\alpha\|=\|\,|k_{i+1}-k_i|\alpha\,\|$$
\ge\frac1{n+1}$. Since $a_{i+1}\ge a_i$, we must have $a_{i+1}-a_i\ge\frac1{n+1}$, for all $1\le i\le n-1$.
Also note that $a_1\ge\frac1{n+1}$ and $1-a_n\ge\frac1{n+1}$. We have
$$\begin{aligned}
1&=a_1+(a_2-a_1)+(a_3-a_2)+\cdots+(a_n-a_{n-1})+(1-a_n)\\
&\ge (n+1)\frac1{n+1}\\
&=1
\end{aligned}$$
Hence, $a_1=a_2-a_1=a_3-a_2=\cdots=a_n-a_{n-1}=1-a_n=\frac1{n+1}.$
So $a_i=\frac i{n+1}$ for all $i$. In particular, $\{\alpha\}=\frac m{n+1}$ for some integer $m$. So, $\alpha=\frac {m'}{n+1}$, where $m'=m+\lfloor \alpha\rfloor(n+1)$ is an integer.
$m'$ and $n+1$ must be coprime. Otherwise, $\|((n+1)/d)\alpha\|=0<\frac1{n+1}$, where $d=\gcd(m', n+1)>1$, which contradicts with the given condition since $(n+1)/d$ is an integer between $1$ and $n$.


Android Spinner dialog popup not working after update from sdk 28 to sdk29

Question: I have a App with a popup dialog spinner that used to work on SDK 28 without problems.
Now i have migrated to SDK 29 AndroidX and the popup does not work anymore.
Spinner_LockSetting = (Spinner) findViewById(R.id.Spinner_LockSetting);
SettingValueAdapter adapter = new SettingValueAdapter(this, android.R.layout.simple_spinner_dropdown_item, SettingValue.values());
Spinner_LockSetting.setAdapter(adapter);

        Spinner_LockSetting.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                   // do something
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

Layout XML
<Spinner
     android:id="@+id/Spinner_LockSetting"
     android:layout_width="100dp"
     android:layout_height="50dp"
     android:prompt="@string/app_name"
     android:spinnerMode="dialog" />

When i click on the spinner i get this exception:
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
        at com.android.internal.app.WindowDecorActionBar.getDecorToolbar(WindowDecorActionBar.java:251)
        at com.android.internal.app.WindowDecorActionBar.init(WindowDecorActionBar.java:196)
        at com.android.internal.app.WindowDecorActionBar.<init>(WindowDecorActionBar.java:180)
        at android.app.Dialog.show(Dialog.java:437)
        at androidx.appcompat.widget.AppCompatSpinner$DialogPopup.show(AppCompatSpinner.java:908)
        at androidx.appcompat.widget.AppCompatSpinner.showPopup(AppCompatSpinner.java:608)
        at androidx.appcompat.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:452)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30250)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8425)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:596)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

When i set the spinnermode XML to dropdown it works without problems.
I don't know where the NullPointerException is referring to, do i need to do more with dialogs in AndroidX vs SDK28?
I have made a clean activity to test and is seems the issue is related to a theme.
android:theme="@android:style/Theme.Holo"
Answer: If you want to show your spinner  as a popup dialog try this

android:spinnerMode="dialog"

For dropdown

android:spinnerMode="dropdown"

If they didn't work add this line also

style="@android:style/Widget.Spinner.DropDown"
Comment: ```android:spinnerMode="dialog"```
I already have this in my XML and it gives an exception.
Comment: ```style="@android:style/Widget.Spinner.DropDown"```
Adding this does not change the exception.


Generating metadata ("bindings" library) from C# DLL to Mono

Question: I have a C# library project targeting Windows 8.
I'd like to build a tool that will act similarly to what tblimp does:

Go over all public types in the library (DLL).
Export these into a new "wrapper" DLL (method bodies will be left blank, although this behaviour can be configured).

The new generated DLL could be referenced in other projects that didn't support the original DLL (just for the sake of building the project, since the methods themselves don't contain any functionality).
The main benefit is to use the generated DLL as a reference to Mono projects.
Is there any tool that allows doing this?
Comment: Is the original DLL a .NET-DLL or another type of DLL? And what kind of projects are the projects that cannot reference the original DLL's? Are they .NET-projects or other type of projects?
Comment: I'd like to take a Windows Store library DLL (C#) and wrap all its code so it can be referenced from Mono.
Answer: I think that's possible if you can use Mono.Cecil to parse the original dlls (you might have to patch Cecil if in some corner cases it fails). Then with the objects you get in memory, you can generate whatever assemblies you need to disk and use the generated assemblies for your purposes.
There are many open source projects based on Cecil that can lead you in this path, such as Obfuscar (an open source obfuscator),
http://obfuscar.codeplex.com/
Answer: I'm doing the same right now - I'm creating a tool called Piranha which removes all code and all non-public members leaving only a "skeleton".
It's not easy to make the resulting library CLS compliant.
There are problems with constructors: Constructors need to call base type constructors. But what if the constructor it calls is internal?
There are problems with structures: Looks like you cannot just remove all private fields since the size of the structure needs to be known (for a verifiable assembly).
But creating a skeleton library is not enough. You also need to remap/remove the references. Your Windows 8 library references WinRT libraries and won't be consumable by Mono libraries. You have to replace the WinRT library references with, most probably, PCL references form some profile. I still haven't done this part.
There also other referenced libraries. They'll drag their platform-specific references with them. So we need to either remove those references (and all members which depend on the types from those libraries) or convert the libraries to skeletons (and re-map the references).
If you're interested in such tool, I'll create a GitHub repo in few days and post the code there.
Comment: I am pretty sure we are both doing this for different reasons... What use do you have for such a tool /
Answer: This tool already exists. It shipped with early versions of the .NET framework. It's called "SoapSuds."
https://support.microsoft.com/en-us/kb/323491


Problem with apt

Question: When I run the apt-get upgrade command.

So I follow the step and run apt-get -f install

If I remove libc-2.17.so from '/lib/i386-linux-gnu' as the instruction says, my sudo command stops working
sudo dpkg --configure -a also doesn't work.
Answer: try to reinstall libc6 by:

apt-get install --reinstall libc6

Problem with apt


Creating Ethereums tokens and set up transaction fees

Question: Since creating a smart contract with Ethereum involves the user of ether, refilling all of the users' ethers becomes costly for a company. So let's say a company decide to issue a token over the ethereum network, and that token represents a new currency. Can the original creator of the token receive transaction fees everytime each user send tokens to someone else? That way the company could easily refill everyone's token's with ether.
Answer: You can't receive Ether paid for gas spent on that transaction, it all goes to the miner of current block.
But you can add support for that fee into your token contract. For example you can require to send some Ether with each token transfer, and then automatically send that Ether value into Token contract itself, or send to some other address.
Something like that:
<code>function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
    // accept fees
    if (msg.value < FEE) {
        return false;
    }
    if (!MYADDR.send(msg.value) {
        throw;
    }

    // do token transfer (WARNING, no validation here, don't use, it's for current example only)
    balances[_to]   += _value;
    balances[_from] -= _value;
    return true;
}
</code>
Comment: But what if the user of that token doesn't have enough ether? Can I require users to send a bigger amount of tokens for each token transfer? And just take a cut (in tokens, not ether) from each token transfer?
Comment: yes, sure. so instead of that fees lines of code, just add part of the `_value` to `balances[your system address]`
Answer: If you look at the problem as a whole, every user should spend some ether (as fees) to perform any transaction. If you are planning to fill the users accounts' with ether paid by users, the net sum is zero (looking at all users as an entity and company as another entity). So, either you have to fill the users accounts with ether from your pocket or Users have to burn their own pockets to make transactions (transfer tokens etc.)


Big-$O$ notation and constant values

Question: Function f(x) $n^3 2^n$  is:
a) $O(\ln n)$
b) $O(n^{3 + n})$
c) $O(2^n)$
d) $O (n^3)$
e) None of the above
Definition:
$f(x)$ is $O(g(x))$ as $x \rightarrow \infty$ if there are positive real constants $C$ and $x_0$ such that $f(x) \leq C g(x)$ for all values of $x \geq x_0$.
Choice b) $O(n^{3 + n})$ seems correct, but how is constant C and $x_0$ values chosen. If constant $C$ was large , choice c) $O(2^n)$  could also satisfy $f(x) \leq C g(x)$.
Comment: @avs:  you changed the original option b, which was $n^{3+n},$ to $n^3+n$.  These are very different and b is no longer correct.
Comment: Yes, option b is right, but you didn' t get the place in the text that was changed.
Comment: @RossMillikan edited back. I think now option $b)$ is right
Comment: b) is still incorrect: a polynomial is outgrown by an exponential.
Comment: @RossMillikan, you are right, I edited my answer accordingly.
Answer: No, a polynomial function, $n^k$, is outgrown by the exponential $2^n$.  This can be seen by using, say, L'Hopital's rule to compute the limit
$$
\lim_{x \rightarrow \infty}  {x^k \over 2^x}.
$$
The best (i.e., smallest in the order of growth) big-$O$ estimate for $f(n) = n^k 2^n$ is that function itself.  All options, except for b) and e), that you are given, grow slower than that, hence can't serve as the upper bound.
However, the function $g(n) = n^n$ does outgrow both exponentials and polynomials, and is present in b).  Hence, that's the right option.  Yes, it serves as a very crude upper bound, but it is the only upper bound among the options you are given.
For practical guidance, see section "Properties" in this article.
Answer: Your definition is not complete.  Formally, if $f \sim O(g)$, then
$$\lim_{x \rightarrow \infty} \frac{f(x)}{g(x)} = C \ne 0,$$
where $C < \infty$.
Option b) is certainly not correct.
Comment: The definition of big O in [Wikipedia](https://en.wikipedia.org/wiki/Big_O_notation) and elsewhere I have seen it does not impose $\neq 0$.  That is reserved for $\Theta$.
Comment: If the constant $C = 0$, then we might say that $f \sim o(g)$ (little 'o' notation).
Comment: Yes, that is true, but it is not excluded from big O.  We have $n \in O(n^2)$ for example.  It is also true that $n \in o(n^2)$ and not true that $n \in \Theta(n^2)$
Comment: I believe that is equivalent to your O definition with your $C$ somewhere in $[C_1,C_2]$
Comment: @RossMillikan, perhaps you could explain what is meant by $\Theta$?
Comment: @RossMillikan but in usual algorithm complexity, $n=o(n^2)\neq O(n^2)$
Comment: It is exactly what you are saying O is.  They are within a multiplicative constant of each other.  The family I have seen is [here](https://en.wikipedia.org/wiki/Big_O_notation#Family_of_Bachmann%E2%80%93Landau_notations).
Comment: @RossMillikan I think $f=\Theta(g)$ if $\exists C_1,C_2:C_1g\le f\le C_2g$
Answer: Option c is not correct.  If you claim $n^32^n \in O(2^n)$ I will ask you to state what values $x_0$ and $C$ have.  Then I just have to find an $n \gt x_0$ where it fails, which means that $n^3 \gt C$.  Clearly I can choose $n$ large enough to do that.

Big-$O$ notation and constant values


My dachshund turnt into a golden retriever?

Question: On another website I am posting pictures of nintendogs + cats and someone said my dachshund my dachund where it was a gold retriever
I asked them and showed them a picture of a golden retriever from the game but they said judging from the snout it looked like a golden retriever
So I went here to ask if there is something wrong with my game becouse the info says she is a dachund but she looks like a golden retriever
Is this a little graphic or a model glitch or is it a lot worse
Answer: As far as I can tell, your Nintendogs(&Cats) Dachshund is indeed a Dachshund.
Looking up some wiki articles on the game's Dachshunds and Golden Retrievers, your's is definitely not a retriever. It looks to be a Red, Yellow, or Golden coloured Dachshund. For some more direct comparrisons:

Your Dachshund
A real Dachshund with similar fur colour to yours
Another Nintendogs&Cats Dachshund (black & tan fur)
A Golden Retriever
A real Golden Retriever
Another Nintendogs&Cats Golden Retriever.

It is a little difficult to determine based on the snout - the model the game uses for the Dachshunds is a little less pronounced than some real life ones posses, but it is additionally difficult based on the angle of the screenshot you provided. Still, yours does look like the snout of the real life Dachshund.
The ears of your dog more closely match that of a Dachshound. While on the bottom row we can see that both the virtual and real Golden Retrievers have similarly shorter ears that do not match the shape of your dog's.
The legs may also be a key identifying feature; those of your dog appear slightly shorter than those of the retrievers on the bottom row. Again, however, it is a bit difficult to tell leg lengths based on the angle of the screenshot provided.


plyr parallel error-handling and warnings

Question: This is a common construction I use for error-handling:
x <- tryCatch(foo(), error=function(e){
    warning(e)
    NULL})

I run foo against lots of data objects, some of which might fail for whatever reason, if so I want the result to be NULL so that my entire run doesn't stop, but I also want to have the warning so I can see what failed and why.
I often run these from plyr, like this, and let's suppose some of them fail:
x <- llply(1:4, .fun=function(i) {
    result<-tryCatch({
        if(i %% 2==0) stop(i)
        i}, error=function(e) {
           warning(e)
           NULL})
    result})
 x

Result:
 Warning messages:
 1: In doTryCatch(return(expr), name, parentenv, handler) : 2
 2: In doTryCatch(return(expr), name, parentenv, handler) : 4

 > x
 [[1]]
 [1] 1

 [[2]]
 NULL

 [[3]]
 [1] 3

 [[4]]
 NULL

However suppose I turn on parallel computing with the same code.
 require(doParallel)
 registerDoParallel(cores=4)
 x <- llply(1:4, .parallel=TRUE, .fun=function(i) {
      result<-tryCatch({
          if(i %% 2==0) stop(i)
          i}, error=function(e) {
              warning(e)
              NULL})
      result})

  Result:
  Error in do.ply(i) : task 2 failed - "2"

The job fails on an error in any of the tasks and no result is constructed.  warning(e) was somehow converted to an error. I can get around this by commenting out warning(e) and then I get the desired result of NULLs in my data structure when there was an error, but then I lose the information about what happened.
In fact, I don't know any good way to throw warnings from parallel plyr.  They seem to be squelched.  If that's a limitation as a consequence of parallelism, that makes sense.  But I think the warnings becoming errors behaviour is weird and I'd like to understand what's going on here.
Answer: It appears to me that there is something wrong with the warning function when it is called with a simpleError object. It seems to work fine:
> warning(simpleError(1))
Warning message:
1

but oddly enough, the warning is treated as an error when called inside tryCatch:
> tryCatch({
+   warning(simpleError(1))
+ }, error=function(e) {
+   cat('caught an error\n')
+   print(class(e))
+   print(e)
+ })
caught an error
[1] "simpleError" "error"       "condition"
<simpleError: 1>

Since the foreach package evaluates the body of the loop in tryCatch, it thinks that an error has occurred. For example:
> library(foreach)
> foreach(i=1:4) %do% warning(simpleError(1))
Error in warning(simpleError(1)) : task 1 failed - "1"

That means that passing the .errorhandling='pass' option to foreach via the .paropts option should prevent the error from aborting llply:
> x <- llply(1:4, .parallel=TRUE, .paropts=list(.errorhandling='pass'),
+       .fun=function(i) {
+       result<-tryCatch({
+           if(i %% 2==0) stop(i)
+           i}, error=function(e) {
+               warning(e)
+               NULL})
+       result})
> x
[[1]]
[1] 1

[[2]]
<simpleError in doTryCatch(return(expr), name, parentenv, handler): 2>

[[3]]
[1] 3

[[4]]
<simpleError in doTryCatch(return(expr), name, parentenv, handler): 4>

It looks like you can fix this problem by changing the class of the simpleError object to a simpleWarning before calling warning:
x <- llply(1:4, .parallel=TRUE,
      .fun=function(i) {
      result<-tryCatch({
          if(i %% 2==0) stop(i)
          i}, error=function(e) {
              class(e) <- class(simpleWarning(''))
              warning(e)
              NULL})
      result})

If you want to get the warnings when running sequentially or in parallel, you could convert the error objects into warning objects and return them with the other results. For example:
x <- llply(1:4, .parallel=TRUE, .fun=function(i) {
         result<-tryCatch({
             if(i %% 2==0) stop(i)
             i}, error=function(e) {
                class(e) <- class(simpleWarning(''))
                e})
         result})

for (i in seq_along(x)) {
    if (inherits(x[[i]], 'simpleWarning')) {
        warning(x[[i]])
        x[i] <- list(NULL)
    }
}


Find $k\in\Bbb R$ if $\lim_{x\to0}\frac{1-\cos(kx)}{x^2}=\int_0^\infty xe^{-x}\,\mathrm dx$

Question: Find $k\in\Bbb R$ if $$\lim_{x\to0}\frac{1-\cos(kx)}{x^2}=\int_0^\infty xe^{-x}\,\mathrm dx.$$

$$\lim_{x\to0}\frac{1-\cos(kx)}{x^2}=\lim_{x\to0}\frac{k\sin(kx)}{2x}=\lim_{x\to0}\frac{k^2}{2}\frac{\sin(kx)}{kx}=\frac{k^2}2.$$ To find $\int_0^\infty xe^{-x}\,\mathrm dx$ we can add a limit: $$\lim_{b\to\infty}\int_0^bxe^{-x}\,\mathrm dx.$$ Now we can integrate by parts. Thus $u=x$, so $u'=1$, and $\mathrm dv=e^{-x}$, so $v=-e^{-x}$, thus $$\int xe^{-x}\,\mathrm dx=uv-\int u'v\,\mathrm dx=-xe^{-x}+\int e^{-x}\,\mathrm dx=-xe^{-x}-e^{-x}=-e^{-x}(x+1),$$ hence $$\lim_{b\to\infty}\left[-e^{-x}(x+1)\right]_0^b=-\lim_{b\to\infty}(e^{-b}(b+1)-1)=-(0-1)=1.$$ Hence, $$\frac{k^2}2=1\implies\boxed{k=\sqrt2\vee k=-\sqrt2}.$$ Is it correct?
Thanks!!
Comment: Looks good to me!
Comment: We have $1-\cos(kx)=\frac{k^2x^2}{2}+o(x^2)$, so the limit on the left is $k^2/2$, without further ado.
Answer: Yes, this is correct. You could vary certain details. For example, $1-\cos kx=2\sin^2\frac{kx}{2}$ would let you evaluate the left-hand side without any calculus, if you know the famous geometric result $\frac{\sin x}{x}\sim 1$.


Configuring a Maven plugin twice in a pom.xml

Question: I am working on a large Maven Java project that contains suites of TestNG automated tests and also suites of Cucumber automated tests. I realise that this is not ideal, but the different test suites were written by different sub-teams at different stages of the project. Going forward we intend to split this project out into smaller projects, but for now we are stuck with this mix.
The surefire plugin can be used to run these tests from Maven, but the plugin needs to be configured differently for each in our pom.xml.
For Cucumber, we are using it in conjunction with cucumber-jvm-parallel-plugin and it is configured like this:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20.1</version>
            <configuration>
                <forkCount>${threads}</forkCount>
                <reuseForks>true</reuseForks>
                <includes>
                    <include>**/Parallel*IT.class</include>
                </includes>
            </configuration>
        </plugin>

For our TestNG tests, it is configured like this:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20.1</version>
            <configuration>
                <suiteXmlFiles>${file}</suiteXmlFiles>
                <skipTests>false</skipTests>
                <properties>
                    <property>
                        <name>suitethreadpoolsize</name>
                        <value>${threads}</value>
                    </property>
                </properties>
            </configuration>
        </plugin>

We are not Maven experts and so, at the moment, we simply comment out the version of the plugin that we do not want to use for the suite we are running. Obviously this is cumbersome and not best practice, so I would be very grateful for any advice as to how we should address this. Can we legitimately define the plugin twice in the pom.xml and somehow pass a flag to indicate which version should be run? Many thanks for reading my question.
Comment: Integrations tests should be done using maven-failsafe-plugin...which has a default naming schema...
Answer: Use maven profiles to select the proper configuration:
add this snippet:
<profiles>
    <profile>
        <id>Cucumber</id>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <forkCount>${threads}</forkCount>
                    <reuseForks>true</reuseForks>
                    <includes>
                        <include>**/Parallel*IT.class</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </profile>
    <profile>
        <id>TestNG</id>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <suiteXmlFiles>${file}</suiteXmlFiles>
                    <properties>
                        <property>
                            <name>suitethreadpoolsize</name>
                            <value>${threads}</value>
                        </property>
                    </properties>
                </configuration>
            </plugin>
        </plugins>
    </profile>
</profiles>

and change this
<plugins>
  <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.20.1</version>
    </plugin>

</plugins>

you have to pecify the desired profile at the command line:
   mvn test -P Cucumber
   mvn test -P TestNG

bit you can also run both at once:
mvn test -P Cucumber -P TestNG
mvn test -P Cucumber,TestNG

Comment: Also you can add many profile for your tests(cuke and TestNG) as well e.g. smoke, full etc.
Comment: I made the changes suggested above and my tests are now working as desired. I very much appreciate the answer. Thank you.
Answer: Create a downstream maven project for each set of tests you want to run. More work up front but it pays off pretty quickly.
Comment: Yes, good answer - thank you. This will be the long term plan. In the short term, I implemented the suggestions in the other answer and they worked great.
Comment: Great you found a solution that works for you. I found that profiles makes it harder to make reproducible builds. That may or may not be relevant to you.


I checked this box: VMWare workstation console tools into system path. Now Chrome and Firefox don't work; it says proxy server is refusing connections

Question: I use Windows 10 Pro and I installed VMWare workstation 16.0.0 to use Ubuntu. I did an update for VMWare and I checked this box:

VMWare workstation console tools into system path

Now, Google Chrome and Firefox don't work; it says something about the proxy server is refusing connections.
I would like to undo all the changes and I don't know how.
Answer: You just have to disable the VM network adapter in

Network and Sharing -> Adapter Settings

This should fix it. But if you plan to connect the VM machine instance to the Internet; this will not work. May be you should clarify the error by providing the error message. I hope this solves your problem regarding the browsers.


overlapping of buttons in android

Question: I have two buttons in my XML file
<Button
    android:id="@+id/button1"
    android:layout_width="60dp"
    android:layout_height="65dp"
    android:layout_alignBottom="@+id/img"
    android:layout_alignParentRight="true"
    android:background="@android:color/transparent" />

<Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="65dp"
    android:layout_alignBottom="@+id/img"
    android:layout_alignParentRight="true"
    android:background="@android:color/transparent" />

Now in my java code I want to enable 1st button and disable second on basis of some logic and some times vice-versa.
I have tried -
button1.setenabled(true);
button2.setenabled(false);

But in this case both the buttons are disabled as button1 mathces the parent and once it is disables teh button under it also gets disabled.
Please help how to handle such case.
Comment: Show how you defined buttons. Make shure you didn't do something like this: button1 = (Button)findViewById(R.id.button1); button2 = (Button)findViewById(R.id.button1); - same id.
Comment: That is ok I alreday checked..   button1 = (Button)findViewById(R.id.button1); button2 = (Button)findViewById(R.id.button2)
Comment: from `XML` file it is look like that both buttons are on each other, at same position? Atm you are able to see only `button1` ? And no text on buttons and no background ?
Comment: @PankajKushwaha update your question every time when you want to add new information so you will get more answers.. btw you should post some java code for buttons in question so we can see where you going wrong?
Comment: @RDC : button1.setenabled(true);
button2.setenabled(false); This is the only relevant java code which I used and anyhow I have got the resolution that I have to bring the button to font using bringtofront()
Answer: Disabling the top view does not let touch event pass to views beneath it. You will have to try some thing else to get this.
Can you please explain what exactly you are trying to achieve here?
Answer: Thanks a lot guys for your time. I found a solution.
I was disabling a button based on some conditions and enabling the other, but they were overlapping and the button on below of view was also getting disabled when i disabled the button on top of view, even though button on below was enabled.
I used-
button1.bringToFront();

And it is working fine now.
Thanks Chitranshu Asthana.. your answer hinted me

overlapping of buttons in android


Android. How to use symbol code in TextView?

Question: I am using custom font to show weather conditions (sunny, rain, snow ...). I am referencing typeface from assets/fonts folder.
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Climacons.ttf");
TextView tvTest = (TextView)findViewById(R.id.tvTest);
tvTest.setTypeface(myTypeface);
tvTest.setText(getString(R.string.clear_day));

clear_day string contains code for 'sun' symbol.
<string name="clear_day">\e028</string>

I have taken this code from its CSS:
Pseudo ::before element
.climacon.sun:before {
  content: "\e028";
}

But TextView is showing other symbols

So my question is how to show symbol in TextView using its code?
Comment: in `\e028` maybe `\ ` makes error
Answer: I use this:
 //function
 private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
 public static Typeface getFace(Context c, String assetPath) {
    synchronized (cache) {
        if (!cache.containsKey(assetPath)) {
            try {
                Typeface t = Typeface.createFromAsset(c.getAssets(),
                        assetPath);
                cache.put(assetPath, t);
            } catch (Exception e) {
                Log.e(TAG, "Could not get typeface '" + assetPath
                        + "' because " + e.getMessage());
                return null;
            }
        }
        return cache.get(assetPath);
    }
}

//where you use
yourView.setTypeface(getFace(getActivity().getApplicationContext(),"counterfont.ttf"));

Put *.ttf inside assets folder(assets is not in res folder!)
Then put your icon string inside yourView xml, in my case "i" is mail icon:
<TextView
          ...
          android:text="i"
          ...
           />

Comment: I know how to show symbol using character 'a', 'b', 'c'... Yes this is easy way. How I am going to know which character which symbol? In that case I should check all characters to find my symbol?
Comment: @JoeRichard noo, you should know from where you get it. I created .ttf myself , and it says which character is which symbol. Try: http://fontello.com/ , 3rd tab says which symbol  is which character, yu can edit character too


Show $\frac{(2n)!}{n!\cdot 2^n}$ is an integer for $n$ greater than or equal to $0$

Question:
Show $$\frac{(2n)!}{n!\cdot 2^n}$$ is an integer for $n$ greater than or equal to $0$.

Could anyone please help me with this proving? Thanks!
Answer: You can see that $n! \cdot 2^n$ is exactly $\prod_{i=1}^n 2i$.
Then any of these (even) number appears in the numerator $(2n)! = \prod_{j=1}^{2n}j$.
Then the division is an integer. It is exactly $\prod_{i=1}^n (2i-1)$.
Answer: There are $mn$ people ($m,n$ are nonnegative integers).  We want to put them into $n$ groups, each consisting of $m$ people.  Let $N$ be the number of ways to do so.  If we label the groups, say, groups $1$, $2$, $\ldots$, $n$, there are $n!$ ways for the labeling.  Hence, there are $n!\cdot N$ ways to put $mn$ people into $n$ labeled groups.
Now, from $mn$ people, we can choose in $\binom{mn}{m}$ ways $m$ persons and put them into group $1$.  For $k=2,3,\ldots,n$, we can place $m$ persons from the remaining $mn-m(k-1)$ people into group $k$ in $\binom{mn-m(k-1)}{m}$ ways.  Therefore, we can perform this task (with labeled groups) in $\binom{mn}{m}\binom{mn-m}{m}\binom{mn-2m}{m}\cdots\binom{2m}{m}\binom{m}{m}=\frac{(mn)!}{(m!)^n}$ ways.
That is, $n!\cdot N=\frac{(mn)!}{(m!)^n}$.  Ergo, $\frac{(mn)!}{(m!)^nn!}=N$ is an integer.  Your question is a particular case where $m=2$.
In parallel to Laurent's and mathlove's arguments, we shall also prove that $\frac{(mn)!}{(m!)^nn!}=N=\prod_{k=1}^n\binom{mk-1}{m-1}$.  Consider again $mn$ people which will be placed into $n$ (unlabeled) groups, each having $m$ members.  Pick a person.  He has to be in a group.  Therefore, this group needs $m-1$ other members which can be chosen from the remaining $mn-1$ people in $\binom{mn-1}{m-1}$ ways.  For $k=2,3,\ldots,n$, we already have $k-1$ groups, and so we pick one person from $mn-m(k-1)$ people.  Put this person into a group, and choose $m-1$ people to be in the same group from the remaining pool of $mn-m(k-1)-1$ people in $\binom{mn-m(k-1)-1}{m-1}$ ways.  This shows $N=\binom{mn-1}{m-1}\binom{mn-n-1}{m-1}\cdots\binom{2m-3}{m-1}\binom{m-1}{m-1}=\prod_{k=1}^n\binom{mk-1}{m-1}$.  When $k=2$, we retrieve Laurent's formula: $\frac{(2n)!}{2^nn!}=\prod_{k=1}^n(2k-1)$.
Answer: Induction works.
For inductive step:
$$\frac{(2n+2)!}{(n+1)!\cdot 2^{n+1}}=\frac{(2n)!}{n!\cdot 2^n}\cdot\frac{(2n+1)(2n+2)}{(n+1)\cdot 2}=\frac{(2n)!}{n!\cdot 2^n}\cdot(2n+1)$$
Comment: The 2n + 1 from the inductive step gives me an integer. But how can I show (n+1) (n+2) ...( 2n) when divided by 2^n gives an integer ?
Comment: @GuoJinLong: This is induction. We suppose that $\frac{(2n)!}{n!\cdot 2^n}$ is an integer. Then, we know that $\frac{(2n+2)!}{(n+1)!\cdot 2^{n+1}}$ is also an integer.
Answer: The simplest way is to prove by induction as already shown in another answer. Another way to see why it's an integer is that this is exactly the unique number ways you can pair up all the vertices in a complete graph (also called matching). The number of ways of doing something can't be anything apart from a positive integer.


Android save activity dynamically created layout in onPause

Question: So I'd like to save temporarily my Activity layout. My layout is created in a LinearLayout, by adding children like ll.addView(btn);
But when I go to another Intent, and that Intent finishes, all the added buttons disappear. How can I prevent this?
Comment: Despite all the answers here, you should check, why your activity is recreated.
Comment: why do u want to do like this ?
Comment: Data are received from a service. When user selects data -> activity displaying them -> back to data selection
Comment: @JacksOnF1re it is not recreated. It's just paused, and it's state is lost
Answer: You will have to implement onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle).
In onSaveInstanceState you store the information needed to create the views dynamically in the bundle.
In onRestoreInstanceState you get this information from the bundle and recreate the dynamic layout.
Something like:
@Override
public void onSaveInstanceState(Bundle bundle) {
  bundle.putString("key", "value"); // use the appropriate 'put' method
  // store as much info as you need
  super.onSaveInstanceState(bundle);
}

@Override
public void onRestoreInstanceState(Bundle bundle) {
  super.onRestoreInstanceState(bundle);
  bundle.getString("key"); // again, use the appropriate 'get' method.
  // get your stuff
  // add views dynamically
}

Alternatively, you can restore your layout's dynamic views from the onCreate method instead of the onRestoreInstanceState method. You decide what's best for you.
Comment: From the same page **Instead of restoring the state during `onCreate()` you may choose to implement `onRestoreInstanceState()`, *which the system calls after the `onStart()` method***. The logic will break if someone implements `onStart()` which initializes some state variables.
Comment: `onCreate` is not an alternative for `onRestoreInstanceState`.
Comment: @BirendraSingh It is. From the docs: "Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information." https://developer.android.com/guide/components/activities/activity-lifecycle.html#saras
Comment: If activity is paused then `onCreate()` is not going to help.
Comment: @BirendraSingh So? It is still an alternative. Whether it's the best way to do it will depend on the case in question. Sometimes, restoring the instance state in `onCreate()` is a way to avoid redundant code. If `onCreate` wasn't meant to be used to restore the instance state, this possibility would never exist in the framework, specially if you consider that `onCreate(Bundle)` and `onRestoreInstanceState` were both available since API Level 1. Again, choosing `onCreate` or `onRestoreInstanceState` to restore data will depend on the situation.
Comment: and the title of the question explicitly contains the word `onPause`. Finally I don't agree as per my definition of **Alternative.**
Comment: @BirendraSingh Besides, if the Activity is just paused, then there is no need to save or restore the instance state. If `restoreInstanceState` is called, it means the Activity was destroyed, thus, `onCreate` will also be called.
Comment: @BirendraSingh Well, you can have your opinion, but the docs agree with me. "Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here (referring to onRestoreInstaceState)". Which means that yes, onCreate is an alternative. I rest my case. https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)
Answer: You can make use of onSaveInstanceState to save the view and
onRestoreInstanceState to retrieve the saved view.

private String someVarB;

...

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putString("btn_added", "true");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    someVarB = savedInstanceState.getString("btn_added");

    if(someVarB.equalsIgnoreCase(true))
    {
         ll.addView(btn);
    }

}

Answer: To prevent an Activity's contents from always updating each time you call it by using Intent() action, go to the Manifest file and add a tag to the activity named `android:launchMode="singleTask".
Here is an example
<activity
        android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TranscluscentBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

Comment: This will create another launcher for the activity, as far as I know
Comment: No, I copied this snippet from my project where launch mode is used on my MainActivity (Which is also the launcher activity). All I'm explaining is the android:launchMode="singleTask"


Spark/Arc observing while connecting battery to charge controller

Question: I have the solar system as shown in below diagram. When I connect my battery terminals to the MPPT charge controller, I am observing an arc immediately and due to which I am afraid to connect. Does this arc/spark is expected, is this because of some capacitor present inside the MPPT charge controller?
Also I have doubt on ratings of panel, charge controller and battery too.
Comment: I'm voting to close this question because it isn't about home improvement.
Comment: Hello, and welcome to Home Improvement. You should contact the manufacturer(s) about this; there's no way we'd know. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know you'll know the details of contributing here.
Answer: Because you're doing it with the power on.
That is to say, during daytime.  The arc should go away if you turn off the solar panel.   Either throw a tarp over it or wait til night.
Also, try to get out of the inverter business.
Try to arrange things so your loads run directly off 12V instead of off the inverter.  The worst sin I see is people running cell phone chargers off inverters.  Every gas station, big-box and 7-11 sells cell phone chargers that run on 12 volts.
Certain loads like a refrigerator need to be on inverter. But try to find a way to spin up the inverter only when needed. An ideal setup would be to spin up the inverter hourly, and then have it shut itself down when current draw stops (after the fridge has cycled and quit).
Ratings
As far as quality ratings, that's on you. You can choose to buy quality stuff or save money, and you endure the result of that.   I can tell you "cheap Chinese" isn't anymore; they now charge retail prices as high as 95% of the genuine/quality units. Paying a lot is no longer an assurance of quality.
As far as sizing the system (how big solar vs how big battery vs loads), that is the usual place people go wrong, because they have not bothered to learn the concepts.
It takes some time. Hang out on off-grid solar power forums and such. (SE isn't the right forum; we don't field nearly enough questions about off-grid). You'll get exposed to a lot, such as "don't use more than 1/3 of a lead-acid battery's capacity", what a watt-hour is, how much common loads take (modern refrigerator: 1000 watt-hours per day), how to size solar panels to allow for winter and cloudy days, battery versus your expected draw, etc.
Comment: Not clear form the question that the panels are connected at all, yet. But it's still utterly normal to get a spark when connecting a battery (MPPT controllers are charge pumps/switching supplies and do indeed have capacitors looking to get charged.) Likewise any UPS I've ever connected a battery to tends to spark unless you precharge with a resistor.
Answer: Utterly normal.
If you want to avoid it you could attach a resistor in series for a minute before connecting directly.
By the way, most UPSes are terrible .vs. a "real" inverter, IME - since you appear to be attempting to use a UPS as an inverter.


Sending an image and text together to other peers through MultipeerConnectivity

Question: I am using Apple MultipeerConnectivity framework and I am able to send the message to all the peers connected to it.
I am using:
- (BOOL)sendData:(NSData *)data toPeers:(NSArray *)peerIDs withMode:(MCSessionSendDataMode)mode error:(NSError **)error;

I am even able to send the image by converting it in NSData.
Problem is I am trying to send image and text together to other peers. I know there are three ways to send information to other peers:
1. NSData
2. Resource
3. Stream
So for sending an image and text together which method we should use and how?
Thanks
Answer: You could use NSData for your task. Here is example:
Serialization to NSData:
NSString *string = @"Any String";
UIImage *image = [UIImage imageNamed:@"Any Image"];
NSData *imageData = UIImagePNGRepresentation(image);
NSDictionary *dictionary = @{@"string":string, @"imageData":imageData};
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
// Send |data| by MultipeerConnectivity

Deserialization to NSString and UIImage:
// Receive |data| by MultipeerConnectivity
NSDictionary *dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSString *string = dictionary[@"string"];
NSData *imageData = dictionary[@"imageData"];
UIImage *image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];

Comment: Thanks i was also doing the same. Just found out here. http://stackoverflow.com/questions/5513075/how-can-i-convert-nsdictionary-to-nsdata-and-vice-versa


Converting digits from string into words

Question: The goal of this assignment for my cs class is to search a string for digits and change them to the written form
ex: 4 -> four
It's a relatively simple task.  I have two problems however:
1) due to my current code if I convert a string of just "8" and try and make it "eight", it won't work because it's longer than the current length of the string.
2) dealing with more than one number char in a row through the string.  I have it somewhat figured out.  If you run what I have with certain Strings it works.  We're supposed to separate more than one number char with a hyphen.
Here is my code:
public class NumberConversion {

    /**
     * * Class Constants **
     */
    /**
     * * Class Variables **
     */

    /* No class variables are needed due to the applet not having a state.
     All it does is simply convert. */
    /**
     * * Class Arrays **
     */
    char numberChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    String numbers[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

    /**
     * * Accessor Methods **
     */
    /**
     * * Transformer/Mutator Methods **
     */
    public void writeNumber(String phrase) {
        /**
         * Local Variables *
         */
        String newPhrase = "";
        int j = 0;
        int k = 0;

        phrase = phrase.trim();

        /**
         * * Counts through the length of phrase **
         */
        for (int i = 0; i < phrase.length(); i++) {
            /**
             * * If the current char is a number char, enter the next repitition
             * structure **
             */
            int l = i + 1;

            if (isNumber(phrase.charAt(i)) && isNumber(phrase.charAt(i + 1))) {
                boolean searchArray = true;

                do {
                    if (numberChar[ j] == phrase.charAt(i)) {
                        searchArray = false;
                    }

                    j++;

                } while (searchArray && j < numberChar.length);

                phrase = phrase.replace(Character.toString(phrase.charAt(i)), numbers[ j - 1] + "-"); //error HERE

            }

            if (isNumber(phrase.charAt(i))) {
                boolean searchArray = true;

                do {
                    /**
                     * * Counts through numberChar array to see which char was
                     * found in the phrase. Stops when found **
                     */
                    if (numberChar[ k] == phrase.charAt(i)) {
                        searchArray = false;
                    }

                    k++;

                } while (searchArray && k <= numberChar.length);

                /**
                 * * Changes char to string and replaces it with the matching
                 * String numbers array element **
                 */
                phrase = phrase.replace(Character.toString(phrase.charAt(i)), numbers[ k - 1]);
            }
            phrase = phrase.replace("- ", " ");
        }
        System.out.println(phrase); // Prints the changed phrase.
    }

    /**
     * * Helper Methods **
     */
    /**
     * * Observer Methods **
     */
    public boolean isNumber(char input) {
        boolean isNumber = false; // Initially fails

        for (int i = 0; i < numberChar.length; i++) {
            /**
             * * If input matches a number char, method returns true **
             */
            if (input == numberChar[ i]) {
                isNumber = true;
            }
        }
        return isNumber;
    }
}

Comment: please add examples your code worked for and examples where it failed and how it failed...
Comment: @acdcjunior : The language is Java.
Comment: @Lion: Okay. When the OP stated "The goal of this assignment for my **cs** class", he led me into thinking it was C#. `System.out.println` gives it away, though.
Comment: What are the inputs that work and what are the inputs that don't work? And what are the errors or wrong outputs you get?
Comment: if there is a number `34` how do you want to print it like `ThreeFour` or `Three Four`
Comment: @Arun P Johny - It has to be made into three-four.
Comment: @ Anthony Shwartz - What I listed as #1 above is one error.  It gives me a stringindexoutofbounds for that particular situation.
Answer: Do not replace numbers in the current string, create a new string, and keep appending to it. You can then avoid a lot of unnecessary validation.
    List<Char> myNumberChar = Arrays.asList(numberChar);
    List<Char> myNumbers = Arrays.asList(numbers);
    StringBuilder mySB = new StringBuilder();
    //String myResultString = ""; // If you don't want to use StringBuilder
    for (int i = 0; i < phrase.length(); i++) {
        mySB.append(myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-");
        //myResultString = myResultString + myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-"; //Again, for no StringBuilder case
    }
    String myResult = mySB.toString();
    // No need to do the above in no StringBuilder case, just use myResultString in place of myResult
    System.out.println(myResult.subString(0, myResult.length - 1)); // removed the last hyphen

Comment: Thanks I'm going to try both of these.  I really don't know why I didn't think of the first.
Comment: Actually, is there a simpler way of doing what I did without list using StringBuilder? I won't be allowed to use them due to them not being covered yet in class.
Comment: You can do something like `myResultString = myResultString + myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-";` with `myResultString` initialized to "", but that is too inefficient. String operations are costly.
Comment: I can see why StringBuilder would help in this case though.  The index error is coming from the fact I'm changing the string into something longer than the length.  If I understand what I read right on oracle's site that using the setLength() method and setting it to a high number should get me around that problem.
Comment: I'm getting really weird output using StringBuilder under my current structure.  I'm honestly stumped.  In your opinion( or anyone else that reads this ), is my entire structure bad?  I feel like that may be part of the problem.  I honestly feel no closer to getting what I need after looking at it at least 2 hours the last 3 days.
Answer: I would use String.replace
for(int i = 0; i < 10; i++) {
   str = str.replace(numberChar[i] + "", numbers[i]);
}

Comment: Don't you mean `replaceAll()`. Also, you missed the hyphen.
Comment: Yeah and I already had replace in there to begin with almost that exact same way anyways.
Answer:     public class NumberConversion

{
/*** Class Variables ***/

/* No class variables are needed due to the applet not having a state.
   All it does is simply convert. */

/*** Class Arrays ***/

char numberChar[] = { '0' , '1' , '2' , '3' , '4' ,
                         '5' , '6' , '7' , '8' , '9' };
String numberWord[] = { "zero" , "one" , "two" , "three" , "four" ,
                        "five" , "six" , "seven" , "eight" , "nine" };
/*** Transformer/Mutator Methods ***/

public String writeNumber( String phrase )
   {
        /** Local Variables **/
  phrase = phrase.trim();

  /*** Counts through the length of phrase ***/

    for ( int i = 0; i < phrase.length(); i++ )
    {

     /*** If current char is a number, count through the array
          that contains the number chars until the one needed is
          found. ***/

        if ( isNumber( phrase.charAt( i ) ) )
        {
            boolean keepSearching = true;

            int j = 0;

            do
            {
               if ( numberChar[ j ] == phrase.charAt( i ) )
                  keepSearching = false;

               else
                  j++; // Increments j if char doesn't match array element

            } while ( keepSearching && j < numberChar.length );

            /*** Replaces the current char with the corresponding String
                 word from the other number array.  ***/

            phrase = phrase.replace( Character.toString(
                                      phrase.charAt( i ) ) ,
                                      numberWord[ j ] + "-" );
    }
    }

    /*** Gets rid of dashes from unwanted places ***/

    phrase = phrase.replaceAll( "- " , " " );
    phrase = phrase.replaceAll( "-," , ", " );
    phrase = phrase.replace( "-." , "." );

    if ( phrase.charAt( phrase.length() - 1 ) == '-' )
       phrase = phrase.substring( 0 , phrase.length() - 1 );

  return phrase;
}

/*** Observer Methods ***/

public boolean isNumber( char input )
   {
        boolean isNumber = false; // Initially fails
    for ( int i = 0; i < numberChar.length; i++ )
    {
        /*** If input matches a number char, method returns true ***/

        if ( input == numberChar[ i ] )
           isNumber = true;
    }

    return isNumber;
}

Comment: Don't know why some of it didn't indent in to the code but whatever.  Anyways I figured it out.  Some minor details were changed to get what I needed after restructuring the selection statement and making one do instead of two.


Does "Install this third-party software" add the proprietary Nvidia driver or only Codecs?

Question: I'm installing Ubuntu on a Dell Latitude E6520 with an Optimus configuration.
I'd like to not install the NVIDIA proprietary drivers, but I would like to get all codecs possible. However, I'm not sure what the "Install third-party software" option in the installer does.
Will I get just the codecs, or will I get drivers too?
Comment: It has nothing to do with Nvidia drivers. Those are available in the main repository but are never installed automatically.
Answer: The "Install this third-party software" option in the Ubuntu installer installs a group of frequently used media codecs, but it does not install all possible codecs, for example codecs which are rarely used. The "Install this third-party software" option in the Ubuntu installer also does not install proprietary graphics drivers such as the proprietary Nvidia graphics driver. Open source graphics drivers are built-in by default in Ubuntu.
The proprietary Nvidia graphics driver can be installed in Ubuntu using the built-in Additional Drivers utility or from the terminal with the following commands:
sudo ubuntu-drivers install
sudo reboot

The ubuntu-drivers install command installs drivers that are appropriate for automatic installation including their dependencies, and the Nvidia driver will also be updated automatically when an update is available.
When installing a proprietary graphics driver, it is not necessary to uninstall the open source graphics driver. The two graphics drivers can be installed alongside each other allowing the open source graphics driver to be used as a fallback alternative in case there is a problem using the proprietary graphics driver.
Answer: Third Party software in Ubuntu enables an extra repository that allow you to download closed source softwares. By example, Nvidia doesn't provide the source code of their drivers, this is why you need to activate this third-party software repository. Third party means that Ubuntu is not responsible of the content as the binaries are build by third party users (like Nvidia).
Comment: it doesn't answer my question at all :)

Does “Install this third-party software” add the proprietary Nvidia driver or only Codecs?


issue while installing pod by command line

Question: I am using pods first time in the project . I created a new project and followed following process :

Downloaded master from the github ,as terminal asked me to do it manually
fired : pod init method . This command generated  Podfile in my Xcode project folder
Then I added a line in the pod file : pod 'Alamofire', '2.0.2'

4 . Then I fired pod install command and I am getting following error in the terminal window :
Setting up CocoaPods master repo
[!] Unable to add a source with url `https://github.com/CocoaPods/Specs.git` named `master-1`.
You can try adding it manually in `~/.cocoapods/repos` or via `pod repo add`.

I am following this tutorial :
https://www.raywenderlich.com/97014/use-cocoapods-with-swift
Please suggest workaround for this issue.
following is my pod file :
platform :ios, "8.0"
 use_frameworks!
target 'PodsTest' do
  # Uncomment this line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

  # Pods for PodsTest
  pod 'Alamofire', '2.0.2'
  target 'PodsTestTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'PodsTestUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

Comment: step-4 should be pod install command
Comment: yeah , thats by mistake , I edited my question
Comment: how you have mentioned the pod command for Alamofire in Pod file? Can you tell me that? @V-Xtreme
Comment: Can you tell me you xcode version?
Comment: @EktaMakadiya: Version 8.0
Comment: Try following steps from Github : https://github.com/Alamofire/Alamofire#installation
Comment: In you pod file mention the code like this.

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'Alamofire', '2.0.2'
Comment: checked this ? http://stackoverflow.com/questions/38222229/alamofire-not-working-swift-xcode-8
Comment: Its not working for AFNetwork also : target 'PodsTest' do
   pod 'AFNetworking', '~> 3.0'
end
Comment: see this https://github.com/CocoaPods/CocoaPods/issues/4293
Comment: @V-Xtreme Kindly find my answer and respond.
Answer: In you pod file mention the code like this.
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'Alamofire', '2.0.2'

and then try pod install
Comment: I am using the same. For me it is working. Or try 2.0.0 instead of 2.0.2. Also try without target 'PodTests' do @V-Xtreme
Answer: You just need to update repo
Run pod repo update on terminal.
Try to use latest Alamofire => pod 'Alamofire', '~> 4.0'
Hope it will help you.
Answer: Are your Command Line Tools set up correctly according to the Xcode version you are using?
In Terminal:
sudo xcode-select -r
And then in XCode:
Xcode -> Preferences -> Locations -> Command Line Tools
worthwhile checking, this might cause the problem


SQL: Where should the Primary Key be defined

Question: I'm creating a database with several sql files
1 file creates the tables.
1 file adds constraints.
1 file drops constraints.
The primary is a constraint however I've been told by someone to define your primary key in the table definition but not given a reason why.
Is it better to define the primary key as a constraint that can be added and dropped or is it better to do it in the table definition.
My current thinking is to do it in the table definition because doing it as a removable constraint could potentially lead to some horrible issues with duplicate keys.
But dropping constraints could lead to serious issues anyway so it is expected that if someone did drop the primary key, they would have taken appropriate steps to avoid problems as they should have for any other data entry
Comment: We generally script each object and all associated constraints, indexes etc in one script per table and save that script in source control. It drops existing objects and then recreates then at the end.  For later versions, we might have an alter table script instead that applies only to the change for that version.
Answer: A primary key is a constraint, but a constraint is not necessarily a primary key. Short of doing some major database surgery, there should never be a need to drop a primary key, ever.
Defining the primary key along with the table is good practice - if you separate the table and the key definition, that opens the window to the key definition getting lost or forgotten. Given that any decent database design utterly depends on consistent keys, you don't ever want to have even the slightest chance that your primary keys aren't functioning properly.
Comment: You may need to drop or alter keys as your design evolves during initial development or to support changes to business requirements. I would put each key constraints in it's own script. Some database change management tools also insist on having separate scripts per object.
Answer: From a maintainability perspective I would say that it is better to have the Primary Key in the table definition as it is a very good indicator of what the table will most likely be used for.
The other constraints are important as well though and your argument holds.
Answer: For effective source control it usually makes sense to have a separate script for each object (constraints included). That way you can track changes to each object individually.
Answer: All of this is somewhat platform specific, but a primary key is a logical concept, whereas a constraint (or unique index, or whatever) is a physical thing that implements the logical concept of "primary key".
That's another reason to argue for putting it with the table itself - it's logical home - rather than the constraints file.
Answer: There's a certain logical sense in keeping everything related to a table in one file--column definitions, keys, indexes, triggers, etc. If you never have to rebuild a very large database from SQL, that will work fine almost all the time. The few times it doesn't work well probably aren't worth changing the process of keeping all the related things together in one file.
But if you have to rebuild a very large database, or if you need to move a database onto a different server for testing, or if you just want to fiddle around with things, it makes sense to split things up. In PostgreSQL, we break things up like this. All these files are under version control.

All CREATE DOMAIN statements in one file.
Each CREATE TABLE statement in a separate file. That file includes all constraints except FOREIGN KEY constraints, expressed as ALTER TABLE statements. (More about this in a bit.)
Each table's FOREIGN KEY constraints in a separate file.
Each table's indexes for non-key columns in a separate file.
Each table's triggers in a separate file. (If a table has three triggers, all three go in one file.)
Each table's data in a separate file. (Only for tables loaded before bringing the database online.)
Each table's rules in a separate file.
Each function in a separate file. (Functions are PostgreSQL's equivalent to stored procedures.)

Without foreign key constraints, we can load tables in any order. After the tables are loaded, we can run a single script to rebuild all the foreign keys. The makefile takes care of bundling the right individual files together. (Since they're separate files, we can run them individually if we want to.)
Tables load faster if they don't have constraints. I said we put each CREATE TABLE statement in a separate file. The file includes all constraints except FOREIGN KEY constraints, expressed as ALTER TABLE statements. You can use the streaming editor sed to split those files into two pieces. One piece has the column definitions; the other piece has all the 'ALTER TABLE ADD CONSTRAINT' statements.  The makefile takes care of splitting the source files and bundling them together--all the table definitions in one SQL file, and all the ALTER TABLE statements in another.  Then we can run a single script to create all the tables, load the tables, then run a single script to rebuild all the constraints.
make is your friend.