How to install Ubuntu 12.04 within Windows 7 with a CD image of ubuntu (without use of an external CD/USB)?

Question: The wubi installer that comes with Ubuntu 12.04 doesn't allow one to install ubuntu within windows. I downloaded the Wubi installer available here Ubuntu Windows Installer
This howerver doesnt allow me to install with the existing image that I downloaded earlier. It downloads ubuntu afresh prior to installing.
Is there a way to install it with the existing CD image and WITHOUT use of an external CD/DVD (too lazy to buy one :P)
I used to be able to do this with the earlier versions of Ubuntu just by mounting the CD image as a drive in windows... and the installation would complete in minutes!
Comment: There is absolutely no reason to mount the CD image. Wubi.exe - when run from a CD (or mounted CD image) - no longer supports the 'Install inside Windows' option. Unless you supply `--force-wubi` as a command line option. All you need to do is place wubi.exe in the same folder as the desktop CD ISO before running wubi. If it starts to download a new ISO then there is something wrong with your one - check the log file for details (in the `%TEMP%` folder, called `wubi-12.04-revxxx.log`
Answer: The procedure from bcbc's comment works perfectly:

There is absolutely no reason to mount the CD image. Wubi.exe - when
  run from a CD (or mounted CD image) - no longer supports the 'Install
  inside Windows' option. Unless you supply --force-wubi as a command
  line option. All you need to do is place wubi.exe in the same folder
  as the desktop CD ISO before running wubi. If it starts to download a
  new ISO then there is something wrong with your one - check the log
  file for details (in the %TEMP% folder, called wubi-12.04-revxxx.log –
  bcbc Jun 1 at 17:50
Answer:
Go to http://www.slysoft.com/en/virtual-clonedrive.html Download and install.
Then go to the iso that you downloaded.
Right click and click mount. Do not click anything on auto start.
Go to my computer.
Right click on the ubuntu install drive. Click open folder.
Then open the wubi install program. Proceed with installation.

Hope this helps,
Leinardo
Answer: You can still mount the image using any virtual CD software, like PowerISo, or Virtual CD, or Magic ISO and do that same thing.  You have to create a Virtual Cd Drive to be able to do that.
Answer: As told by Mitch you need to install a virtual cd software
Install DAEMON Tools Lite from here
Its a free version with no usage limit
It will help you create a virtual drive for you
Mount the iso you downloaded with the software. It will then autoplay
Then choose install inside windows as the install option.
Done. It will install Ubuntu as wubi.
Answer:
Extract the downloaded ISO image
copy and paste the ISO image into the extracted folder and then launch the Wubi installer.


jQuery Effect Overlaps With Delay + Inline-Block

Question: I'm having an issue with showing three inline divs through the slide effect in jQuery after a different delay for each div.
Without the different delay it works ok but with the delay, the divs overlap with eachother in the center of the wrapping div and then just magically show up as the three inline divs again (after the effect takes place). I don't know if its because my wrapper div isn't wide enough or not.
Here is my jQuery code:
$(document).ready(function () {
    $('#left-service').hide();
    $('#middle-service').hide();
    $('#right-service').hide();

    $('#left-service').delay(500).show('slide', {
        direction: 'up'
    }, 1000);
    $('#middle-service').delay(1000).show('slide', {
        direction: 'up'
    }, 1000);
    $('#right-service').delay(1500).show('slide', {
        direction: 'up'
    }, 1000);
});

Essentially what it does is it the #left-service slides first in the middle of the wrapper, then the #middle-service slides in the middle of the wrapper pushing the #left-service left, then the #right-service wrapper slides in the middle and moves to the right side.
Here is the fiddle
Comment: Can you share jsfiddle or codpen demo?
Comment: Sorry, just did it. It's in the original question.
Comment: You can see how they overlap before each sliding individually. I was thinking would it be better for this purpose to put the divs inside a table instead of keeping them inline?
Answer: Adding float: left to all three will solve the issue.
Here is the demo
You can remove display: inline-block for all three div's
CSS
#middleside, #rightside, #leftside {
    float: left;
}


How to remove HTML from CSV Export in wordpress?

Question: I am creating a plugin in wordpress and i am trying to export data from array, it works. but the problem is with the output it print HTML also.
So please help me to get rid of this problem.
Here is my PHP code that i try
public function export_data()
{
        ob_start();
        $filename = "export_data" . rand(1, 100) . ".csv";
        $export_data = $this->order_detail_items();
        ob_end_flush();

        $output = fopen("php://output", 'w') or die("Can't open php://output");
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Description: File Transfer');
        header('Content-type: text/csv');
        header("Content-Disposition: attachment; filename={$filename}");
        header('Expires: 0');
        header('Pragma: public');
        fputcsv($output, array('Store Name', 'Product name', 'Sell Quantity', 'Date', '(£) Total Price'));

        foreach ($export_data as $key => $data) {
            fputcsv($output, $data);
        }

        fclose($output);

        die();
}

Any solution appreciated!
Comment: Can you show us sample of html ?
Comment: @ttrasn sure, i will show you, Please check the updated post
Comment: actually i didnt found `html` on your `csv`. can you tell me where is it? or can you take image ?
Comment: @ttrasn please check, now you can see the image
Answer: First of all I see java script tags in your result.
you can remove this tags by :
 $html = preg_replace('##is', '', $html);

And you can remove your html tags with strip_tags function.
$html = strip_tags($html);

At the end. you can change your code to:
foreach ($export_data as $key => $data) {
    $data = preg_replace('##is', '', $data);
    $data = strip_tags($data);
    fputcsv($output, $data);
}

Comment: But there is whole page html, start from `` to ``, how can i rid of this?
Comment: @RobinSingh You can remove tags with `strip_tags` function in php. which i used it in my answer


Is there any built-in in method in spring to write an empty/null check method?

Question: I wrote this code, and I was wondering if there was a built-in method from spring that does the same thing as this method.
public static String map(String value) {
    return value != null && value.isEmpty() ? null : value;
}

I found ObjectUtil, but it didn't have any method that has the same functionality.
I would appreciate any suggestion!
Comment: As @Stultuske said there is nothing wrong by writing your own utils.
You could also do `Optional.ofNullable(value).filter(String::isEmpty).orElse(null)` to achieve the same result. Or you can directly use the Optional result to handle the upcoming `if (result != null)` block by using it's is/ifPresent() method.
Comment: There's nothing wrong in creating your own util methods (if you do so in a reusable way). After all, you might have to rework that logic sooner or later, and then it would not be the same as the logic by the built in method anymore. I would, however, recommend a better name for the method
Comment: It will be difficult to find this functionality off-the-shelf as mostly the requirement is the other way around (return "" for empty String or null). But as Stultuske said, it is perfectly ok to write a small utility by oneself.
Answer: Looking at your code seems you just map the empty string to null instead of avoiding it at all.
public static String map(String value) {
    return value != null && value.isEmpty() ? null : value;
}

If value is null it return value so null, if it's empty it returns null again.
If your intent  is to avoid null values, you should introduce the NullObject pattern.
On java 8+ use the Optional as it is the same, but natively supported by the language.
As already shown in comments by Jan Schumacher, it helps you to easely filter the value further.
With your function you still need a null check, but using Optional you don't need it anymore and the code is much clearer.
You can even use the @NotNull annotation in the method signature, to help enforce null values to be propagated when not expected.


What are the benefits of the different Jobs in Forsaken World?

Question: I'm just getting into the game (and I'm already hooked). I am leveling a Protector on my own, and a Human Assassin with my wife's Priest. My wife will be leveling a Marksman on her own.
Can anyone provide a summary of each Job and what they allow you to do in the game, and how they might be beneficial to the classes we are playing?
Comment: I'm too lazy to actually extract the important information from this thread, so I won't be posting it as an answer (someone else is welcome to use it do so). However, it seems to have the information you want: http://www.mmorpg-tactics.com/forum/english-section/180-forsaken-world-jobs.html#180
Answer: Botanist

This job will help you acquire the neccesary items for other jobs like Alchemy or Cooking.
Collecting plants can help you make money

Alchemy
Alchemy will help you make potions that you can use to gain benefits:

Basic Health Potion – Recovers 1640 HP
Basic Mana Potion – Recovers 1370 MP
Sturdy Potion – Increases defence by 15 for 5 minutes
Valor Potion – Increases attack by 50 for 5 minutes
Earth Mastery Potion – Increases Mastery by 30 for 5 minutes
Light Mastery Potion- Increases Mastery by 30 for 5 minutes
Water Mastery Potion- Increases Mastery by 30 for 5 minutes
Wind Mastery Potion- Increases Mastery by 30 for 5 minutes
Dark Mastery Potion- Increases Mastery by 30 for 5 minutes
Physical Mastery Potion – Increase Physical Attack by 30 for 5 minutes.
Basic Health Supplement – Increases Max HP by 200 for 10 minutes
Basic Mana Supplement- Increases Max MP by 200 for 10 minutes
Health Supplement- Increases Max HP by 400
Mana Supplement- Increases Max MP by 400

Mining

Minerals/Gems are used by Artisans
Required for some quests

Merchant

Unlocks new items in the Mercury Trade Union
Gain reputation points

Chef

Create food/drink
Can boost Attack/Accuracy/Health/Recovery/etc.

Artisans

Create jewelry

Socialite

Special quests from Rio
New skills:

Cooperative Efficiency: Cooperative Socialites can read the Book of Co-opto gain   EXP.
Exchange for Benefits: Exchanges Social Contribution for EXP or Gold Coins.
Persuade: Use this skill in front of an NPC. Complete quests using this skill to increase your Kindness
Intimidate: Use this skill in front of an NPC. Complete quests using this skill to increase your Cruelty.

Some new daily quests

Adventurer

Some new skills

Demon Hunt: Effective against monsters who have been affected by Darkness. Each use consumes a Hunting Gem.
Observe: Use this skill to trigger the Observe effect. Observing certain places can give you valuable information.

Fishing

Allows you to catch fish (!)
Chance of getting secret treasure
Can open secret drift bottles
Can gather coral

Scavenger

Break down gear into materials used by weaponsmiths/armorsmiths
Make recharger shards which increase max durability

Tamer

Make money by selling pets

Armorsmith

Create armor (!!)

Weaponsmith

Create Weapons (!!)

Extracted from here


How I can disprove this $-x\neq x \implies x^2\neq x^2$ with $x$ is a positive real number?

Question: let $x$ be a positive real number , Really am not familiar with mathematical logic as well ? I came accrosse this proposition :$-x\neq x \implies x^2\neq x^2$ in my mind which i can't disprove it , Any idea ?
Comment: disproof by counterexample is fully allowed in mathematical logic.
Comment: Not sure what you have in mind.  A single counterexample, say $x=1$ is all you need.
Comment: Hint:  What does "$=$" mean?
Answer: Easy: Take any positive $x$. Then $-x \not = x$, but $x^2 = x^2$. So, the antecedent is true, and the consequent false, and hence the statement is indeed false.
In fact, for a counterexample, you can just take any specific $x$, say $x=1$. Again, we have $-1 \not = 1$, but $1^2 = 1^2$.  So, $x=1$ is a counterexample to the claim that $-x\neq x \implies x^2\neq x^2$ for any positive real number $x$


How to dynamically set the height on just one header row in ag-grid for react

Question: This method sets the height
gridApi.setHeaderHeight(height);

But the problem is it sets height for both header groups.
 (Header group spans entire width)<------------------------- height gets set here

(Header1    | Header 2   | header 3)<------------------------ and height gets set here
------------------------------------
row data 1 | row data 2 | row data 3

How to set the height for just one header row
 (Header group spans entire width)

(Header1    | Header 2   | header 3)<------------------------ This row one only
------------------------------------
row data 1 | row data 2 | row data 3

See example: https://codesandbox.io/s/ag-grid-practice-forked-py43m?file=/src/index.tsx
Click Expand, and see both column header groups expand in height.
Answer: I think that this is impossible. The following methods can be used, but they set the height for the entire line in the header. I think this is a rather strange design decision to increase the header for only one of the columns.
gridApi.setHeaderHeight(value)
gridApi.setGroupHeaderHeight(value)

Comment: I looked at your example, you are right, it really is. Then I went to the official site of ag grid and checked it out there. It doesn't work for them either. https://ag-grid.com/react-grid/column-headers/#dynamic-header-heights
setGroupHeaderHeight set height only for a group, but setHeaderHeight set height for a group and column header.
Comment: It's not a single column I want to set the height on. Its the row. The problem is if I use setHeaderHeight it sets the height on all header groups. Updated my question for clarity
Comment: Do you using this code for groups and the columns?

Comment: if so then try to use code from my previous answer. Create customHeaderGroupComponent. Then to change the height of the group use the method gridApi.setGroupHeaderHeight(value) and to change the height of the column header use the method gridApi.setHeaderHeight(value)
Comment: ok I've added an example - see - https://codesandbox.io/s/ag-grid-practice-forked-py43m?file=/src/index.tsx
Answer: ok I've come up with a solution to circumvent this.
Simpler version:

https://codesandbox.io/s/ag-grid-custom-setaddedcolheight-sypg2?file=/src/Grid/Columns.tsx

More dynamic version:

https://codesandbox.io/s/ag-grid-custom-setaddedcolheight-expand-reduce-mh8rw?file=/src/Grid/Columns.tsx


Should I use the adapter ring that came with my Schlage deadbolt?

Question: Could someone help me in understanding the purpose of this silver adapter ring? I have a 2 1/8" borehole, the manual only mentions its removal if you have a 1 1/2". Yet none of the YouTube tutorials I've viewed address this ring.
Additionally, I'm working with the Schlage Century trim plate. It doesn't seem aesthetically pleasing to position it between the deadbolt and the trim board as suggested by the menu, since it would result in a visible silver ring. The only way to achieve the looking from product page is to place it inside, between the door and the trim plate. I'm unclear about its function nor if this is the correct way to install it. Any insights would be greatly appreciated.
Thanks,
Chris
Comment: Can you tell me where you can see the silver ring after installation?  Does your lock cover the entire hole in the Century trim, or can you see the adapter ring through the hole in the trim?  It seems like your lock cylinder might not be compatible with the Century trim you have, since it requires an adapter for a 2⅛ bore hole.
Answer: The adapter ring is intended to go inside the door to keep the lock from moving around inside the door if the hole is larger than 2⅛".  Since your hole is only 2⅛" you don't need an adapter.
Comment: The adapter in the question photo is to do as you say if the bore _is_ 2-1/8". The one you point out is not what's in the question. It's an additional part, akin to the legacy ring I show in my answer.
Answer: For this door you'll use the adapter.
The adapter is for use with modern 2-1/8" bores. In decades past, deadbolt bores were smaller--the size of the cast cylinder we see inside the adapter. Schlage used to offer a stamped steel washer to expand the smaller deadbolt body to the larger bore. Now the deadbolt body is large, but accommodates both bore sizes with this adapter.
Modern (deadbolt body and latch plate roughly the same size):

Legacy (deadbolt body smaller than latch plate, adapter ring installed for modern 2-1/8" bores):

You're probably right that the adapter would go behind the Century trim, but I'm not as familiar with that part. It should be fairly obvious, though, whether you can use the adapter with that trim and whether it's needed for centering.


Logic in Unit Tests

Question: I have a unit test like so:
<code>    [Test]
    public void DataIn_NoOfRowsReached_CreatesSequentialData()
    {
        //Assert
        MyLogic logic = SetupLogic();
        logic.NoOfRows = 3;

        logic.DataIn(1, "1,4,7");
        logic.DataIn(2, "2,5,8");
        logic.DataIn(3, "3,6,9");

        CollectionAssert.AreEqual(new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9" }, logic.ExpectedValues);
    }
</code>
Each DataIn call adds the passed in data to a separate list depending on ID (1st param). When the NoOfRows number equals the DataIn input Id it merges the data to be sequential. I then test to check this.
I now want to use test cases but I cannot see any easy way to do this without putting if statements and various optional parameters in the test method. I don't really want to duplicate the tests for various scenarios.
The NoOfRows maximum is 6.
Comment: Which unit test framework are you using?
Comment: So to paraphrase... you want to create a generic method that will take input parameters and do this specific test with a multitude of inputs?
Answer: I believe this is what you are looking for.  Leverage the params keyword to allow passing in an arbitrary amount of strings.
<code>[Test]
public void DataIn_NoOfRowsReached_CreatesSequentialData()
{
    MyGenericTest("1,4,7", "2,5,8", "3,6,9");
}

private void MyGenericTest(params string[] inputs)
{
    //Assert
    MyLogic logic = SetupLogic();
    logic.NoOfRows = inputs.Length;

    List<string> allNumbers = new List<string>();
    for(int i = 0; i < inputs.Length; i++)
    {
       logic.DataIn(i + 1, inputs[i]);
       allNumbers.AddRange(inputs[i].Split(',');
    }

    allNumbers.Sort();
    CollectionAssert.AreEqual(allNumbers.Distinct(), logic.ExpectedValues);
}
</code>
This just does string sorting... if you have numbers that are bigger than 9, you'll want to add your own compare function to the Sort() method.
Comment: Yeah I did until you mentioned numbers greater than 9! Thanks
Comment: I assume casting all the strings as int then sorting them would work as well?
Comment: Yeah, using int.Parse, int.TryParse, or whatever your favorite conversion method is would work fine.  I kept it as strings because I assumed you probably wanted strings.
Answer: If you are using NUnit and want to run multiple test cases with different input, you could make use of the Values attribute, http://nunit.com/index.php?p=values&r=2.6 .
Your unit test could then look like this:
<code>[Test]
public void DataIn_NoOfRowsReached_CreatesSequentialData([Values(new[] { "1,4,7", "2,5,8", "3,6,9" }, ...)] string[] vals)
{
    //Assert
    MyLogic logic = SetupLogic();
    logic.NoOfRows = vals.Length;

    for (var i = 0; i < vals.Length; ++i)
      logic.DataIn(i + 1, vals[i]);

    CollectionAssert.AreEqual(new[] { "1", "2", "3", "4", "5", "6", "7", "8", "9" }, logic.ExpectedValues);
}
</code>
Comment: What is the difference between using Values and TestCases?
Comment: Had not considered this, thanks for the idea. It seems that using Values in combination with the Combinatorial attribute gives you the possibility to test all possible combinations if you have two or more variables. On the other hand, using the TestCase attribute gives you additional degrees of freedom, for example by allowing you to set ExpectedException for a specific test case. If you only want to run sequential test cases, TestCase might also make the code more readable. I might even stretch so far as to say that I recommend using the TestCase attribute for the unit test above :-)
Answer: If you want to write some "smart" tests, you probably can create the expected array with the numbers you enter as input and sort them, you can keep track of the numbers you enter as part of each row (use some numbers to create the string). Other than that I don't see too much improvement really.

Logic in Unit Tests


Where to put your patents/ patent pending info in software? And should you really do it?

Question: My softare company has a few patents/ patent pendings. Does it make sense to showcase this in our products?
If so, where should we put it? In our splash screen? In the Help Menu?
Answer: The information of any software usually resides as Meta data of the application in an About box. There you usually find information of current installed version, license agreements and sometimes patents / patents pending information. I would put this information as a link to your patents / patents pending page on your web site, if users want to read more.
Accessing an About box from the HELP-menu is implemented in some of the major web browsers (Internet Explorer, Firefox and Opera). Other web browsers (Chrome and Safari) lets you access the same About box from the settings menu. But the About box itself contains the same information.

If it's important that your users finds the patents / patents pending information, I see no reason not to link both from the SETTINGS menu and the HELP menu. Users have different mappings and preconceived meaning of how to reach the About box. Supporting both conventional ways to get there can only do well.


Saveable background image

Question: On my site, I use a full size background image. However, I'd like to give the user the ability to right click > Save As on the image. How could I accomplish this?
Comment: I don't think you can do that with a CSS background image. You could either have your own element with a low z-index to act as a background image or have a custom context menu, and maybe there's some other way as well
Comment: If you want to encourage that behavior, then give users an express link to 'download this background image.'
Answer: You cannot. Browsers will never present that option for a background image.
You would have to have a large element behind the rest of your content that has the image, with everything floated on top of it.
It's not a good idea, and you should avoid doing anything like this.

Saveable background image


Replace a line of text in a file, with the contents of another file

Question: I have two files, let's call them foo.py and fixed_rule_map. I need to:

find the line in foo.py that contains the pattern rule_map = . It would be enough to find the pattern rule_map, if that's easier, but since there are more than one line in foo.py which contains rule_map, in this case I need to match only the first occurrence.
substitute the line in foo.py with the contents of fix_rule_map_in_foo (which contains a single line of text).

For example, foo.py may look like this:
class example:
    """some useless text.

    """
    rule_map = {'greater': lambda x, y: x > y, 'less': lambda x, y: x < y}

    def __init__(self,
                rule=None,
                ):
        self._init_rule(rule)

    def _init_rule(self, rule):
        if rule not in self.rule_map and rule is not None:
            raise KeyError(f'rule must be greater, less or None, '
                           f'but got {rule}.')
        self.rule = rule
        if self.rule is not None:
            self.compare_func = self.rule_map[self.rule]

and I would like to correct it to this:
class example:
    """some useless text.

    """
    rule_map = {'greater': lambda x, y: (x if x is not None else -inf) > (y if y is not None else -inf), 'less': lambda x, y: (x if x is not None else -inf) < (y if y is not None else -inf)}

    def __init__(self,
                rule=None,
                ):
        self._init_rule(rule)

    def _init_rule(self, rule):
        if rule not in self.rule_map and rule is not None:
            raise KeyError(f'rule must be greater, less or None, '
                           f'but got {rule}.')
        self.rule = rule
        if self.rule is not None:
            self.compare_func = self.rule_map[self.rule]

thus fixed_rule_map would be a text file containing
    rule_map = {'greater': lambda x, y: (x if x is not None else -inf) > (y if y is not None else -inf), 'less': lambda x, y: (x if x is not None else -inf) < (y if y is not None else -inf)}

Note that since foo.py is a Python file, the substitution must preserve indentation.
The command that performs the substitution has to go in a Dockerfile, since the substitution must be performed when building the Docker image. Docker uses /bin/sh as an interpreter for RUN commands, rather than /bin/bash, which may be a problem if your solution uses bash. However, I think I could fix this by using a shell script fix_rule_map_in_foo.sh:
#! /bin/bash
FOO_PATH = /path/to/foo
<your_solution>

and adding this line in the Dockerfile:
RUN fix_rule_map_in_foo.sh

Comment: @Raffa sounds interesting. Can you write it as an answer and explain in detail the syntax of the command?
Comment: Something like this `awk -v fix="$(cat fix_rule_map_in_foo)" '/rule_map = / {$0 = fix}1' foo.py`
Answer: You can use the sed editor's r command to read the contents of a file and insert them, deleting the original matching line after:
sed -e '/rule_map = /{r fix_rule_map_in_foo' -e 'd;}' foo.py

The new contents will be written to standard output by default, but GNU sed supports an in-place editing flag (--in-place or -i).
Since this doesn't involve any shell constructs, I think you can run it directly (although I don't use docker, so don't know for sure):
RUN sed -i.bak -e '/rule_map = /{r fix_rule_map_in_foo' -e 'd;}' foo.py

however you can put it in a POSIX shell script if you prefer.
Alternatively, using the non-stream editor ed (this does use shell constructs, so must be in a script):
#!/bin/sh

printf '%s\n' '/rule_map = /r fix_rule_map_in_foo' '-1d' 'wq' | ed -s foo.py

Comment: why  `sed -i.bak`? Shoudn't the command be `sed -i`?
Comment: it looks like `sed` in my Docker image supports the `-i` option, so this should work.
Answer: You can set that single line contained in the file fix_rule_map_in_foo in a variable named e.g. fix with command substitution like so:
fix="$(cat fix_rule_map_in_foo)"

You can set the variable to a fixed string as well if you wish (instead of reading that string from a file) like so:
fix="The substitution string here"

Then pas that variable to awk so you can match the line and substitute it like so:
awk -v fix="$(cat fix_rule_map_in_foo)" '/rule_map = / {$0 = fix}1' foo.py

That will search for rule_map =  and replace the line that contains the match with the value of the variable fix and print all the lines(after modification) to the terminal ... you can redirect the output to a file if you wish with e.g. >.
If you wish to edit the file foo.py instead, then use the GNU awk like so:
gawk -i inplace -v fix="$(cat fix_rule_map_in_foo)" '/rule_map = / {$0 = fix}1' foo.py

Comment: @DeltaIV Not natively but you can ether use command substitution like `echo $(awk -v fix="$(cat fix_rule_map_in_foo)" '/rule_map = / {$0 = fix}1' foo.py) > foo.py`   or ...
Comment: Write to a temp file then rename it overwriting the original file `awk -v fix="$(cat fix_rule_map_in_foo)" '/rule_map = / {$0 = fix}1' foo.py > tmpfile && mv tmpfile foo.py` ...
Comment: That said some versions of `awk` do that so test first `awk -i inplace -v fix="$(cat fix_rule_map_in_foo)" '/rule_map = / {$0 = fix}1' foo.py` ... might work.
Comment: The Docker image I'm using doesn't have `gawk`, but only `awk`. Isn't it possible to edit the file `foo.py` using `awk`?
Comment: Also, I made some edits to the question. Could you please have a look? Thanks. It's important that the substitution preserves the indentation, since `foo.py` is a Python script and indentation matters.


How do I use a part of the matched text in regex for Sublime Text, in the replacement?

Question: If I have
width: 12px 0;
width: 24px 0;

how can I use regex to replace it with
width: 12px 0px;
width: 24px 0px;

While keeping the first number intact?
I am using Sublime Text that uses Python PCRE for regex. I tried searching Google and Bing and reading the Sublime Text documentation and I couldn't find anything helpful. Using :[0-9]*px 0; and :${m}px 0px; doesn't work.
Comment: I'm busy doing lots of personal projects at the moment that's taking weeks to complete. I'll try out your answer on wednesday.
Comment: Your answer works. I've given you the accepted answer. Thank you.
Comment: Did that work out?
Answer: You could use
(:\h*\d+px\h+\d+);

( Capture group 1

:\h*\d+px Match : optional spaces and 1+ digits followed by px
\h+\d+ Match 1+ spaces and 1+ digits

); Close group and match ;

And replace with the first group followed by px; like  $1px;
Regex demo

Without using a capture group, this could be another option using \K to forget what is matched so far, and replace with px;
:\h*\d+px\h+\d+\K;

Regex demo
Comment: If OP's data is as mentioned (but at risk of oversimplification) you could try: `(\d+);` replaced with `$1px;`, though not worth an answer =). Nice 1
Comment: I never used `\h` and `\K`. Does `\h` have different meanings on different regex implementations?
Comment: @qräbnö `\h` matches a horizontal whitespace character and `\K` resets the current match buffer. See these pages for the different engines that support them. http://www.rexegg.com/regex-quickstart.html#other and http://www.rexegg.com/regex-quickstart.html#whitespace
Comment: Thx. `\h` can also mean hexadecimal digit shorthand on other engines.


Why is Ubuntu 12.04 taking very long to start and run programs?

Question: I have a Toshiba laptop with 2.8 gb of ram, 1.87x2 GHz processor, and Ubuntu 12.04 64 bit on it as a partition installed with wubi. It takes 5-10 mins to start up, and opening any program (such as Chromium, Chrome, Skype, Firefox, Thundermail, etc) takes over half a minute. I stopped using Unity because my graphic card couldn't handle it and swapped over to Cinnamon. It's a little better, but everything is still really really slow.
Any suggestions/solutions?
Comment: Sounds like the file system is too fragmented. How much space have you allocated to Ubuntu? What about the Windows partition, is it fragmented?
Answer: Your Windows host drive may be fragmented. Wubi stores its data within one file on the Windows filesystem, so you can trying to use the defrag utility to defrag the wubi drive.
Hold the windows key and press R, and then type dfrg.msc into the text box and click [OK]. Then, select the drive Wubi is installed on(try the C: drive then all the other internal drives if unsure), and choose to Defragment it. Let it finish, and try booting into Wubi again.


convert stdClass object with XML data to array in PHP

Question: Given this object:
<code>stdClass Object (
    [customerdata] => <TPSession userid="22" CustomerId="123456"LoginId="123456"/><TPSession userid="26" CustomerId="1234567"LoginId="1234567" />
)
</code>
How can I convert this XML data to an array using PHP?
Comment: what should the array look like?
Answer: Simply cast it to array:
<code>$arr = (array) $obj;
</code>
Comment: Useful but isn't the solution for original question.
Answer: Xml data in the question is not valid.

It has no root element
CustomerId="1234567"LoginId="1234567" breaks xml parsing

You need to wrap it into root element , resolve attribute issue, than you can use simple xml parser to generate object that can be converted to array.
Example
<code>$o = new stdClass ();
$o->customerdata = '<TPSession userid="22" CustomerId="123456"LoginId="123456" /><TPSession userid="26" CustomerId="1234567"LoginId="1234567" />';
function wrap($xml) {
    return sprintf ( '<x>%s</x>', $xml );
}
function fix($xml) {
    return str_ireplace ( '"LoginId', "\" LoginId", $xml );
}

$xml = wrap ( fix ( $o->customerdata ) );
$sx = new SimpleXMLElement ( $xml );
$sx = ( array ) $sx;
$sx = $sx ['TPSession'];
foreach ( $sx as $row ) {
    var_dump ( ( array ) $row );
}
</code>
Answer: If I understand you want to convert the string contained into the object element to an array, in other words, convert an xml string to an array.
This is what you looking for...
http://php.net/manual/en/function.simplexml-load-string.php
Follow the example on this page.


Xorg has high CPU load after unlocking XFCE

Question: I am running Xubuntu 20.04 with a NVIDIA GeForce GTX 760 and an AMD Ryzen 7 CPU.
The Nvidia driver version is 450.66, the kernel is 5.4.0-47-generic
Starting up without previous hibernation works fine, no excessive CPU load. Invoking hibernation works fine, no error entries whatsoever, resuming is fast and without any problems (checked dmesg and journalctl).
After logging in from lightdm top  shows a CPU load of 100% of Xorg. The high CPU load persists for up to 5 Minutes, on one core mostly.
I've read some similar threads (e.g. the XModmap bug), checked the xfce4 config files for empty values, but found nothing.
So any idea where to look would be appreciated.
Edit
Seems to be a bug in XFCE
Answer: The culprit is described here
When executing xmodmap ~/.Xmodmap which happens on "unlock" (so the question title is basically wrong) the CPU of Xorg, Firefox and Thunderbird is going up.


Nested C array pointer types

Question: This seems like a question that should have been answered already somewhere but I can't seem to find something satisfactory. Anyway I need to return from a function something that looks like:
{ {"foo", "bar"}, {"baz", "foo"}, {"foo", "bar"} }

I am familiar with the use of argv and I understand what its types means but for some reason I can't get the type of the above expression correct. There will always be 2 string literals on the innermost part and as such I thought something like either
char **s[2] or char *(*s[2])

should be what I am after but for some reason I constantly end up with a segfault no matter the permutation I try when I attempt to iterate through and use printf. Also the compiler is constantly complaining about incompatible pointer types, excess elements and too many braces. This is the current code:
 char *(*s[2]) = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };

Answer: You are close.
#include <stdio.h>

int main()
{

    char* s[][2] = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };

    for( int i = 0; i < 3; i++ )
    {
        for(int j = 0; j < 2; j ++)
        {
            printf("%s ",s[i][j]);
        }
    }

}

The above prints: foo bar baz spam eggs ham
Comment: `char* s[][2]` says "I want an array of `s[][2]`'s". `s[][2]` says, I want a character array of any length (the `[]`) in sets of 2 (the `[2]`). What you have written. `char **s[2]` says I want a 2d array of `s[2]`'s or I want a pointer to a 1d array of `s[2]`'s (depending on how you fill it).
Comment: Can you explain the difference? I know pointers aren't the same as arrays but I think I might not have fully grasped the differences. Thanks so much.
Comment: @0x69 That is awesome! And I thought we had to fend for ourselves in C declaration land...
Answer: It's simple
char *s[3][2] ={ {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };

A little explanation :
char *s ; //   |s| ---> "Only one char array or string"
                          ______
char *s[] ; //  |s| ---> |_s[0]_|--> 1st pointer to char array --> "1st string"
                         |_s[1]_|--> 2nd pointer to char array --> "2nd string"
                         |_s[2]_|--> 3rd pointer to char array --> "3rd string"

                          ___                                __
char *s[][] ;// |s| ---> |___|--> 1st pointer to pointer -->|__|-->"1st string"
                                                            |__|-->"2nd string"
                         ____                                __
                         |___|--> 2nd pointer to pointer -->|__|-->"1st string"
                                                            |__|-->"2nd string"
                         ____                                __
                         |___|--> 3rd pointer to pointer -->|__|-->"1st string"
                                                            |__|-->"2nd string"

Comment: i understand that this works but what i don't get is how this differs from char **s[]. why does that fail while yours works?
Comment: char **s[] is an array of pointers to pointers to char. here it's one dimensional array of of char ** pointers , but char*[][] is a 2-D array of char*
Answer: char *s[][2] = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };

cout<<s[1][0];

would print baz
Comment: @dreamriver Has nothing to do with RO memory. Also it dynamic allocation would work.

Nested C array pointer types


How soon after starting is StreetPass available?

Question: How far into Bravely Default do I have to go to activate StreetPass in the game?
Answer: Just after the first cave (which is the tutorial too), you'll get Agnes's Pendant, which allows you to use StreetPass. It will let you send or receive friends or guest attacks.
So, about 1 hour of game time if you start a new game, search everywhere, and read all dialogue.
If you skip everything, 30 minutes should be enough.
Comment: Ok, then. For initial StreetPassing then I should just use the demo, go home, play the demo one last time, import my game, and then start up a new game in the retail version. Man I hope they do a midnight release.
Comment: Midnight release?
Comment: @DrakaSAN: Bravely Default hasn't been released in the Americas yet. I'm guessing CyberSkull is in that region, and wants a midnight release with plenty of other people around (for more StreetPasses).
Comment: @MichaelMadsen: Wow, That must be the first time a game is launched in Europe before US XD
Comment: @DrakaSAN: Layton 6 was earlier still, and there have been several other titles like that (not to mention Europe gets physical releases of a few games that are eShop-only in US, e.g. Senran Kagura Burst). The inverse does still happen though (e.g. Etrian Odyssey IV came out much later in Europe than US), and we do still miss out completely on some titles (Rune Factory 4! ;_;), but the situation is generally much, much better than it was just a few years ago.
Comment: From what I'm told there weren't enough pre-orders for a midnight release in my area.


is there any way to monitor secret rotation failed in aws secret manager?

Question: I want to create a cloud watch alarm to monitor secrets rotation and triggers if RotationFailed.
I have checked the aws documentation about RotationFailed. This document says,
<code>RotationFailed event - a mechanism to inform you that secret rotation failed for an application.
</code>
but I cant find how to use RotationFailed event to trigger alarm. please help me to create metric filter and alarm for secret rotation failed.
Comment: I need to create a  cw alarm using terraform
Answer: Try this cloudwatch event
<code>{
  "source": [
    "aws.secretsmanager"
  ],
  "detail-type": [
    "AWS API Call via CloudTrail"
  ],
  "detail": {
    "eventSource": [
      "secretsmanager.amazonaws.com"
    ],
    "eventName": [
      "RotationFailed"
    ]
  }
}
</code>
Comment: but in cloud trail I dont see any event name called RotationFailed. I will try and update here.
Comment: do you have any idea how to create alarm with this event using terraform file
Comment: Refer to the documentation: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_rule


"Damage screen" remains always

Question: My Screen is always like this, even when just standing for long time:
Answer: Try using a bandage or medkit to heal your self.  I suspect you are under the impression that you heal automatically in this game.  This is not true.
Open the weapon/item wheel and select the medkit/bandage.  With it equipped, use the item like you would a grenade.  If you don't have any, you can find them by searching bodies, or searching around the map.

"Damage screen" remains always


Ansible - Using an encrypted string as variable

Question: I'm trying to use an encrypted password for the credential of SVN.
Unfortunately I get an error.
My task:
- name: Export subversion directory to folder
  vars:
    svn_pass: !vault |
            $ANSIBLE_VAULT;1.1;AES256
            61366435663930323762326534376237329939319321939999373334616364343865333830333435
            6338646239363735376431633863333632363135383963390a636664353535663366336263626264
            39616366333132316531653461646365393332386365366264613931383165366235343238336463
            3438336335613838380a393037613636396564326465396132613162326335313932626135666333
            3630
  subversion:
    repo: svn://myserver/trunk
    dest: /tmp/svn
    username: svnuser
    password: {{ svn_pass }}
  become: true

The error I get:

The offending line appears to be:
username: ****

password: {{ svn_pass }}

           ^ here

We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:

  - {{ foo }}

Should be written as:
with_items:

  - "{{ foo }}"

Answer: As the error message says, you forgot the quotes
password: "{{ svn_pass }}"


How to delete specific number of nodes from firebase realtime database

Question: I have an app which has a structure like
Chatrooms--------
Messages-------
Chatroomid---------
-Message1
-Message2
In this chatroom when the number of messages reaches 200 I want to delete the first 50 messages.So if the messages are 200 it will delete the messages from message1 to message50.I am using a push key for the messages.
My java code for sending message
send.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {

              Map<String,Object> message = new HashMap<>();
              message.put("message",messageBox.getText().toString());
              message.put("imageurl",ppurl);
              message.put("sender",FirebaseAuth.getInstance().getCurrentUser().getUid());

              reference2.push().setValue(message).addOnSuccessListener(new OnSuccessListener<Void>() {
                  @Override
                  public void onSuccess(Void aVoid) {

                      messageBox.setText("");

                  }
              }).addOnFailureListener(new OnFailureListener() {
                  @Override
                  public void onFailure(@NonNull Exception e) {

                      Toast.makeText(chatroom.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();

                  }
              });

          }
      });

My java code for retrieving message

    private void getdata() {
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    for (DataSnapshot npsnapshot : snapshot.getChildren()) {

                        message l = npsnapshot.getValue(message.class);
                        list.add(l);
                    }

                    messageAdapter.notifyDataSetChanged();
                }else {

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

    }

Answer: You can easily add this in your existing getdata function:
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        if (snapshot.exists()) {
            if (snapshot.getChildrenCount() > 200) {
                int count = 0;
                Map<String, Object> updates = new HashMap<>();
                for (DataSnapshot npsnapshot : snapshot.getChildren()) {
                    if (count++ <= 50) {
                        updates.put(npsnapshot.getKey(), null);
                    }
                }
                ref.updateChildren(updates); // this will refire onDataChange, so we'll update the UI then
            }
            else {
                for (DataSnapshot npsnapshot : snapshot.getChildren()) {
                    message l = npsnapshot.getValue(message.class);
                    list.add(l);
                }

                messageAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException(); // don't ignore errors
    }
});

There is also a Cloud Functions sample that can do this server-side for you btw: https://github.com/firebase/functions-samples/tree/master/limit-children


Resolution compatible - HTML

Question: I have this problem with my navigation menu in which when I change my screen resolution, the menu gets all messed up. This is my code in jsfiddle: http://jsfiddle.net/qh5u47t2/. Help would be greatly appreciated. Thanks.

These are the main HTML codes for my menu and the CSS is:
.navigation {
    float: right;
    margin: 0 auto;
}

ul.menu {
    margin: 0 0 0 0;
    padding: 0;
    position: absolute;
    top: 65%;
    left: 20%;
    list-style: none;
}

Comment: You have 2 solutions, learn `media-queries` or just use a framework like `Bootstrap` it will take care of that for you.
Answer: I've tried re-sizing your JSfiddle, and it seems to me that your code is not responsive in a way that if not enough 'space' is allocated on the top window (viewable area), it will not reflow the content to show it all.
The Bootstrap Grid system will assist you getting the work done, including dealing with various screen resolutions right out of the box.
In my experience it is well worth learning.
A few links to get you started: http://getbootstrap.com/css/#grid (The Grid System)
You can see some templates here: http://getbootstrap.com/getting-started/#examples
Hope it helps

Resolution compatible - HTML


Error while installing Rhythmbox Mozilla Plugin

Question: I am trying to install Rhythmbox Mozilla PLugin via Synaptic. But I am getting the following error:
rhythmbox-mozilla:
  Depends: rhythmbox (=3.4.2-1ubuntu1~ubuntu18.04) but 3.4.2-4ubuntu1 is to be installed

The command:
apt-cache policy rhythmbox-mozilla

gives the prompt:
rhythmbox-mozilla:
  Installed: (none)
  Candidate: 3.4.2-1ubuntu1~ubuntu18.04
  Version table:
     3.4.2-1ubuntu1~ubuntu18.04 500
        500 http://ppa.launchpad.net/ubuntuhandbook1/apps/ubuntu bionic/main amd64 Packages

Comment: There is [no official package for 18.04 LTS](https://packages.ubuntu.com/search?suite=all&section=all&arch=any&keywords=rhythmbox-mozilla&searchon=names). Please add output of `apt-cache policy rhythmbox-mozilla` to the question.
Comment: updated my question
Answer: We have two problems here:

ppa:ubuntuhandbook1/apps PPA does not respect current version of rhythmbox package from official repository (so it won't install);
Even if we install rhythmbox-mozilla package with some hacks, it will not work with modern Firefox 53+ Quantum (see quote from latest package Changelog):

rhythmbox 3.4.2-4ubuntu1 source package in Ubuntu
Changelog
rhythmbox (3.4.2-4ubuntu1) bionic; urgency=medium
  ...
  * Stop building rhythmbox-plugin-mozilla since it won't work in Firefox 53+

But if you need to play video in your browser, then you can install Mozilla SeaMonkey all-in-one internet application suite and use it with VLC-plugin:
cat <<EOF | sudo tee /etc/apt/sources.list.d/mozilla.list
deb http://downloads.sourceforge.net/project/ubuntuzilla/mozilla/apt all main
EOF

sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 2667CA5C
sudo apt-get update
sudo apt-get install browser-plugin-vlc seamonkey-mozilla-build

I view RTSP streams this way on Ubuntu 16.04 LTS.


Is any RDP client can be used in Ubuntu 14.04 that can access Windows Server 2012?

Question: I want to access Windows Server 2012 from Ubuntu 14.04 through RDP, but I can't find a software that can be used to access Win2012. There uesed to be a software called Remmina, it can connect to Win2012, however it just show white screen all the time. So can anyone give me a client can be used to access to Windows Server 2012?
Answer: I solved it by reinstalling the latest version of Remmina.


using OAuth client to access Netflix and Facebook APIs

Question: I coded a small Java program that handles Facebook's API from server to server, it was very simple especially when getting the code parameter from Facebook (on the callback URL). I only had to use HttpClient (I used apache commons).
Now I am trying to develop a client to use Netflix API, but for some reason I need to use some OAuth client (rather than just HttpClient and overloading the parameters such as AppID and secret).
I have to say I am a bit confused and I am not sure why there is such a difference.
I must say that I am not super familiar with OAuth and maybe it is a result of the different protocol versions (1.0a and 2.0) but I would appreciate it if anyone could help me with this.
Answer: I ended up creating the signature and oauth calls by hand, using these gems:
<code>require 'cgi'
require "base64"
require "hmac-sha1"
require 'net/http'
</code>
for details on constructing the call, see my answer here:
Generating oauth_signature for Netflix


UPDATE with join referencing same table - Redshift SQL

Question: Assume I have a table named tab. Tab has a field called "version". Version is sequential.
In Redshift, I would like to update rows in Tab with the value from a previous row. Please tell me how to do this. Essentially:
UPDATE tab
    SET tab.fieldA = tabPrior.fieldA
    FROM tab tabPrior
    WHERE tab.version = tabPrior.version + 1;

I would love to use a JOIN, but this does not seem to work in Redshift.
Comment: I would expect your code to work.
Comment: Please report the error from such an update query.
Comment: A `FROM` in an `UPDATE` is effectively the same as a `JOIN`. By the way, `UPDATE` statements in Amazon Redshift are quite inefficient because previous versions of a row are marked as deleted and new rows are added to the end of the storage space. Run a `VACUUM` afterwards to reclaim disk space and make the table more efficient for querying.
Comment: Have you tried the code you gave an example? If so and this didn't work, what was the error?
Comment: Possible duplicate of [Update table based on self table lookup in redshift](https://stackoverflow.com/questions/46769936/update-table-based-on-self-table-lookup-in-redshift)
Comment: this is a duplicate question, I've referenced you to the original answer
Answer: To Update with a JOIN statement you are better off writing it in a subquery.
UPDATE table
SET
 col1 = TT.col1
 col2 = TT.col2
FROM (SELECT T1.id, T1.col1, T2.col2
     FROM T1
     JOIN T2 ON T1. id ON T2. id) AS TT
WHERE table.id = TT.id

Also, I noticed that your syntax is the SET is not correct:
SET fieldA = tabPrior.fieldA

Redshift does not allow for you to pass the table when selecting the column since it goes under the assumption that you are updating 1 table at a time.

SET column = One or more columns that you want to modify. Columns that
aren't listed retain their current values. Do not include the table
name in the specification of a target column. For example, UPDATE tab
SET tab.col = 1 is invalid.

Link: https://docs.aws.amazon.com/redshift/latest/dg/r_UPDATE.html


How to prove that a tangent cuts through a point when it has an odd order?

Question: I noticed that when a straight line which is a tangent to a polynomial at point $x_1$ is equated to the polynomial, we get a repeated root at point $x_1$.
Let's define a cubic function:
$$y=f(x)=ax^3+bx^2+cx+d$$
whose derivative is equal to:
$$\frac{dy}{dx}=3ax^2+2bx+c$$
At point $x_1$, the slope is $3ax_1^2+2bx_1+c$. The tangent for point $x_1$ is thus:
$$y-y_1=m(x-x_1)$$
$$\implies y-(ax^3_1+bx^2_1+cx_1+d)=(3ax_1^2+2bx_1+c)(x-x_1)$$
$$\implies y=(3ax_1^2+2bx_1+c)x-(2ax_1^3+bx_1^2-d)$$
This form of the tangent is general to every cubic. We can equate the tangent to the polnomial:
$$ax^3+bx^2+cx+d=(3ax_1^2+2bx_1+c)x-(2ax_1^3+bx_1^2-d)$$
$$\implies ax^3+bx^2-(3ax_1^2+2bx_1)x+(2ax_1^3+bx_1^2)=0$$
Since we know $x-x_1$ is a factor, we can factor it out.
$$\implies (x-x_1)[ax^2+bx+ax_1x-(2ax_1^2+bx_1)]=0$$
$$\implies (x-x_1)^2(ax+2ax_1+b)=0$$
Here the root is repeated. So going deeper into this I noticed that if $(x-x_1)$ is repeated thrice, then the tangent cuts through the line and that if it is repeated four times it touches the line. I came to the conjecture that if the root is repeated an even number times, the tangent will touch the curve, but if it is repeated an odd number of times, the tangent will cut through the curve. But how would one prove this conjecture?
Answer: Let $p(x)$ be the polynomial in question, and $t(x)=mx+n$ the tangent to the polynomial at some point $(x_1,y_1)$.
Now, the following arguments are restricted to a small neighborhood of $(x_1,y_1)$. How small depends on $p(x)$. If we take for example $p(x) = x^2(x-0.001)$, then this polynomial has the $x$-axis as tangent on $p(x)$ at $(0,0)$, and this tangent is above the graph of $p(x)$ on both sides of $(0,0)$ 'near' that point, but the $x$-axis will cut trough the graph again at $(0.001,0)$. But this is the nature of tangents, they have 'meaning' for the curve only 'near' they point where they are taken.
So if the tangent $t(x)$ is above or below $p(x)$ depends on the sign of $p(x) - t(x)$: If that difference is below zero, the tangent is above, if it is above zero, the polynomial is above.
The tangent 'cuts through' the polynomial if and only if the sign of $p(x) - t(x)$ changes when $x$ goes from smaller than $x_1$ to higher than $x_1$. Otherwise, it will stay on the same side.
So we have to analyze $p(x) - t(x)$, which is itself a polynomial! Since the polynomial and the tangent both go through $(x_1,y_1)$, we have $p(x_1) - t(x_1) = y_1-y_1=0$, so $x_1$ is a root of $p(x) - t(x)$. This means,
$$p(x) - t(x) = (x-x_1)q(x)$$
For some polynomial $q(x)$. Now let's differentiate that equation, using the product rule on the right:
$$p'(x) - t'(x) =(x-x_1)q'(x) + 1\cdot q(x)$$
Now, $t(x)$ was not just any line through $(x_1,y_1)$, it was the tangent to $p(x)$ at that point. This means they have the same derivative in $(x_1,y_1)$ (which is just the constant $m$ for $t(x)$). If we take that into account and plug in $x=x_1$ in the above equation, we get:
$$p'(x_1) - t'(x_1) = 0 =(x_1-x_1)q'(x_1) + 1\cdot q(x_1) = q(x_1)$$
So we find $x_1$ is also a root of $q(x)$, and we get
$$p(x) - t(x) = (x-x_1)q(x) = (x-x_1)^2r(x)$$
with a new polynomial $r(x)$.
That is what you also found when you did the manual calculation for a polynomial of degree 3. $r(x)$ may or may not have $x_1$ as root. If it doesn't, this process stops here, if it does, we have
$$p(x) - t(x) = (x-x_1)^2r(x) = (x-x_1)^3s(x)$$
a.s.o. until we finally reach a polynomial that does not have $x_1$ as a root (maybe until only a constant remains). So what we can say is there is some value $k \ge 2$ and some polynomial $u(x)$ such that
$$p(x) - t(x) = (x-x_1)^ku(x)$$
and $u(x_1) \ne 0$
That is exactly the term you arrived at as well. Now let's look at what this means for the sign of $p(x) - t(x)$ near $x_1$. $u(x_1) \ne 0$ and $u(x)$ being a polynomial means $u(x)$ is continuous, so in some (maybe small) neighborhood of $x_1$ it will not change it's sign. No matter if $x < x_1$ or $x > x_1$, near $x_1$ $u(x)$ will have the same sign.
Let's now look at the remaining term, $(x-x_1)^k$.
If $k$ is even, this function will also not change its sign, it will always be positive (or $0$ at $x_1$). In this case, the sign of $p(x) - t(x) = (x-x_1)^ku(x)$ will not change when $x$ changes from a value  $<x_1$ to a value $>x_1$, which, as you noticed, means that the tangent $t(x)$ will touch the polynomial $p(x)$ from one side.
If $k$ is odd, however, $(x-x_1)^k < 0$ for $x<x_1$ and $(x-x_1)^k > 0$ for $x>x_1$. So we get that in this case the sign of $p(x) - t(x) = (x-x_1)^ku(x)$
will change when $x$ changes from a value  $<x_1$ to a value $>x_1$, which, as you also noticed, means that the tangent $t(x)$ will cut trough the polynomial $p(x)$.


Closure of the Irrational

Question: I have to find the closure of the Irrational in the context of Euclidean topological space. I would have to find your complementary set, right? And it should be closed in R.
Can you help me? I can not prove it.
Comment: You can indeed use the complementary set of $\Bbb R - \Bbb Q$, and the fact that the interior of this set is .... ?
Comment: it's the very $\Bbb R$
Comment: No, I was talking about the **interior** of $\Bbb Q $, not its closure.
Comment: The interior of $\Bbb R - \Bbb Q$ is the complement of the closure of the complement of $\Bbb R - \Bbb Q$?
Comment: Once again, I'm talking about the interior of $\Bbb Q $, not $\Bbb R - \Bbb Q $.
Comment: $int\mathbb{Q}=\emptyset$
Comment: Yes - you might want to prove that. Now, use the fact that a set is dense iff its complementary has empty interior - why is it true by the way?
Comment: I'll have to study more. We came to conceptss that I did not have the opportunity to see
Comment: Possible duplicate of [Show that the set of irrational numbers is dense in $\mathbb{R}$ using definition of Closure](https://math.stackexchange.com/questions/2641214/show-that-the-set-of-irrational-numbers-is-dense-in-mathbbr-using-definitio)
Answer: As you know $\mathbb{R}=\mathbb{Q}\cup\mathbb{I}$ is a disjoint union, the irrationals are dense in the real numbers, (also the rationals),i.e. $\forall{x,y}\in\mathbb{R}$ with $x>y,\exists{I}\in\mathbb{I}$ (the irrationals) such that $x>i>y$. For this, the border points of $\mathbb{I}$ are $\mathbb{Q}$ and $\mathbb{I}$, and the interior points of $\mathbb{I}$ are the vacuum. You know the clausure of a set is its interior union its border, then you have $\overline{\mathbb{I}}=\mathbb{R}$
Answer: Following our discussion in the comments : one way (amongst many) to prove the density of the irrationals is as follow :

Prove that $\mathring{\Bbb Q} = \emptyset$
Use the following to conclude :

$X$ is dense in $\Bbb R$ $\iff \Bbb R -X$ has empty interior

Let's prove both those points.

$$\begin{align}
\mathring{\Bbb Q} = \emptyset &  \iff \text{ any open subset of $\Bbb Q$ contains an irrational number} \\
&\iff  \forall q \in \Bbb Q, \forall \epsilon > 0, B_\epsilon(q) = \{ x\in \Bbb R\ : \vert x - q \vert < \epsilon \}  \text{contains an irrational number.}
\end{align}$$

But any interval $]a;b[$ contains an irrational number, because :

if there is no irrational in this interval, then $\Bbb R \subseteq \Bbb Q$, since $\forall x \in \Bbb R$, $\exists r \in \Bbb Q$ s.t. $x+r\in ]a,b[$. - left as an exercice
but $\Bbb R \subseteq \Bbb Q$ is obviously false - why ?

This shows $\mathring{\Bbb Q} =\emptyset$.

Let's prove :

$X$ is dense in $\Bbb R$ $\iff \Bbb R -X$ has empty interior

Actually, we're only interested in $\impliedby$. You should be able to prove this, using the fact that $\overline{X} = (\text{int}({X^c}))^c$.

Closure of the Irrational


UINavigationBar contentMode not being set

Question: I am trying to make the background of the UINavigationBar an image, and the image isn't the exact size of the bar. I can't seem to set the contentMode of the bar correctly for some reason. This is the code I have:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // ...

    let image = UIImage(named: object?.imageName ?? "")
    navigationController?.navigationBar.alpha = 0
    navigationController?.navigationBar.setBackgroundImage(image, for: .default)
    self.navigationController?.navigationBar.contentMode = .scaleAspectFill
    UIView.animate(withDuration: Double(UINavigationControllerHideShowBarDuration), animations: {
        self.navigationController?.navigationBar.alpha = 1
    })
}

I don't know what I'm doing wrong, or maybe contentMode just doesn't do anything for UINavigationBar.
What's currently happening is the background image is just presented again like mosaic
Thanks
Answer: You can create UIView and add Image and Text to it, but you must set constraints
    let titleView = UIView()
    titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)

    let containerView = UIView()
    containerView.translatesAutoresizingMaskIntoConstraints = false

    titleView.addSubview(containerView)

    let profileImageView = UIImageView()
    profileImageView.translatesAutoresizingMaskIntoConstraints = false
    profileImageView.contentMode = .scaleAspectFill
    profileImageView.layer.cornerRadius = 20
    profileImageView.clipsToBounds = true
    containerView.addSubview(profileImageView)

    profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
    profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
    profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
    profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true

    self.navigationItem.titleView = titleView

    titleView.addGestureRecognizer(UITapGestureRecognizer(target:
    self, action: #selector(func)))

I hope that I helped you
Comment: Didn't completely work. Ended up adding the image to the `VC`'s `view` and put it behind the `UINavigationController`


python: writing ★ in a file

Question: I am trying to use:
text = "★"
file.write(text)

In python 3. But I get this error message:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0: ordinal not in range(128)

How can I print the symbol ★ in a file in python? This is the same symbol that is being used as star ratings.
Comment: You'll want to use a different encoding. `with open('file.txt', 'w', encoding='utf-8') as f: f.write("★")`
Comment: As long as Python lives, these pesky questions around Unicode will keep coming. I don't understand Python didn't get it right, even in v3.
Comment: @nehemiah I agree, I wish this was automatic in python so the programmer didn't need to take care of these details.
Comment: Possible duplicate of [Writing Unicode text to a text file?](https://stackoverflow.com/questions/6048085/writing-unicode-text-to-a-text-file)
Answer: By default open uses the platform default encoding (see docs):

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

This might not be an encoding that supports not-ascii characters as you noticed yourself. If you know that you want utf-8 then it's always a good idea to provide it explicitly:
with open(filename, encoding='utf-8', mode='w') as file:
    file.write(text)

Using the with context manager also makes sure there is no file handle around in case you forget to close or it throws an exception before you close the handle.

python: writing ★ in a file


Where can I buy elbow grease?

Question: Whenever I'm in the process of fixing something or building something, people keep telling me all it needs is some elbow grease to fix a problem I am having. Although I'm not sure where to buy this 'elbow grease'. Can anyone tell me where I can buy it? I live in Los Angeles, California.
Comment: I think there is a plume of it emitted by the La Brea Tar Pits.
Comment: There is room for humor on this site, I hope and pray??? DIY can be disheartening at times and having something for a grin once in a while is kind of nice.
Comment: [Shopping assistance, product recommendations, or brand specific advice are considered off-topic](http://diy.stackexchange.com/help/on-topic). ;)
Comment: @RedGrittyBrick then why did this question get upvotes? http://diy.stackexchange.com/questions/2924/where-can-i-buy-perspex-sheets?rq=1
Comment: The close reason makes this hilarious.
Comment: Please tell me this is a joke...LOL
Answer: Elbow grease™ can be found in the Shake a Leg store.
Comment: @george, you're either incredibly dense and really need help (and I don't think this is the case), or trolling (trawling?) hard-working men and women on this site to score imaginary internet points. If it's the latter, please stop - it's not very funny at all. And just in case it's the former, please follow the links and advise that people provide, and you'll be helped.
Comment: Where they also carry Flight Line, Prop Wash and Muffler Bearings. We regularly send our newest recruits down to our local "Shake a Leg" store for the experience of collecting parts from our local jobber.
Comment: I can't seem to find where that store is on Google Maps?
Comment: @george:  Please follow my link.  (Elbow grease is a euphemism.)

Where can I buy elbow grease?


PowerShell and = inside a & call parameter

Question: I am trying to run the following inside a powershell script:
ffmpeg.exe -hide_banner -i .\input.mkv -passlogfile input -c:v libvpx-vp9 -b:v 0 -crf 31 -tile-columns 6 -tile-rows 2 -threads 8 -pass 2 -speed 1 -frame-parallel 1 -row-mt 1 -c:a libopus -b:a 256000 -c:s copy -af aformat=channel_layouts=5.1 -auto-alt-ref 1 -lag-in-frames 25 -y output.mkv

This works fine on either cmd or powershell line directly, but not if I try to run it inside a .ps1 with &. I get the following error:
Unrecognized option '-hide_banner -i .\input.mkv -passlogfile input -c:v libvpx-vp9 -b:v 0 -crf 31 -tile-columns 6 -tile-rows 2 -threads 8 -pass 2 -speed 1 -frame-parallel 1 -row-mt 1 -c:a libopus -b:a 256000 -c:s copy -auto-alt-ref 1 -lag-in-frames 25 -y -af aformat=channel_layouts=5.1 output.mkv'. Error splitting the argument list: Option not found

Digging around a bit it seems that the double = with the -af afilter=channel_layouts=5.1 is pissing powershell off and I have no clue how to get around it. Already tried escaping it in some ways with no luck.
Is there any way I can pass these kind of arguments to my exe without powershell complaining to be unable to split up the arguments? Don't understand the shell tries it in the first place anyway as it should all go to my ffmpeg.exe in the first place.
Comment: Please show exact command, which is falling, preferably as [mcve]. Given the error message, you are running `ffmpeg.exe "-hide_banner ..."`, but not `ffmpeg.exe -hide_banner ...`. Also specify your PowerShell version.
Answer: Try passing command line arguments after --% ("stop parsing symbol"):
& ffmpeg.exe --% -hide_banner -i .\input.mkv -passlogfile input -c:v libvpx-vp9 -b:v 0 -crf 31 -tile-columns 6 -tile-rows 2 -threads 8 -pass 2 -speed 1 -frame-parallel 1 -row-mt 1 -c:a libopus -b:a 256000 -c:s copy -af aformat=channel_layouts=5.1 -auto-alt-ref 1 -lag-in-frames 25 -y output.mkv

Comment: oh that might come in handy in another situation, thanks for that!
Answer: my bad. I was just to dump with the output filename. I tried to construct an output filename like this:
$show.$episode.mkv

which for whatever reason works on the commandline.
the correct way is like this:
$outfile = $show + "." + "$episode" + ".mkv";

The splitting error just put me on the wrong track.


How to avoid running actions when repo is created from a template?

Question: I am creating a template repo for building libraries (primarily React18/Next.js libraries with RSC support) using turborepo. I have also added workflows to run unit tests on push or PR. There is also a workflow to automate publishing the package to NPM and GitHub Public Repo.
The issue is that the workflows run immediately after a new repo is created using this template. How to avoid that?
Answer: After exploring some tweaks and streaks, I found a very simple solution to this issue.
jobs:
  test:
    # Don't run just after creating repo from template
    if: github.run_number != 1


VBS script random and switches

Question: In the program below r is initialized as a rounded random number and the user is prompted to guess. If the user guesses correctly there is one prompt Else there is another prompt. The code looks right but when ran the Else case is chosen whether the user got the number right or not. Please help I have read over it so many times that it hurts.
Set WshShell = WScript.CreateObject("WScript.Shell")
'This script is designed to create a random number, and have a user guess the number
'If the user guesses the number incorrectly, negatively impact the users system
'if the user guess the number correctly, do nothing

dim InputValue
dim UserInput
'create a random number
dim r
randomize
r = int(rnd * 10)+1

'Allow the user to guess what number is correct
Input = inputbox ("Choose a number from one to ten, and choose wisely ;)", "Type a number.")
InputValue = Input
'Provide the user with feedback as to what his/her choice was and what the number actually was.
UserInput = "You typed " & InputValue & "." & " The number was " & r & "."
'echo the random generated number for test purposes
WScript.Echo r

Select Case InputValue
    Case r
        WScript.Echo "No action"
    Case Else
        WScript.Echo "Negative Action"
End Select

Answer: The issue is that InputValue is a String type because that's what's returned by the InputBox function and r is an Integer, so when you compare InputValue to r, you're comparing a string to an integer, i.e. apples to oranges.
Proof of concept:
Dim x
x = "5"

Dim y
y = 5

Select Case x
    Case y
        MsgBox "Yes"
    Case Else
        MsgBox "No" 'this is what happens.
End select

VBScript is not a strongly-typed language, i.e. it does not know about types really at all -- well, it kind of knows.  It treats every variable as one type called a "variant" which itself can then have an affinity to a more specific type but in a very confusing and error-prone way.  I'd say you should read this to learn more about it.
You can get into a lot of trouble with this unless you always make sure you know what "types" you're working with.
Try changing it to this:
InputValue = CInt(Input)

Now you're converting the "string" into an "integer" (the variables are both still actually "variants" but they have the same underlying affinity to integer).  However, you want to be careful because someone might input a value that is not able to be converted to an integer, e.g. hello, and thus you'll get an error on this line.  You will need to do some error checking first before converting it.
Comment: Quick check is all you need `If Len(Input & "") > 0 And IsNumeric(Input & "") Then Input = CLng(input) Else input = 0`
Comment: I deleted the comment where I pointed out that `select case "5": case 5: msgbox "yes":  end select` is `yes` because as you say the variables are both variants with different types whereas the constant literals presumably get different treatment,

VBS script random and switches


How does DbQuery implement IEnumerable

Question: I am checking the metadata of Assembly EntityFramework.dll, v220.127.116.11, $EntityFramework.dll$v4.0.30319$NoDynamic\System.Data.Entity.Infrastructure.DbQuery.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace System.Data.Entity.Infrastructure
{
    // Summary:
    //     Represents a non-generic LINQ to Entities query against a DbContext.
    [SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface")]
    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
    public abstract class DbQuery : IOrderedQueryable, IQueryable, IEnumerable, IListSource, IDbAsyncEnumerable
    {
        // Summary:
        //     The IQueryable element type.
        public virtual Type ElementType { get; }

        // Summary:
        //     Returns a new query where the entities returned will not be cached in the
        //     System.Data.Entity.DbContext.
        //
        // Returns:
        //     A new query with NoTracking applied.
        public virtual DbQuery AsNoTracking();
        //
        // Summary:
        //     Returns a new query that will stream the results instead of buffering.
        //
        // Returns:
        //     A new query with AsStreaming applied.
        [Obsolete("Queries are now streaming by default unless a retrying ExecutionStrategy is used. Calling this method will have no effect.")]
        public virtual DbQuery AsStreaming();
        //
        // Summary:
        //     Returns the equivalent generic System.Data.Entity.Infrastructure.DbQuery<TResult>
        //     object.
        //
        // Type parameters:
        //   TElement:
        //     The type of element for which the query was created.
        //
        // Returns:
        //     The generic set object.
        public DbQuery<TElement> Cast<TElement>();
        //
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj);
        //
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode();
        //
        [EditorBrowsable(EditorBrowsableState.Never)]
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public Type GetType();
        //
        // Summary:
        //     Specifies the related objects to include in the query results.
        //
        // Parameters:
        //   path:
        //     The dot-separated list of related objects to return in the query results.
        //
        // Returns:
        //     A new DbQuery<T> with the defined query path.
        //
        // Remarks:
        //     Paths are all-inclusive. For example, if an include call indicates Include("Orders.OrderLines"),
        //     not only will OrderLines be included, but also Orders. When you call the
        //     Include method, the query path is only valid on the returned instance of
        //     the DbQuery<T>. Other instances of DbQuery<T> and the object context itself
        //     are not affected.  Because the Include method returns the query object, you
        //     can call this method multiple times on an DbQuery<T> to specify multiple
        //     paths for the query.
        public virtual DbQuery Include(string path);
        //
        // Summary:
        //     Returns a System.String representation of the underlying query.
        //
        // Returns:
        //     The query string.
        public override string ToString();
    }
}

But I didn't find the GetEnumerator() method. How does this happen?
Answer: From the Mono and actual EF6 source, it's explicitly implementing the function.
https://github.com/mono/entityframework/blob/master/src/EntityFramework/Infrastructure/DbQuery%60.cs#L138
https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/Infrastructure/DbQuery.cs
Answer: It is explicitly implemented... From the codeplex:
#region IEnumerable

///
/// Returns an <see cref="IEnumerator{TElement}" /> which when enumerated will execute the query against the database.
///
/// <returns> The query results. </returns>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
IEnumerator<TResult> IEnumerable<TResult>.GetEnumerator()
{
    ...
}

///
/// Returns an <see cref="IEnumerator{TElement}" /> which when enumerated will execute the query against the database.
///
/// <returns> The query results. </returns>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
IEnumerator IEnumerable.GetEnumerator()
{
    ...
}

#endregion

Ah... Just notice... You are looking at the wrong file... I am checking the metadata of Assembly EntityFramework.dll, v220.127.116.11, $EntityFramework.dll$v4.0.30319$NoDynamic\System.Data.Entity.Infrastructure.**DbQuery.cs** is for the abstract class DbQuery, not for the class DbQuery<TResult>. Being an abstract class, it can be incomplete (not implement all the interfaces). You should look in the DbQuery`.cs file
Comment: Thank you. Though the link does prove it is implemented, you explained why I failed to see it.

How does DbQuery implement IEnumerable


Can't install the Ubuntu One Indicator

Question: sudo apt-get install indicator-ubuntuone
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package indicator-ubuntuone is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'indicator-ubuntuone' has no installation candidate

I even tried 'ubuntuone-indicator', but that also didn't work.
Answer: You have to add Third-Party Repository for installing  UbuntuOne-Indicator, by following these commands
sudo add-apt-repository ppa:rye/ubuntuone-extras
sudo apt-get update && sudo apt-get install indicator-ubuntuone

Logout and login to see the Indicator.
EDIT : If you have already added the Repository then try changing your mirror from software sources (refer image) and do sudo apt-get update && sudo apt-get upgrade in terminal , then try installing again
Comment: @tonybac -Try changing your mirror from software sources and do `sudo apt-get update && sudo apt-get upgrade` in terminal , then try installing again.
Comment: I've done already all of this. Sorry if I had not included the sudo add-apt-repository in my example.
Comment: It worked. I checked my software sources and found out that the rye ppa was unchecked. I had the ubuntu one indicator working before, but after uninstalling both the Ubuntu One app and the indicator, I also unchecked its ppa from my software sources.
Comment: Fine :) , you provided incomplete info in question then , anyways it is now sorted out, HA :D
Comment: this is not valid anymore under raring
Comment: @papachan - You can update the answer for Raring Ringtail..you are always free to do so.

Can't install the Ubuntu One Indicator


Provide a Venn diagram of a counter example of the converse of if A ⊆ B, then A ∪ C ⊆ B ∪ C?

Question: Provide a Venn diagram of a counter example of the converse of
$$A \subseteq B\rightarrow ((A \cup C) \subseteq (B \cup C))$$
Comment: Expecting us to make a drawing for you is not really reasonable.
Comment: Take $C$ to be some set not intersecting $A$ or $B$, then the right side is always true.
Answer: First of all, we need to clearly state the converse of
$$ (A ⊆ B) \rightarrow [(A ∪ C) ⊆ (B ∪ C)].\tag 1$$
The converse of $(1)$ is as follows:
$$[(A ∪ C) ⊆ (B ∪ C)]\rightarrow (A\subseteq B)\tag{2}$$
One counterexample to the converse (2):  $$\text{Suppose } \;A = \{1\}, \;B=\{2\}, \;C=\{1,2\}$$
Then, it is true that $((A ∪ C) = C) ⊆ ((B ∪ C) = C)$ but $A\not \subseteq B$ because $\{1\} \not \subseteq \{2\}$
Comment: Thanks! Great explanation! I got it right!
Comment: You're welcome!
Answer: For example, suppose that $A\subset C$ and $B\subset C$, and $A $ is not a subset of $B$.
For instance, suppose $A=\{a\}$, $B=\{b\}$ with $a\neq b$ and $C=\{a,b\}$.
Comment: This works! thanks!
Answer: Let's take subsets of $\Bbb{R}$:
$A=(0,1)$, $B=(1,2)$ and $C=(0,2)$, for example.
Answer: Consider  when B is a proper subset of A is a proper subset of C.
Comment: If you ever bothered to typeset your answers correctly, then there's a **really** nice way to communicate what you are trying to say


android long forms always opens and focuses on the center of the form

Question: I have developed an application where the form is very long and it scrolls to  2 pages.
 I have multiple doubts
1) whenever my app starts it always goes to the center of the form instead of going to the top of the form,
2) whenever i do a drop down selection the  the form again scrolls  to the center automatically,
3)whenever i click my custom button in the form to take photo and after taking the photo,form again scrolls  to the center automatically,
how to avoid this scrolling and make my form stagnant where i am doing the entry .
Answer:
Set the focus on the first element when the form screen is shown first. For more info, check out requestFocus()
Use the next and previous identifiers so that the next element automatically takes focus when you are moving forward or backward on the form. For more info, check out Focus Handling
Same as point 2. When you set which item has to take focus next, that will prevent some central element taking focus.


Remove CO detector From wired alarm system

Question: My house has a wired smoke alarm system, three smoke detectors and one CO detector. These are all old firex detectors, I am replacing them with three kiddie smoke alarms where one is  combo CO + smoke detector.
The problem is if I remove the old CO detector and leave it disconnected the alarms chirp every 5-10 minutes. I put it back in and the chirping reduced to rarely a couple times a day.
How can I fix this setup to remove that old detector from the system?
Comment: All of your new alarms chirp, or just the one CO detector you have disconnected? Are these brand new detectors (can you check the manufacture date)? In my limited experience, occasional chirping has indicated a bad backup battery and the batteries are usually made to last for the useful life of the detector.
Comment: I have edited the title of your post to better match your actual question. Welcome to diy.stackexchange.
Comment: It sounds like there is an value in the detector needed for verification on some of the dumb systems I worked on years ago a simple 1k resistor was used to verify the sensor was not unplugged. With the smarter programmable systems they must be removed from the program map or disabled.
Comment: @statueuphemism the only chirping one was the combo alarm. I had used the same wire order as the old firex, and just reinstalled it now and saw the white and black wires were wrong. I did this after it woke everyone up this morning with a false fire alarm. The CO detector is now disconnected and no issues. If no chirping in the next 24 hours I will update here as resolved.
Answer: I solved this by re-inspecting the detector that was making the noise. I discover that the original wiring had reversed white and black power connections.
Perhaps the older alarms were not polarized.
I have no confirmed idea why the external CO detector impacted this system, my theory is it helped balance the load to offset the crossed wires.
After fixing the wiring, I was able to remove the external CO detector without any further issue.


Representing a tail in Haskell

Question:
Possible Duplicate:
Where does the name "xs" for pattern matching come from?

I'm learning Haskell. Here is a function that calculates the sum
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs

I can't figure out that xs means. x - is the head, xs - is the tail. But is it written is xs and not as just x or s?
Comment: See http://stackoverflow.com/questions/13701099/where-does-the-name-xs-for-pattern-matching-come-from
Comment: I'm not asking about why is called xs (and not ca or xw or bq). I'm asking about what does it mean exactly or how does it work? I guess there should be only one character.
Comment: It's just a variable name. It can be anything that's allowed by the naming rules. You can read about the syntax of pattern matching in general for example here: http://learnyouahaskell.com/syntax-in-functions#pattern-matching
Answer: x and xs are just variable names; you could use fred and wilma instead, for example. But it's very common to call the head of a list x, and the tail xs (pronounced exes), because it gives you a hint that x is a single element, while xs may contain multiple elements.
The example you've given uses pattern matching, which is a nifty feature. The line
 sum' (x:xs) = x + sum' xs

basically says "take the input parameter to sum', and split it after the first element. Call the first element x and the rest of the list xs". It would be essentially equivalent to:
 sum' list = x + sum' xs
     where x = head list
           xs = tail list

Comment: I was confused because I thought that xs were 2 variables for some reason.
Comment: `xs` is a single variable, but it is a list of elements whereas `x` is just one element. To give you a concrete example, if `(x:xs)` is `"hello"`, then `x` is `'h'` and `xs` is `"ello"`.

Representing a tail in Haskell


Shared Pointer from Boost library

Question: Presently, am using a Shared Pointer from the Boost library.
class A
{
};
main
{
    boost::shared_ptr<class A> classpointer;
}

Under what cirumstances will the "classpointer" counter be incremented?
Comment: But you're not using shared pointer from boost library.
Comment: sorry Juanchopanza i should have used boost instead of std, now it has been edited properly. please help me on this.
Answer: Currently, the pointer is empty, with a count of zero.
It will be incremented to one when you assign ownership of an object, for example
classpointer.reset(new A);  // owns the object, count=1

The count will be incremented if you copy this pointer, or any other pointer that shares ownership of the same object. It will be decremented if you destroy any such pointer, or reassign it to a different object, or reset it to be empty.
In general, the count for a particular object is equal to the number of shared pointers that currently share ownership of it. When the count becomes zero, so that no pointers remain sharing ownership, the object is automatically deleted.

Shared Pointer from Boost library


Command line MSBUILD PreBuildEvent for bower install

Question: I'm trying to create a command line MSBUILD publish on a Jenkins server with a PreBuildEvent to do a bower install. I already tried several options (see below) but the command line output just says build completed without executing the PreBuildSteps and without showing any errors.
Test1
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>True</ExcludeApp_Data>
    <publishUrl>URL</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <ExcludeFoldersFromDeployment>bower_components</ExcludeFoldersFromDeployment>
    <ExcludeFilesFromDeployment>bower.json</ExcludeFilesFromDeployment>
  </PropertyGroup>
  <Target Name="BeforeBuild">
    <Exec Command="bower-installer -silent" />
  </Target>
</Project>

Test2
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemDefinitionGroup>
      <PreBuildEvent>
        <Command>bower-installer -silent</Command>
      </PreBuildEvent>
  </ItemDefinitionGroup>
  <PropertyGroup>
    <PreBuildEventUseInBuild>true</PreBuildEventUseInBuild>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>True</ExcludeApp_Data>
    <publishUrl>URL</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <ExcludeFoldersFromDeployment>bower_components</ExcludeFoldersFromDeployment>
    <ExcludeFilesFromDeployment>bower.json</ExcludeFilesFromDeployment>
  </PropertyGroup>
</Project>

The command I'm executing is the following:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild "<PATH>\website.publishproj" /p:DeployOnBuild=true /p:PublishProfile="<PROFILE>" /p:VisualStudioVersion=14.0

Any help anyone??
Comment: are `Test1` and `Test2` `website.publishproj` or `` in your msbuild commandline?
Answer: The BeforeBuild target is not something that's included in MSBuild by default. You are missing an <Import> of the Microsoft.Web.Publishing.targets, which you can get to your build server by installing the MSBuild.Microsoft.VisualStudio.Web.targets package.
It defines a similar build process as the common msbuild targets. A snippet from the Microsoft.Web.Publishing.targets file:

<PipelineDependsOn Condition="!$(PipelineDependsOnBuild)">
  $(PipelineDependsOn);
  BeforeBuild;
  BuildOnlySettings;
  ResolveReferences;
  PrepareResourceNames;
  ComputeIntermediateSatelliteAssemblies;
  GetCopyToOutputDirectoryItems;
  _SGenCheckForOutputs;
</PipelineDependsOn>

<PipelineDependsOn Condition="$(PipelineDependsOnBuild) And !$(_DeployOnBuild)">
  $(PipelineDependsOn);
  Build;
</PipelineDependsOn>

<PipelineDependsOn Condition="!$(PipelineDependsOnBuild) And !$(_DeployOnBuild)" >
  $(PipelineDependsOn);
  AfterBuild;
</PipelineDependsOn>

Comment: Thanks for the answer. I checked the files and everything is in place. Also the import statement is present in the publishproj file. The BeforeBuild however is still not executed. I tried running the same command on the develop machine and even there it is not working... Do I have to add an option to the MSBUILD command that says it needs to do some prebuild steps?
Comment: @BjoVa did you add `` to Test1 & 2?
Answer: I found the solution...
All the files were in the correct place and the import statements were correctly defined, but if you want to execute the MSBUILD from command line, you have to add some extra parameters.
.pubxml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>FileSystem</WebPublishMethod>
    <LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish />
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>True</ExcludeApp_Data>
    <publishUrl>URL</publishUrl>
    <DeleteExistingFiles>True</DeleteExistingFiles>
    <ExcludeFoldersFromDeployment>bower_components</ExcludeFoldersFromDeployment>
    <ExcludeFilesFromDeployment>bower.json</ExcludeFilesFromDeployment>
  </PropertyGroup>
  <Target Name="BeforeBuild">
    <Exec Command="bower-installer -silent" />
  </Target>
</Project>

Command line
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild "<PATH>\website.publishproj"
/t:BeforeBuild;Build /p:DeployOnBuild=true /p:PublishProfile="<PROFILE>"
/p:VisualStudioVersion=14.0

The trick was to add the /t:<Target Name>;Build (don't forget to add the build are else it will only execute the specified target).


Android Add many Imageview by code

Question: I would like to create a layout with many ImageView on it.
It should be an array of 10 pictures by 15 pictures. There is only 5 differents picture but I need to place them many time on this array.
Something like that but in 10 * 15 :
http://blazinggames.com/brain/puzzle/screenshots/cc.gif
So far, I am using a linear layout ( not sure it is the best choice Oo ) and I have this :

unsing this code :
<code>LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);

linearLayout.setLayoutParams(new LayoutParams(
       LayoutParams.MATCH_PARENT,
       LayoutParams.MATCH_PARENT));

ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.green);
imageView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(imageView);
setContentView(linearLayout);
</code>
And I set an imageview1, imageview2, ... Each one with one of the 5 drawable I want ...
I know ! It is not the good way to code this ! It could work but it is very very long !
That is why I am here ^^
Can anyone help me ?
Thanks
Comment: You can use custom grid view.
Comment: You could have used a for loop to place your image view if the image chosen depends on the position. If this is not the case, so you have no way out but to manually code each.
Comment: Thanks guys but I dont know how to create a custom GridView neither to use a loop to set different drawable for different imageview, can you help me a little bit more ? Thanks !
Answer: I have been able to make a gridview ! Thanks !

Android Add many Imageview by code


Export to csv in ui-grid : exporterAllDataFn fires only when we have more than one page

Question: exporterAllDataFn event fires only when we have more than one page : when i reduce the page size and i have two pages it fires but when i have only one page it doesn't fire.i have some code in exporterAllDataFn that must be run each time . is there any solution or other way to run some piece of code before exporting ?!!
Answer: you can use it to call a new function which you can handle the downloading of CSV:
exporterAllDataFn: function () {
<code>                $scope.downloadCSV();
</code>
}
and handled the csv here:
<code>$scope.downloadCSV = function () {

            paramsObj['query'] = $scope.keyword;

            $scope.downloadCSVPromise = Material.query(paramsObj, function (response) {

                if (response && response.partSearchList && response.partSearchList.length > 0) {

                    $scope.noData = false;

                    $scope.numFound = response.numFound;

                    **var csv = JSON2CSV(response.partSearchList);**
                    //window.open("data:text/csv;charset=utf-8," + escape(csv))

                    if (window.navigator.msSaveOrOpenBlob) {
                        var blob_ie = new Blob([decodeURIComponent(encodeURI(csv))], {
                            type: "text/csv;charset=utf-8;"
                        });
                        navigator.msSaveBlob(blob_ie, 'FileName.csv');
                    }

                    var date = new Date();
                    var today = date.toString().substr(4,20);
                    var regex = new RegExp(" ", 'g');
                    today = today.replace(regex, '_');
                    var fileNm = 'AGSExtract_'+today+'.csv';

                    var downloadLink = document.createElement("a");
                    var blob = new Blob(["\ufeff", csv]);
                    var url = URL.createObjectURL(blob);
                    downloadLink.href = url;
                    downloadLink.download = fileNm;

                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);

                } else {

                    $scope.noData = true;
                }
            });

        };
</code>
Above solution is for server side full data, if you are using client side pagination then check for JSON2CSV and pass the $scope variable which has the table data.
Hope this helps :)
Comment: my problem is that exporterAllDataFn code does not even fire when we have one page
Comment: Can you make a plunker or jsfiddle to show your code then may be i could help because i have implemented the same and works smooth silk.


How to combine two dynamic arrays to make one dynamic array in a formula?

Question: I have two columns both with results of individual unique functions, i.e. both columns contain unrelated dynamic arrays.
Is there a way I can combine both these dynamic arrays as a single dynamic 2D array and use in a formula?
Example:
Cell A1 = UNIQUE(rng1)
Cell B1 = UNIQUE(rng2)
both always return same number of items.
What I want in cell D1 = SORT(A1#:B1#)  --> how do I do this combination?
The notation A1#:B1# gives an error.
Answer: You could use:
<code>=SORT(CHOOSE({1,2},A1#,B1#))
</code>
Comment: Perfect, thanks. I like how I can combine UNIQUE, SORT & CHOOSE in these ways to eliminate a significant need to use vba!
Comment: How do I do this if A1# or B1# were to have multiple columns?
Comment: I can't think of a good dynamic way currently. You could use something like: `=SORT(CHOOSE({1,2,3},A1#,INDEX(B1#,0,1),INDEX(B1#,0,2)))` If you know the columns will be next to each other, you could use: `=SORT(OFFSET(A1#,0,0,,3))` for example
Comment: Thanks. I see, can devise situational solutions using choose & offset. I'll try and find if there can be a universal solution for stacking/appending arrays in Excel 365.


Display Int value in text box swift from parse

Question: I have this code in swift 2 to get the Int phone no from Parse and display in a text box
        if (PFUser.currentUser()!["phoneNumber"] !== nil)
    {
        mobile.text = String(PFUser.currentUser()!["phoneNumber"] as? Int)
    }

But it shows it as Optional(XXXXXXXXXX) ...but i just want the it without Optional wrapping like XXXXXXXXXX
Answer: A solution is to use optional chaining and optional binding
if let phoneNumber = PFUser.currentUser()?["phoneNumber"] as? Int {
    mobile.text = String(phoneNumber)
}