JS window.close popup isn't working after refresh of parent

Question: Currently i'm creating a simple html/php/js project for internal use and found a little problem i can't solve by my self :-(
In my parent window is a JS function which opens and closes a popup with:
function openit(){
  boersenfenster = window.open('boerse.php','_blank','scrollbars=no');
}
function closeit(){
  boersenfenster.close();
}

Now after a while the parent window refreshes to get fresh data of a csv file and after the page reload the closeit() function isn't working anymore. In my thoughts, the parent window can't remember the openend popup after the refresh but how can i fix this problem?
Answer: Yes, I believe the parent window has lost the the link, so you can either
use ajax to update your page, or close the child window like this
window.addEventListener('beforeunload',function(e){
       boersenfenster.close();
};

and then reopen the child window after the page has reloaded
Comment: thanks for the answer, so reopen the child window is not really an option because it's showed fullscreen on a beamer in a show.

I haven't worked with ajax yet, is there a easy way to implement what i need?
Comment: so you can either use ajax to update the page, or possibly use local storage.http://www.codediesel.com/javascript/sharing-messages-and-data-across-windows-using-localstorage/


Twitter rss feed 401 - unauthorisation

Question: I have a public twitter account and this is the rss feed for it:
http://twitter.com/statuses/friends_timeline/150784631.rss
The problem is, im getting an http 401 whenever im trying to access it.
Can anybody explain how to stop this - and get it to work either with authentication or without!
Cheers
Comment: Wait, this doesn't sound right. friends_timeline is usually accessed like this:

http://api.twitter.com/1/statuses/friends_timeline.rss

and it gives you your friends' timelines. Where did you get the RSS link above?
Answer: It looks like you need a Twitter API username/password to access this feed.
Comment: I want to access the status updates programatically without authentication ideally...

This works but isnt in rss format :

http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=cicsdemo
Comment: Just change .xml to .rss

http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=cicsdemo

Twitter rss feed 401 - unauthorisation


Import-CSV Nested HashTable

Question: Say I have a CSV file that looks like:
arch,osversion,kb
32,6.1,KB1,http://kb1
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4

How would this CSV get imported into structured hash table that looks like this?
32 -> 6.1 -> KB1 -> http://kb1
   -> 6.2 -> KB2 -> http://kb2
64 -> 6.1 -> KB3 -> http://kb3
   -> 6.2 -> KB4 -> http://kb4

The command below yields http://kb1:
$data['32'].'6.1'.'KB1'

Answer: Probably Group-Object is what you want.
$csv = @'
arch,osversion,kb,link
32,6.1,KB1,http://kb1
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4
'@

$data = ConvertFrom-Csv $csv

$data | Group-Object -Property arch

Or maybe closer to what you want to query:
$groups = $data | Group-Object -Property arch, osversion, kb
($groups | ? Name -eq '32, 6.1, KB1').Group.link

You could even use variables...
$a = '32'
$o = '6.1'
$k = 'KB1'

($groups | ? Name -eq "$a, $o, $k").Group.link

From this, you can determine if such a pattern works for you.
Comment: thanks, the idea is not to use where-object by accessing it directly as opposed to filtering it.
Answer: Interesting task. The following code snippet could help (solves arch duplicates):
Remove-Variable data*, aux* -ErrorAction SilentlyContinue ### clear for debugging purposes
$datacsv = @'
arch,osversion,kb,link
32,6.1,KB1,http://kb1
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4
'@
$datac = ConvertFrom-Csv $datacsv
$datag = @{}
$datac | ForEach-Object {
    $auxLeaf    = @{ $_.kb = $_.link }
    $auxParent  = @{ $_.osversion = $auxLeaf }
    if ( $datag.ContainsKey( $_.arch) ) {
        $auxParent += $datag[ $_.arch]
    }
    $datag.Set_Item( $_.arch, $auxParent )
}

Then, $datag['32']['6.1']['KB1'] returns desired value http://kb1
Another interesting problem: solve osversion duplicates in a particular arch:
Remove-Variable data*, aux* -ErrorAction SilentlyContinue ### clear for debugging purposes
$datacsv = @'
arch,osversion,kb,link
32,6.1,KB1,http://kb1
32,6.1,KB5,http://kb5
32,6.1,KB7,http://kb7
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4
'@
$datac = ConvertFrom-Csv $datacsv
$datag = @{}
$datac | ForEach-Object {
    $auxLeaf   = @{ $_.kb = $_.link }
    $auxParent = @{ $_.osversion = $auxLeaf }
    if ( $datag.ContainsKey( $_.arch) ) {
        if ( $datag[$_.arch].ContainsKey($_.osversion) ) {
            $auxLeaf  += $datag[$_.arch][$_.osversion]
            $auxParent = @{ $_.osversion = $auxLeaf }
        } else {
            $auxParent += $datag[ $_.arch]
        }
    }
    $datag.Set_Item( $_.arch, $auxParent )
}

The latter code snippet is roughly equivalent to
$datag =
@{
    '32' = @{ '6.1' = @{ 'KB1'='http://kb1';
                         'KB5'='http://kb5';
                         'KB7'='http://kb7' };
              '6.2' = @{ 'KB2'='http://kb2' }
            };
    '64' = @{ '6.1' = @{ 'KB3'='http://kb3' };
              '6.2' = @{ 'KB4'='http://kb4' }
            }
 }

Comment: This is very well thought out and works. Thanks very much.

Import-CSV Nested HashTable


USB DVD drive mapped to wrong product

Question: I'm on Ubuntu 16.04.3 LTS (dual boot w/ Windows)
I picked up this external USB DVD writer, model ECD819-SU
I have successfully plugged it in, burned a CD, and listened to the CD in the car, so at one point everything worked fine without doing anything special.
Now many days later I try to burn another CD and things are strange.
Plugging in the USB DVD drive no longer notifies me of a blank disc in it or otherwise appears in Brasero or file viewer.
After searching for similar problems I come across this technique where I unplug and replug the USB DVD drive, then run this:
dmesg | tail
[ 1517.648577] usb 3-1: USB disconnect, device number 10
[ 1562.479656] usb 3-1: new high-speed USB device number 11 using xhci_hcd
[ 1562.621181] usb 3-1: New USB device found, idVendor=13fd, idProduct=1040
[ 1562.621186] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 1562.621189] usb 3-1: Product: \xffffffc2\xffffff92¬A6þ¾\xffffffc2\xffffff80\xffffffc2\xffffff83/µ\xffffffc2\xffffff85\xffffffc2\xffffff87ðL
[ 1562.621192] usb 3-1: Manufacturer: Initio
[ 1562.621195] usb 3-1: SerialNumber: 00000000000000000
[ 1562.621919] usb-storage 3-1:1.0: USB Mass Storage device detected
[ 1562.622179] scsi host6: usb-storage 3-1:1.0
[ 1585.001736] usb 3-1: reset high-speed USB device number 11 using xhci_hcd

Cool so the vendor ID is 13fd and the product ID is 1040.
More searching and I come across http://www.linux-usb.org/usb.ids which reveals some interesting info:
    13fd  Initio Corporation
        0840  INIC-1618L SATA
        0841  Samsung SE-T084M DVD-RW
        ...
        1040  INIC-1511L PATA Bridge   <--- current PID
        1340  Hi-Speed USB to SATA Bridge
        ...
        3940  external DVD burner ECD819-SU3  <--- HEY, this is right!
        3e40  ZALMAN ZM-VE350

So that's where I'm stuck. I don't know if the product ID actually changed or has been this way all along. Even though I can see some files with these codes, I would rather not just blindly change values:
/sys$ grep -r "13fd" * 2>/dev/null
devices/pci0000:00/0000:00:14.0/usb3/3-1/idVendor:13fd
devices/pci0000:00/0000:00:14.0/usb3/3-1/3-1:1.0/uevent:PRODUCT=13fd/1040/106
devices/pci0000:00/0000:00:14.0/usb3/3-1/uevent:PRODUCT=13fd/1040/106

I assume that 106 following 13fd and 1040 is some kind of driver ID, so I'd have to know what the DVD drive driver ID should be, maybe.
Anyway, any suggestions? Should I edit these things, or use some technique to get Ubuntu to totally forget this info and see if it will deduce the correct product/driver from scratch again?
Answer: If you do not see any message about the device being recognized as "sr",
then the drive (obviously behind a PATA-USB bridge) is not recognized
as optical drive. Probably it is not detected at all.
A power cycle (with quite old kernel) looks here in dmesg like

[...] usb 2-1.5: USB disconnect, device number 82
[...] usb 2-1.5: new high-speed USB device number 90 using ehci-pci
[...] usb 2-1.5: New USB device found, idVendor=152d, idProduct=2338
[...] usb 2-1.5: New USB device strings: Mfr=1, Product=2, SerialNumber=5
[...] usb 2-1.5: Product: USB to ATA/ATAPI Bridge
[...] usb 2-1.5: Manufacturer: JMicron
[...] usb 2-1.5: SerialNumber: 59CF92A50122
[...] usb-storage 2-1.5:1.0: USB Mass Storage device detected
[...] scsi78 : usb-storage 2-1.5:1.0
[...] scsi 78:0:0:0: CD-ROM            ASUS     BW-16D1HT        1.01 PQ: 0 ANSI: 0
[...] sr4: scsi3-mmc drive: 48x/48x writer dvd-ram cd/rw xa/form2 cdda tray
[...] sr 78:0:0:0: Attached scsi CD-ROM sr4
[...] sr 78:0:0:0: Attached scsi generic sg6 type 5

One can see that the drive's class "CD-ROM", its manufacturer "ASUS", its
drive model id "BW-16D1HT", and its firmware revision "1.01" are reported.
Then some of its oldfashioned CD capabilities are reported and it gets
attached as optical drive /dev/sr4 (and generic SCSI device /dev/sg6).
Your dmesg reports a reset instead, which i do not see here. Your dmesg
mentions "1040", which you found in the web as "PATA Bridge". That would
be the hardware in the drive's box, which makes it appear as USB device
although all optical drives have either PATA or SATA controllers.
(In my case it's by "JMicron".)
Fishiness in your dmesg begins by:

[ 1562.621189] usb 3-1: Product: \xffffffc2\xffffff92¬A6þ¾\xffffffc2\xffffff80\xffffffc2\xffffff83/µ\xffffffc2\xffffff85\xffffffc2\xffffff87ðL

Why cannot the USB controller tell its model name, like mine does ?

[...] usb 2-1.5: Product: USB to ATA/ATAPI Bridge

This difference and the reset give me the suspicion that the USB controller
in the drive's box has died.
Comment: Thanks for looking it over! I purchased this drive new just recently, but it was very cheap and from a company I hadn't heard of. You've convinced me even if there is a way to revive it that it's not worth any more time.
Answer: I have the same problem with a device showing the identical lsusb info.
Bus 001 Device 004: ID 13fd:1040 Initio Corporation INIC-1511L PATA Bridge
I had used this CD/DVD Writer on Mac for a number of years, then I switched to linux & used it there also.
Recently I reinstalled my distros. I was able to burn 1 CD & then I was unable to burn anymore. At that point I noticed the device was shown as PATA Bridge.
However, it is NOT BROKEN as I can still use it to play CDs & it seems to work fine as a player in Archcraft & Manjaro.
Connecting the device to my wife's Win11 computer I was able to burn a CD without issue.
But in multiple Linux CD writing apps it will not work. (xfburn, brasero, gnome cd master, k3b)

USB DVD drive mapped to wrong product


UIDatePicker NSRangeException crash iOS 11

Question: I have the following code to add a DatePicker to one of my UIViews.
UIDatePicker *datePicker =
      [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 30, 320, 250)];
  [datePicker setDatePickerMode:UIDatePickerModeDate];
  datePicker.hidden = NO;
  datePicker.date = [NSDate date];
  [datePicker addTarget:self
                 action:@selector(changeDateInLabel:)
       forControlEvents:UIControlEventValueChanged];
  [self.dateView addSubview:datePicker];

This code has been around for a while but we've been noticing some random crashes now. The crashes only happen in iOS 11. This is what the stack trace of the crash looks like
Fatal Exception: NSRangeException
    *** -[__NSArrayM objectAtIndex:]: index 9223372036854775807 beyond bounds [0 .. 1]
    Fatal Exception: NSRangeException
        0  CoreFoundation                     0x180d87d38 __exceptionPreprocess
        1  libobjc.A.dylib                    0x18029c528 objc_exception_throw
        2  CoreFoundation                     0x180d20c44 _CFArgv
        3  CoreFoundation                     0x180c50cc0 -[__NSArrayM removeObjectAtIndex:]
        4  UIKit                              0x18a3ecaa8 -[UIPickerView selectedRowInComponent:]
        5  UIKit                              0x18ac52224 -[_UIDatePickerMode_Date _dateForYearRow:]
        6  UIKit                              0x18ac4edd8 -[_UIDatePickerMode dateForRow:inCalendarUnit:]
        7  UIKit                              0x18ac4fa70 -[_UIDatePickerMode _updateSelectedDateComponentsWithNewValueInComponent:usingSelectionBarValue:]
        8  UIKit                              0x18ac4fd18 -[_UIDatePickerMode selectedDateComponents]
        9  UIKit                              0x18ac43370 -[_UIDatePickerView _updatedLastSelectedComponentsByValidatingSelectedDateWithLastManipulatedComponent:]
        10 UIKit                              0x18ac427e8 -[_UIDatePickerView _setDate:animated:forced:]
        11 UIKit                              0x18ac42d24 -[_UIDatePickerView _setMode:]
        12 UIKit                              0x18ac42e40 -[_UIDatePickerView setDatePickerMode:]

Any pointers on what would be causing this crash?
Thank you
Comment: Honestly, this looks like a framework bug to me, if the crash is occurring on the second line of the code above (which the stack trace suggests, but which could be verified either using the debugger or by sticking a log after the `-setDatePickerMode:` line and seeing if that log occurs before the crash). A brand-new date picker shouldn't be crashing just because you set the mode on it. With that said, maybe if you reorder your lines so that you call `-setDatePickerMode:` after you set everything else up, it will work around it?
Comment: Agree it's a framework bug, based on the symbolic name I'd suspect it's trying to validate something that no longer applies in iOS 11. Does it still crash if you delete and reinstall the app (i.e. fresh iOS 11 install?)?.
Comment: @CharlesSrstka I agree. I would try setting the picker's `date` property before setting the picker mode and see if that helps.
Comment: What I'd do would be to try to reduce it to the simplest possible program that will cause the crash, and attach the project to a Radar report.
Comment: `index 9223372036854775807 beyond bounds [0 .. 1]` seems pretty clear to me. How do you try to access the picker's data?
Comment: What's the implementation of `changeDateInLabel:`? Just as Linus said, the error is pretty self-explanatory.
Comment: @LinusGeffarth The crash happens on viewdidload where I setup the date picker not when I try to access the picker data
Comment: @CharlesSrstka Thanks, that's what I feel too. I'll reorder it so the datePickerMode is set up at the end. Also, I'm thinking of setting a min and max date for the picker. I'm not able to reproduce the crash so will add some crashlytics breadcrumbs and monitor it.
Comment: Seems related: https://stackoverflow.com/questions/46600674/iosfatal-exception-nsrangeexception Maybe a Radar should be opened?
Comment: @tbag Did you get any solution for this?
Answer: Follow this code.it is help you.
UIDatePicker *datePicker=[[UIDatePicker alloc]init];
    datePicker.datePickerMode=UIDatePickerModeDate;
    [self.dateSelectionTextField setInputView:datePicker];
    UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [toolBar setTintColor:[UIColor grayColor]];
    UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(ShowSelectedDate)];
    UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBar setItems:[NSArray arrayWithObjects:space,doneBtn, nil]];
    [self.dateSelectionTextField setInputAccessoryView:toolBar];.

-(void)ShowSelectedDate
{   NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"dd/MMM/YYYY hh:min a"];
    self.dateSelectionTextField.text=[NSString stringWithFormat:@"%@",[formatter stringFromDate:datePicker.date]];
    [self.dateSelectionTextField resignFirstResponder];
}

Comment: And what did you want to say with this answer?


In an node.js + express app, how can you redirect a URL to remove a file extension from the previous site?

Question: I am transitioning our site which is in a ASP environment and hosted on a Windows server.
The existing URL is
http://www.bruxzir.com/video-bruxzir-zirconia-dental-crown/index.aspx

But I need it to be
http://www.bruxzir.com/video-bruxzir-zirconia-dental-crown/

My app.js has this as the route
app.get('/video-bruxzir-zirconia-dental-crown/', function(req, res){
  res.render('videos', {
    title: 'BruxZir Video Gallery'
  });
});

The new site will likely be hosted as a node.js app on heroku. Can I take care of this with an .htaccess ? if so, where would this be placed in an express app? and not all existing URLs have index.aspx only a few of them.
Comment: try to remove the last / from your defined route...  '/video-bruxzir-zirconia-dental-crown'
Answer: Many ways to get this to work, but here's one with a little middleware:
app.use(function (req, res, next) {
  if (/index\.aspx$/i.test(req.path)) {
    res.redirect(req.path.slice(0, req.path.length - 11));
    return;
  }
  next();
});

Comment: what about query strings such as a=1&b=2 after the aspx extension
Comment: You can retain that if you like. It's parsed into an object available as `req.query` or you can use the `req.originalUrl` string.


I'm continuously repeating code and wondering if there's a way to simplify these if statements

Question: The code I created is used in pygame to highlight buttons that I am hovering over and when clicked on will trigger their corresponding function
if singleplayer_button.collidepoint(mx, my):
    pygame.draw.rect(WIN, (180, 0, 0), singleplayer_button)
    WIN.blit(singleplayer_button_text, (295, 400))
    if click:
        singleplayer()
else:
    pygame.draw.rect(WIN, RED, singleplayer_button)
    WIN.blit(singleplayer_button_text, (295, 400))

if multiplayer_button.collidepoint(mx, my):
    pygame.draw.rect(WIN, (180, 0, 0), multiplayer_button)
    WIN.blit(multiplayer_button_text, (727, 400))
    if click:
        multiplayer1()
else:
    pygame.draw.rect(WIN, RED, multiplayer_button)
    WIN.blit(multiplayer_button_text, (727, 400))

if leaderboard_button.collidepoint(mx, my):
    pygame.draw.rect(WIN, (180, 0, 0), leaderboard_button)
    WIN.blit(leaderboard_button_text, (291, 550))
    if click:
        leaderboard()
else:
    pygame.draw.rect(WIN, RED, leaderboard_button)
    WIN.blit(leaderboard_button_text, (291, 550))

if credit_button.collidepoint(mx, my):
    pygame.draw.rect(WIN, (180, 0, 0), credit_button)
    WIN.blit(credits_button_text, (774, 550))
    if click:
        credit()
else:
    pygame.draw.rect(WIN, RED, credit_button)
    WIN.blit(credits_button_text, (774, 550))

if register_button.collidepoint(mx, my):
    pygame.draw.rect(WIN, (180, 0, 0), register_button)
    WIN.blit(register_button_text, (300, 700))
    if click:
        register()
else:
    pygame.draw.rect(WIN, RED, register_button)
    WIN.blit(register_button_text, (300, 700))

if exit_button.collidepoint(mx, my):
    pygame.draw.rect(WIN, (180, 0, 0), exit_button)
    WIN.blit(exit_button_text, (737, 700))
    if click:
        exit_window()
else:
    pygame.draw.rect(WIN, RED, exit_button)
    WIN.blit(exit_button_text, (737, 700))

####_button is a rectangle
####_button_text is text which gets blitted on top the rectangle
Answer: Read a bout Classes.
Create a Button class:
class Button():
    def __init__(self, rect, text, action):
        self.rect = rect
        self.text = text
        self.action = action
    def draw(self, win):
        pygame.draw.rect(win, (180, 0, 0), self.rect)
        WIN.blit(self.text, self.text.get_rect(center = self.rect.center))
    def click(self, mx, my, click):
        if self.rect.collidepoint(mx, my) and click:
            self.action()

Create a list of Botton objects:
buttons = [
    Button(singleplayer_button, singleplayer_button_text, singleplayer),
    Button(multiplayer_button,  multiplayer_button_text,  multiplayer1),
    Button(leaderboard_button,  leaderboard_button_text,  leaderboard),
    Button(credit_button,       credits_button_text,      credit),
    Button(register_button,     register_button_text,     register),
    Button(exit_button,         exit_button_text,         exit_window)
]

Draw the buttons in a loop:
for button in buttons:
    button.draw(WIN)

Do the click detection in a loop:
for button in buttons:
    button.click(mx, my, click)

Comment: Thanks for the solution, if I could upvote this I would.
Comment: @MinhajRahman Thank you. You're welcome.
Comment: @MinhajRahman Sorry, my bad. There was a typo in the answer. `Button(register_button, register_button_text, register),` instead of `Button(register_button, register_button, register),` (the 2nd argument is `register_button_text`).
Comment: Ahhhh I've been trying to figure this out for a while now and didn't even notice, thanks again
Comment: I just wanted to follow up on this. I get and error when I try to run the code   line 147, in draw
    WIN.blit(self.text, self.text.get_rect(center=self.rect.center))
AttributeError: 'pygame.Rect' object has no attribute 'get_rect'
Comment: Same for `Button(exit_button, exit_button_text, exit_window)`.


301 Redirects Using Regular Expression

Question: I'm migrating a blog to a new platform. I've handled 301 redirects for individual URLS via .htaccess. The old blog has individual URLs for archives for each month of each year. As the blog has been active for around a decade, there's a lot of them. I need each of these URLs to re-direct to a single archives page in the new blog. Due to the number of URLs, I have no interest in entering individual 301s for each one, and I want to write a regular expression to match and redirect these.
So, an example of an old URL: http://www.example.com/2014_11_01_archive.html
This would redirect to: http://www.example.com/archives/
What I have in the .htaccess currently:
RedirectRule ^/.*_archive.html$ http://www.example.com/archives [R=301, L]

Which results in a 500 error. Looking for ideas as to what I have wrong about this.
Comment: 500 error is because of  RedirectRule ,as far as im aware that directive does not exist in apache.
Answer: Try with RedirectMatch directive:
RedirectMatch 301 ^/.*archive\.html$ http://www.example.com/archives/

301 Redirects Using Regular Expression


react-toastify: How to position the toasts a little up from the bottom

Question: I want to position the toast at the bottom-right but with some offset from the bottom
example,.

Currently this is my ToastContainer definition
ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route path="/admin" component={Admin} />
      <Redirect from="/" to="/admin" />
    </Switch>
    <ToastContainer
        position="bottom-right"
        autoClose={500000}
        hideProgressBar
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
    />
  </Router>,
  document.getElementById("root")
);

I checked the css it shows
.Toastify__toast-container--bottom-right {
    bottom: 1em;
    right: 1em;
}

HOw to adjust this to
.Toastify__toast-container--bottom-right {
    bottom: 11em;
    right: 1.5em;
}

Where can i mention this
Answer: Just mention it in the CSS imported in your .jsx file.
Please add a className to your Container like
<ToastContainer
        className="toast-position"
        position="top-center"
        autoClose={10000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="dark"
      />

And then in your css file you can do something like this
.toast-position {
  top: 8rem !important;
}

You can also checkout here for more info
https://github.com/fkhadra/react-toastify/issues/263
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Unable to inject class with Dagger 2

Question: I am attempting to add Dagger 2 to my Android Project.  I think I understand the concepts up to the point of where I build the graph.  At that point I'm shooting in the dark and that is where I'm going wrong.
Everything compiles, but the injected field is null at Runtime.
I am attempting to start simply by injecting the Presenter into my MainActivity.  I have written the following code and would appreciate some help figuring out where I have gone wrong.
My PresenterModule.java:
@Module
public class PresenterModule {

  @Provides MainActivityPresenter providesMainActivityPresenter() {
    return new DefaultMainActivityPresenter();
  }
}

My Application class which also includes my Component following the Dagger2 example code:
public class App extends Application {

  private PresenterComponent component;

  @Singleton
  @Component(modules = PresenterModule.class)
  public interface PresenterComponent {
    void inject(App app);
    void inject(MainActivity activity);
  }

  @Override public void onCreate() {
    Log.d("App.java", "Starting Application");
    super.onCreate();

    component = DaggerApp_PresenterComponent.builder()
        .presenterModule(new PresenterModule())
        .build();
    component.inject(this);
  }

  public PresenterComponent component() {
    return component;
  }
}

And finally my MainActivity.
public class DefaultMainActivity
    extends ActionBarActivity
    implements MainActivity
{
  @Inject MainActivityPresenter mPresenter;

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

    ((App)getApplication()).component().inject(this);

    mPresenter.getCurrentDetailLineNumber();
    setContentView(R.layout.base_layout);

    getSupportActionBar();

    mContainer = (Container) findViewById(R.id.container);
    mPresenter.requestCurrentScreen();
  }

The actual object to be injected is an implementation of an interface but is other wise a POJO object:
public class DefaultMainActivityPresenter implements MainActivityPresenter {

  private static final int SCREEN_BROWSER = 0;
  private static final int SCREEN_DETAIL = 1;

  LineNumber mCurrentDetailLineNumber;
  int mCurrentScreen;

  @Inject
  public DefaultMainActivityPresenter() {
  }
  ...
}

Comment: you don't say what the error is, compile time typing? null pointer? ...
Comment: Sorry, the injected variable is null at runtime. Everything compiles fine.
Answer: Changing PresenterComponent to following will fix your problem:
  @Singleton
  @Component(modules = PresenterModule.class)
  public interface PresenterComponent {
    void inject(App app);
    void inject(DefaultMainActivity activity);
  }

This is due to covariance:
While a members-injection method for a type will accept instances of its subtypes, only Inject-annotated members of the parameter type and its supertypes will be injected; members of subtypes will not. For example, given the following types, only a and b will be injected into an instance of Child when it is passed to the members-injection method injectSelf(Self instance):
   class Parent {
     @Inject A a;
   }

   class Self extends Parent {
     @Inject B b;
   }

   class Child extends Self {
     @Inject C c;
   }

Comment: Unfortunately, yes. However, inject method will initialize all members up the inheritance chain.
Comment: Does every class that needs an injected variable need an inject() call in the Component?

Unable to inject class with Dagger 2


I only asked 2 questions - how come I am on a question ban?

Question: I have asked 2 questions, and when I tried to ask another I got a question ban. Is my performance from other SE sites effecting me here?
Answer: The question ban (and answer ban) is in this case decided by the bot. As as far as I know, user-activity on one site doesn't affect question/answer bans on others. For instance, your Bio account is still fully functional.
The fact that your banned from the main site is probably because of the latest downvote(s) here. Overall your posts have gathered a negative vote tally, enough for the bot to act. You can read more on it here in the help center.
And for that matter - you asked three questions, including a deleted one, namely Would SE have a voting war? [closed] that's probably not visible for you any longer. This question received three downvotes.


Vector Resultant Angle and Direction

Question: I am working with set of points, and my goal is to add 4 vectors together and calculate the resultant between start and end point,
Since I already prepared the code to do the above part which seems to be working fine but am not to sure about it.
Anyway the real reason I am posting this question is to do with the resultant direction and angle.
I find it hard to either understand the concept of finding resultant angle and direction as well as PROGRAMMING wise.
Consider this scenario....Image

1st add vectors "Head 2 Tail"
From what I have learned about vector addition is to subtract  x2 - x1, y2 -y1 this will dive me the misplacement difference and do the same calculation for all the points from A-E
To get the resultant I  square root  all the points x to power of 2 and add all the  y position to power of 2.
This ideology seem to work fine.....
But the QUESTION here is how do i get the angle and direction of that resultant....?
the code I use to calculate resultant:
 double Pta;
    double Ptb;
    Point  vect;
    float R1, R2;
    float resultant;

    for(vector<Point>::iterator iter_a = Left_Arm_xy.begin()+1; iter_a != Left_Arm_xy.end(); ++iter_a)
    {

        if(center.y <= 240)
        {
            vect.x = iter_a->x - (iter_a -1)->x;
            vect.y = iter_a->y - (iter_a -1)->y;

            vect_add.push_back(Point(vect.x,vect.y));

                for(vector<Point>::iterator iter_v = vect_add.begin(); iter_v - vect_add.begin() + 4 < vect_add.size(); iter_v+=4)
                {

                        R1 = iter_v->x + (iter_v +1)->x + (iter_v +2)->x + (iter_v +3)->x;
                        R2 = iter_v->y + (iter_v +1)->y + (iter_v +2)->y + (iter_v +3)->y;

                        resultant = sqrt(pow(R1,2) + pow(R2,2));

                }

        }

Consider this..............
Ok lets consider Points A[2,4], B[4,8], C[10,12], To add this vectors i add vectors/points I subtract point B x4 - A x2 and point B y8 - A y4 and point C x10 - B x4 and point C y12 - B y8 this will give me the the displacements between points....Now to get the Resultant i add all the Points X's and Y's  x's 2+4+10 = 16 y's 4+8+12 = 24, Next i would square root 16 ^2 + 24^2  = 28.84. So based on these calculations where resultant is a number not and x and y value how can i get the direction and angle....?
Comment: Off-topic. Basic math question. Look at the properties of dot products. Then summon arctangent.
Answer: It is a simple summation of vectors.
(x, y) = (x1, y1) + (x2, y2) + ... = (x1+x2+..., y1+y2+...)

When you have the final vector, it's angle is found by using
tan(angle) = y/x

Comment: To add onto this, most programming languages will have a math library function atan2() that takes two variables, y and x. This allows it to return the right quadrant of the angle.
Comment: Ok lets consider Points A[2,4], B[4,8], C[10,12], To add this vectors i add vectors/points I subtract point B x4 - A x2 and point B y8 - A y4 and point C x10 - B x4 and point C y12 - B y8 this will give me the the displacements between points....Now to get the Resultant i add all the Points X's and Y's  x's 2+4+10 = 16 y's 4+8+12 = 24, Next i would square root 16 ^2 + 24^2  = 28.84. So based on these calculations where resultant is a number not and x and y value how can i get the direction and angle....? sorry for a long comment :P
Comment: Points are not vectors. (x,y) defines the vector by it's projection lengths on x and y. You need only two numbers to define a 2D vector. If you define it by using two points A (start) and B (end), then your vector is (xB-xA, yB-yA). And then you add them as I described.
Comment: In terms of your picture, you don't care about points B, C and D at all. Your vector is (xE-xA, yE-yA)
Comment: sqrt(x^2+y^2) is a vector length.
Comment: ok i see.....so in the case of the scenerio i have presented you with :P it would be  x = 10 - 2, y = 12-4, And based on these results to get the angle of that vector in Programming i would do this: float a = 8, float b = 8........... atan2(a,b)...? and this would give me the angle of that vector right now what about the direction..?
Comment: Direction is defined by angle. In your case, you go from A to E, so it is directed from A to E.
Comment: ooo ok :) in this case you have answers all my questions now its time go dive into Visual studio C++ and amend the solutions XD much appreciated
Answer: The angle between two vectors is generally defined as:
Angle = arccos( DotProduct(v1, v2) / ( Length(v1) * Length(v2) ) );

The direction is simply subtraction of the two vectors:
Direction = v2 - v1;

Usually, you have to normalize this to get a unit vector:
Len = SquareRoot( direction.x * direction.x + direction.y * direction.y );
Direction.x /= Len;
Direction.y /= Len;

Thus, you'll have a unit direction vector and the angle of the vector.

Vector Resultant Angle and Direction


how to use colspan in VF pages

Question: i have a VF page code
            <apex:pageBlockSection collapsible="false"  columns="2" >

                <apex:inputField value="{!Opp.field1__c}"/>
                <apex:inputField value="{!Opp.field2__c}"/>
                <apex:outputField value="{!Opp.field3__c}"/>
                <apex:outputField value="{!Opp.field4__c}"/>
        </apex:pageBlockSection>

I want to have a command button inside the blockSection. Can we have something like a colspan on table to merge the first line to a single column to hold the command button?
Thanks
Prady
Comment: Please make sure to mark your questions as answered that have been answered correctly Prady, or make comments explaining why you don't feel the answer(s) are correct. Thank you.
Answer: pageBlockSection renders as a table inside a div, so once you are "inside" you can just piggyback on that schema (at least until they change how they render sections). You need two columns per section column (in your case 2x2=>4). Use the following
<apex:pageBlockSection collapsible="false"  columns="2" >

         <apex:commandButton ...>

   <apex:inputField value="{!Opp.field1__c}"/>
   <apex:inputField value="{!Opp.field2__c}"/>
   <apex:outputField value="{!Opp.field3__c}"/>
   <apex:outputField value="{!Opp.field4__c}"/>
</apex:pageBlockSection>

how to use colspan in VF pages


Does Ubuntu damage some LCD screens?

Question: I have an Acer Aspire 5732 Z, with 4 GB RAM and Pentium(R) Dual-core 2.20 GHz Processor. My graphics card is: Mobile Intel® 4 Series.
I had been using Windows since 2013, then I decided to use Ubuntu last summer (June 2015). So, I installed Ubuntu (and removed Windows 7). And I enjoyed Ubuntu for about four months (December 2015).
One day, Ubuntu started showing a low-graphics mode error... I tried to log in to my account using the command line. It says that I logged in successfully while asking me again to enter my password and username... This happened endlessly.
So, as all my work data was on GitHub, I decided to format my computer, and I installed Windows 7 again.
After working with Windows 7 for less than a month, my LCD screen started to show vertical lines (that increase in intensity over time), and nothing shows up on the screen. This never happened until I switched to Ubuntu and switched back to Windows 7 again.
So, I started using desktop screens (with a VGA cable) for about two months, then I changed the LCD display of my laptop, and it's fixed and working great now.
But, I still want to use Ubuntu. Could the LCD problem be caused by Ubuntu (or at least a specific configuration in it)?
Answer: No. It is physically impossible for an operating system to damage the LCD.
Most likely the problem was that the LCD's ribbon cable had a loose connection to the motherboard.
Either that or the display died on its own...
Comment: So, thank you ... the guy who fixed the computer told me that the problem was the LCD display itself... it's working anymore.

But, how can I fix this Low-Graphics mode error?
Comment: I really want to install ubuntu, but I'm afraid it's possible to encounter this error again.
Comment: @SmootQ - Ask Ubuntu is a Q&A site, not a forum. Therefore I would ask you to post it as a separate question.
Comment: Dont be so sure. Seems there is a problem with linux core 5.19.12. https://www.tomshardware.com/news/linux-kernel-update-kills-laptop-displays
Comment: @codelovesme Wow, that's crazy.... This answer was posted many years before that bug, though.
Comment: Nobody says that this damage is occurring because of that bug. But it supports the proposition that software can give irreversible damage to hardware and it means that the accepted answer is invalid. Just think about it next time before trying to insult people. @You'reAGitForNotUsingGit

Does Ubuntu damage some LCD screens?


start-stop-daemon error write to disk (some text)

Question: Have C++ server program that writes logs to disk.
Starting it from php script
shell_exec("start-stop-daemon -Sbvx /home/my_server.out");

inside this program:
ofstream log_file("/home/log.txt");
log_file << "some_log\n";

But there is no any log when start it as daemon :(
(when usual start ./my_server.out all works fine)
Answer: fogot close file. log_file.close(); Thats why it does not works in daemon mode. (No auto close file when daemon killed)


How to keep connection alive between two process

Question: I try to keep the connection between the two consoles alive even after a connection has been made between them. I use Microsoft libraries- Pipe.
Once the Server and the Client are connected they are automatically disconnected.

Is it possible to keep the connection alive for a few minutes?
My goal is to transfer information between the client and the server and return the information after changes have been made by the server.

https://learn.microsoft.com/en-us/windows/win32/ipc/multithreaded-pipe-server
https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-client
Comment: All questions here should have all relevant information ***in the question itself as plain text***. Links can stop working at any time making questions meaningless. Code, data, or errors shown as images cannot be copy/pasted; or edited or compiled for further research and investigation. Additionally, showing the output of unknown code doesn't really mean much. All shown code must meet all requirements of a [mre]. You can find many other questions here that explain everything in plain text, as a [mre], please use them as an example for how your question should look.
Comment: What does "Once the Server and the Client connected they are automatically disconnected" mean?
Comment: I added the image @SamVarshavchik
Comment: You keep a connection alive by not closing it. Programming works best if you understand the code you are entering into your code editor.
Answer: In Microsoft's sample code for a named pipe server (for which you provided the link), the server simply calls ReadFile once to obtain a message, then processes the message and generates a response text using GetAnswerToRequest, and then sends that response using WriteFile. Afterwards, it gracefully closes the pipe by calling:
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);

When the client has finished reading the reply message from the server, it is programmed to print the following line and to exit afterwards:
printf("\n<End of message, press ENTER to terminate connection and exit>");

In your question, you wrote the following:

Once the Server and the Client connected they are automatically disconnected.

This statement is not quite correct. As stated above, the client is programmed to exit as soon as it has finished receiving the reply from the server.
If you want to keep the connection alive for a longer period, then you can for example

reprogram the server to delay the sending of the response to the client, or
reprogram the server to process more than one message per client before closing the pipe, and reprogram the client to read more than one message from the pipe before exiting.


Installing a Heavy Sliding Barn Door into Metal Studs

Question: I'm looking to install a single, sliding barn door in the 2nd bedroom of my condo. The door is solid MDF and weighs 200 lbs, including the metal rail and sliding wheels. And being in a condo, I'm unfortunately plagued with metal studs.
To date, I've installed a 1x4x80 wood backing board across 5 metal studs, with strap toggles going through the studs. The rail is 78.75" and the door is 96x36". I'm also planning on driving two additional screws per stud, on top of and below each strap toggle, for additional support. My plan is to install the rail onto the wood backing, with the provided 4" lag bolts going through the wood/drywall.
Two questions:

Will my planned installation support 200lbs? Or should I consider cutting out some drywall and adding horizontal wood blocking in-between the metal studs?
At least one (maybe two) of the pre-drilled rail holes align with metal studs. Will I have a problem getting those to go through the metal studs behind the wood? Any best techniques for doing so?

I'm less worried about the board pulling out of the wall, and more worried about the rail pulling out of the wood. In considering how much of the 4" lag bolt will be exposed behind the drywall, here's the thicknesses of everything in-between...
<code>1/4" Rail --> 1.5" Spacer --> 3/4" Wood --> 1/2" Drywall
</code>
So, add that all up and there will be 1" of the 4" lag bolt exposed behind the drywall. Will it really make that much of a difference if that 1" were to go into wood blocking?
I'd very much appreciate any advice! Pictures below:
1x4x80 Wood Backing Installation:

4" Lag bolt with spacer (and also a lag bolt with a lag anchor, presumably for drywall only installation)
Answer: I think it'll hold, but I'd have done a couple things differently.

A taller board would've reduced the tension on your fasteners and the rotational torque on the board. I'd have gone with a 2x6 or a 5/4x6 board, or even a 1x6 if thickness is an issue. As it is you might see some gapping along the top as things flex.
Fasteners nearer the top would do the same. When you install your additional screws, put them 3/4" down. That's where most of the pullout force occurs. Picture a hinge running along the bottom of your board. If there's room, put both additional screws above the toggle bolts.

Regarding your questions...

Again, it'll hold. Worst case you get some bulging from the stud flange flexing. If you see that, make improvements.
Your lag screws will penetrate the studs fine. I assume that you'll pilot the wood and steel appropriately, which you certainly should. For 1/4" lags I'd pilot 5/32". For 5/16" lags, 3/16".
Comment: Thanks for the information and advice! I may consider swapping the current board for a 1x6 (I do want the thickness to match the existing door frame). I can probably do it pretty easily by tracing the toggle bolt screw holes onto the new board. Either way, I'll a sleep a bit better once installed. Thanks again!
Comment: Also, the lag bolt goes through the spacer in the other direction.


jquery continuous animation on mouseover

Question: I am trying to have an animation run only when the mouse is over an object. I can get one iteration of the animation and then have it set back to normal on mouse out. But I'd like the animation to loop on mouseover. How would I do it, using setInterval? I'm a little stuck.
Answer: It could be done like this:
$.fn.loopingAnimation = function(props, dur, eas)
{
    if (this.data('loop') == true)
    {
       this.animate( props, dur, eas, function() {
           if( $(this).data('loop') == true ) $(this).loopingAnimation(props, dur, eas);
       });
    }

    return this; // Don't break the chain
}

Now, you can do this:
$("div.animate").hover(function(){
     $(this).data('loop', true).stop().loopingAnimation({ left: "+10px"}, 300);
}, function(){
     $(this).data('loop', false);
     // Now our animation will stop after fully completing its last cycle
});

If you wanted the animation immediately stop, you could change the hoverOut line to read:
$(this).data('loop', false).stop();

Comment: I had to switch my answer due to problems wtih recursion. I can't seem to get you answer to work with the loopingAnimation method - if I change it to "animate", it does one iteration.
Comment: Doug, the *animate* call was missing closing parenthesis so I added it but it wasn't enough to save since you need at least 6 chars modifications so I indented your code for that purpose. FYI.
Answer: setInterval returns an id that can be passed to clearInterval to disable the timer.
You can write the following:
var timerId;

$(something).hover(
    function() {
        timerId = setInterval(function() { ... }, 100);
    },
    function() { clearInterval(timerId); }
);

Answer: I needed this to work for more then one object on the page so I modified a little Cletus's code :
var over = false;
$(function() {
  $("#hovered-item").hover(function() {
    $(this).css("position", "relative");
    over = true;
    swinger = this;
    grow_anim();
  }, function() {
    over = false;
  });
});

function grow_anim() {
  if (over) {
    $(swinger).animate({left: "5px"}, 200, 'linear', shrink_anim);
  }
}

function shrink_anim() {
  $(swinger).animate({left: "0"}, 200, 'linear', grow_anim);
}

Answer: Consider:

This is a test

with:
#anim { padding: 15px; background: yellow; }

and:
var over = false;
$(function() {
  $("#anim").hover(function() {
    over = true;
    grow_anim();
  }, function() {
    over = false;
  });
});

function grow_anim() {
  if (over) {
    $("#anim").animate({paddingLeft: "100px"}, 1000, shrink_anim);
  }
}

function shrink_anim() {
  $("#anim").animate({paddingLeft: "15px"}, 1000, grow_anim);
}

You can achieve this using timers too.
Comment: Cool solution. I'm still a novice at JS. How would I make this generic so if I had several anims, I would assume I would pass in the id in the function and then call it each time for each type? can the function() part there take parameters, and hwo would I call it for each kind, is that really the best solution?


Arranging balls in a row

Question:
Let $m$ white balls and $n$ black balls. We arrange them randomly in a row.
Let $k_1,\ldots, k_j \in\mathbb{N}$ such that $k_1 + \cdots + k_j = m$.
What's the probability the balls arrangement is:
$k_1$ white balls, 1 black ball, $k_2$ white balls, 1 black ball ...

The answer is $\frac{m!n!}{(n+m)!}$. The denominator is easy to understand, that's all the possibilities. How to understand the numerator?
Comment: As all the white balls are visually the same one, and the same for the black ones, the denominator is not what you are thinking...
Comment: are $k_i's$ fixed?
Comment: Yes, they are fixed.
Answer: Hint: The answer is $\frac{1}{\binom{m+n}{n}}$.
Comment: Oh I see where was my problem. Thank you!

Arranging balls in a row


Can't format/erase a partition on usb stick

Question: I wanted to make a bootable Windows 10 USB on my Ubuntu 16.04 Gnome and in the process of following these steps I got myself into a few problems with my 8 GB pen drive disk.

GParted does not recognize the whole 8GB as unallocated. I think another 4GB partition was created but I don't seem to able to manage it via GParted.

I get errors when trying to format disk or erase it in Disks:

When I run sudo mkfs.vfat /dev/sdb1 || sudo dd if=/dev/zero of=/dev/sdb1 bs=1M count=1 to format via command line I get the following output:
mkfs.fat 3.0.28 (2015-05-16)

I tried opening the USB disk in GParted on another laptop (running Lubuntu) and there I could see the disk formatted correctly and showing up the whole 8GB. Could it the problem be my computer's system?

How am I to repair this USB stick so I can get a working windows bootable USB?
Comment: Could you please try to format the drive on the command-line with `sudo mkfs.vfat /dev/sdb1 || sudo dd if=/dev/zero of=/dev/sdb1 bs=1M count=1` (Make sure that `/dev/sdb1` really refers to the drive that you want format! The part after `||` serves as a diagnosis in case the formatting operation fails.) and [edit] your question to include the output? Thanks.
Comment: The solution should usually be the same though: create a new partition table with Gnome Disks or any other tool.
Comment: Maybe the following link will help you analyze the problem, and let us hope, solve it, [Can't format my usb drive. I have already tried with mkdosfs and gparted](https://askubuntu.com/questions/144852/cant-format-my-usb-drive-i-have-already-tried-with-mkdosfs-and-gparted/933035#933035)
Comment: @DavidFoerster I ran it and posted the output! it didn't show much tho.
Comment: Little output or no output often means success of UNIX tools. In this case the drive was successfully formatted to FAT32 and you should be able to use it now. I don't why it wouldn't work with Gnome Disks because there appeared to be no obvious problem.
Comment: @DavidFoerster yes, it did format it to FAT32, I can see it in `Disks`, although I still can't see any difference in Gparted after refreshing devices, maybe the problem is within Gparted? Thanks!
Comment: You can use [mkusb](https://help.ubuntu.com/community/mkusb) to create a Windows install USB drive. See [this link](https://help.ubuntu.com/community/mkusb#Windows_USB_install_drive) for more details. If it does not work, there may be a problem with the USB drive itself, for example that it is 'grid-locked'. See the link in my first comment.
Comment: @DavidFoerster this post isn't answered with your other post as I have a different error when trying to format the disk.
Comment: @DavidFoerster please, note my edit 2 in my post, thanks.
Comment: If you're looking for detailed instructions for steps 1–2 of the [UEFI recipe](/a/487970)/175814 please refer to [my answer to the linked question](/a/833034/175814) and select "GPT" instead of "DOS/MBR" in step 2.
Answer: I had also problems using the standard partitioning tools. I solved it by using the program fdisk.
Install it with
sudo apt install fdisk

and then invoke it  with
sudo fdisk /dev/sd_your_usb_device

Don't forget to unmount your usb before, and DON'T manipulate your system disks!
Link on how to format a disk.
Comment: what commands did you run after entering fdisk menu?
Comment: use `lsblk` to identify your usb stick.  For instance `sudo fdisk /dev/sdb` . press m key to get help, p to print partition table! Then delete partition you don't need by pressing d, by pressing n add new partition, afterwards save and exit by pressing the x key. -- Then you have to format your disk using the `mkfs`command. YOU HAVE TO UNMOUNT YOUR DISK TO DO THAT!
Answer: I too face similar problem with Gparted. I have no Idea why this happens when I make bootable or persistent usb.
But I have easy trick. I use mkusb to format and freshly allocate pen-drive.I never gone through any terminal drill.
I hope it will work for you too.
https://help.ubuntu.com/community/mkusb
Answer: You should try another partitioning tool like GnomeDisks (gdisk), some usb sticks have very specific issues. Maybe one tool can succeed where another doesn't.
On GnomeDisks, select the usbstick and press the minus button on the right section above the partitioning table.
Comment: That doesn't seem to work either. I get: ```Error deleting partition /dev/sdb1: Command-line `parted --script "/dev/sdb" "rm 1"' exited with non-zero exit status 1: Error: Partition doesn't exist.
 (udisks-error-quark, 0)```
Comment: You could also try this command line solution:
https://askubuntu.com/questions/391654/format-a-usb-stick-completely
Also, if it doesn't work, you probably gonna need to buy another usbstick.


Mongodb Query to filter documents based on the length of a field value

Question: I am writing a AWS lambda code in python. My database is AWS DocumentDB. And I use pymongo.
This code snippet works fine
query = {"media_id": {"$exists": True}} collection.find(query)
But it returns a lot of records, so I want to fetch the records where the length of media_id field is less than 3.
For that I tried this query query = { "media_id": {"$exists": True}, "$expr: {"$lt": [{"$strLenCP": "$media_id"}, 3]},}, but I get

Feature not supported Error

because $expr is not supported in DocumentDB.
I am looking for the query which works in DocumentDB.
Answer: The solution might seems a bit tedious, but all the operations inside should be supported according to the official doc
Use an aggregation to project an auxiliary field to store the length of media_id then match on your criteria.
db.collection.aggregate([
  {
    $addFields: {
      length: {
        "$strLenCP": "$media_id"
      }
    }
  },
  {
    $match: {
      media_id: {
        $exists: true
      },
      length: {
        $gte: 3
      }
    }
  },
  {
    "$project": {
      length: false
    }
  }
])


Is there any liquid to stop leakage inside pipe or fitting

Question: i want to ask i have doubt there is a leakage in UPVC pipes or fittings but i am not able to find out this leakage is there any liquid to stop the leakage ( like i just put some kind of liquid inside pipe and leakage should be stopped) i need this liquid name? all pipes and fittings underground.
Comment: Is this a pressurized pipe (like water main) or is it a drain pipe (unpressurized)?
Comment: its UPVC Underground network (unpressurized) bell-and-spigot ends but i want to fix this problem othervise i need to broke all tieling work & Excavate the all area and expose the all network but leakage is very small.
Comment: This might be an odd question, but if it's truly underground, how do you know that it is leaking? Is there a source of the water?
Comment: yes there is drop of water because we already make gravity leak test And backfill that area with approved leak test for underground network and after that we install above ground now we have to make one more gravity leak test now water after 2 hours going down 15cm so thats why i ask this question?
Comment: If there is any type of liquid to stop this leakage othervise big loss for me and i heard this new there is one chemical to insert the hole network to to stop miner leakage ..
Answer: The honest answer is no.
There are things that will fix your problem, but they will cause more harm at the end.
It is like a pill that will only fix the problem, but have no side effects.
Your list of wants is long:
You want something that is liquid inside the pipe, find the leak inside of the pipe, and then dry inside of the pipe.
You are also looking for something that will attach and block to the pipe at the hole, but not attach to rough spots or connectors in the pipe.
It will also not harden around whatever is at the end of the pipe.
There is nothing that will only do what you want.
Your list of fixes is short:
The solution is to either put a smaller piece of pipe in the one you think leaks, and use that instead, or trace the entire pipe to find the leak.
Comment: its UPVC Underground network (unpressurized) bell-and-spigot ends  but i want to fix this problem othervise i need to broke all tieling work & Excavate the all area and expose the all network but leakage is very small.
Comment: Tile work, I would try almost anything to avoid that also. The only thing I know that will stick to UPVC is UPVC glue. A smaller pipe, wait until the leak causes damage to the wall, that you can see, or open wall.   Crazy idea, almost insane. Pull a plastic string 2 times the length of the pipe through it, tie a rag in the center, with window cleaner. Pull it back and forth a few times to clean the inside of the pipe.
Comment: Then tie on a new rag, soaked in upvc pipe cleaner through, then a final rag, soaked in upc glue, slowly through the pipe. Maybe, just maybe the glue will melt the spot with the hole. Most likely the rag or the string will get glued to the pipe, blocking it completely. You could try this, just with the glue after the 1st cleaning, a few times. This is a crazy idea, it is best to not try it. I only mention it because it came to my mind. Pull too slow, and the glue will melt the pipe, and the rag will then complete block the pipe, too fast and no glue will cover the leak. Pull without enough glu
Comment: Pull without enough glue put in the pipe before the rag, it will only get the first few meters. Pull second time before glue dries, lots of melting. Seems like only more problems with this thought, and all pipe could need replacing, and all tile opened. Bad Idea. I have them sometimes.
Answer: Much later, I see a product called Pipefuze on the Web.  I have not tried it yet, but am considering it.  About $900 for a kit with pump, sealant, etc.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Troubleshooting Garage Door Opener (GDO) safety sensors

Question: A Linear Brand GDO (model LD033) does not close unless the wired button is held down.
I believe optical safety sensors:

may have been exposed to flood water (hurricane Matthew flooding)
LEDs are not lit up as per normal ops (all LEDs dark)

UPDATE: LEDS light up: the red LED on photo-detector is dark.  Normally it is red when it detects the emitter source.
I suspect that the GDO thinks that the optical safety beam is interrupted \ broken and that is the reason why the RF opener can not close the door.
NORMAL GDO OPS:
A  separate, asymptomatic, instance of the same GDO setup was exposed to flood water but did not suffer this problem.  Observations of normal ops include visible sensor LEDs being lit up to indicate power.  Interruption of the beam results in one of the two LEDs going dark (red LED).  The symptomatic GDO's unlit \ dark LEDs in the optical safety sensors indicate either the sensors are not receiving power or are damaged.
I would like to isolate (diagnose) the problem for corrective action: is there a good troubleshooting procedure?  Any process or diagnostic questions are appreciated
Comment: Are the GDO sensor emitters on the faulty unit receiving power?
Comment: @ThreePhaseEel: update: sensor and emitter both lit up and receiving power.   Sensor seems stuck in state that signals optical-beam interrupted: tested with a known good emitter.
Answer: The receiver unit likely shorted out inside from the flooding -- it might be possible to fix it by cleaning the insides thoroughly to get rid of any contamination that'd be causing the short, but it could also be that parts inside it failed.  We'd need some photos of its innards to make that determination, though...
Comment: I like how you think.  Will put it under a fan tonight to dry it out (if that is possible).  Likely that electronics are damaged from being immersed in water.   Will report future test results and open it up if it fails.  In all likeliness: will replace it with unit from AMZN.
Answer: On the units I have worked on the emitter is usually a 2 wire and the receiver is a 3 wire . I have worked on some that are 12-24v and some that are 120v if there is voltage the emitter would be my first replacement because it should always be lit. The receiver should be lit when it sees the beam from the emitter but they both may have been damaged by the water. I looked at the web site but did not see the sensors listed.
Comment: Would it make sense to wire-up (and test) the symptomatic sensors in the known-working system or would I risk borking up the good system?
Comment: They are easy to test if the emitter is not lighting up it is not getting power or is bad, the receiver with power applied the receiver with power applied a bright flash light will usually turn on the output and it will light up. The emitters normally run from 690nm to 1064nm wavelength (red to infared) but a bright light will usually turn them on.
Comment: Emitter and receiver were removed and tested one at a time in a known good system.  Transplanted emitter passed test.  Photo-detector failed.  Unsuccessful attempt to simulate known good photo-detector with MAG-light.  Sensors are available on AMZN


apache2 and sshd are listening, but only sshd is accessible from remote

Question: I've just installed apache2 on Ubuntu (aws) using chef.

Apache2 on Ubuntu Server: 10.1.1.1
Client: 10.1.1.200

I've also verified that both tcp 22 (sshd) & tcp 80 (apache2) are listening
root@Ubuntu:/var/www# netstat -anp | egrep '22|80'
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1469/sshd
tcp6       0      0 :::80                   :::*                    LISTEN      16950/apache2
tcp6       0      0 :::22                   :::*                    LISTEN      1469/sshd
root@Ubuntu:/var/www#

Processes also look good
root@Ubuntu:/var/www# ps -ef | egrep 'apache2|sshd'
root      1469     1  0 Sep29 ?        00:00:00 /usr/sbin/sshd -D
root     16950     1  0 Sep29 ?        00:00:00 /usr/sbin/apache2 -k start
www-data 16953 16950  0 Sep29 ?        00:00:02 /usr/sbin/apache2 -k start
www-data 16954 16950  0 Sep29 ?        00:00:02 /usr/sbin/apache2 -k start
root@Ubuntu:/var/www#

Service also running as usual
root@Ubuntu:/var/www# service apache2 status
● apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: active (running) since Fri 2017-09-29 23:36:49 UTC; 2h 13min ago
     Docs: man:systemd-sysv-generator(8)
    Tasks: 55
   Memory: 6.5M
      CPU: 4.637s
   CGroup: /system.slice/apache2.service
           ├─16950 /usr/sbin/apache2 -k start
           ├─16953 /usr/sbin/apache2 -k start
           └─16954 /usr/sbin/apache2 -k start

Sep 29 23:36:47 Ubuntu systemd[1]: Starting LSB: Apache2 web server...
Sep 29 23:36:47 Ubuntu apache2[16933]:  * Starting Apache httpd web server apache2
Sep 29 23:36:48 Ubuntu apache2[16933]: AH00557: apache2: apr_sockaddr_info_get() failed for Ubuntu
Sep 29 23:36:48 Ubuntu apache2[16933]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the '
Sep 29 23:36:49 Ubuntu apache2[16933]:  *
Sep 29 23:36:49 Ubuntu systemd[1]: Started LSB: Apache2 web server.
root@Ubuntu:/var/www#

However, when I try to access the server remotely via http://10.1.1.1, nothing happen. I don't have this problem with ssh on the same server.
I've also run tcpdump when trying to access the web server from remote but I did not see anything
Test from client
[root@Client]# curl 10.1.1.1:80
curl: (7) Failed connect to 10.1.1.1:80; Connection timed out
[root@Client]#

But nothing seen on the server
root@Ubuntu:/var/www# tcpdump -nni eth0 port 80
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
^C
0 packets captured
0 packets received by filter
0 packets dropped by kernel
root@Ubuntu:/var/www#

However, when I try the same thing with ssh, I'm able to access it remotely and traffic seen on tcpdump as expected.
[root@Client]# curl 10.1.1.1:22
SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
curl: (56) Recv failure: Connection reset by peer
[root@Client]#

tcpdump on ssh
root@Ubuntu:/var/www# tcpdump -nni eth0 port 22 and host 10.1.1.200
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
02:03:04.320761 IP 10.1.1.200.35890 > 10.1.1.1.22: Flags [S], seq 1658944714, win 26883, options [mss 8961,sackOK,TS val 52461068 ecr 0,nop,wscale 7], length 0
02:03:04.320923 IP 10.1.1.1.22 > 10.1.1.200.35890: Flags [S.], seq 2270168630, ack 1658944715, win 26847, options [mss 8961,sackOK,TS val 13211819 ecr 52461068,nop,wscale 7], length 0
02:03:04.321264 IP 10.1.1.200.35890 > 10.1.1.1.22: Flags [.], ack 1, win 211, options [nop,nop,TS val 52461069 ecr 13211819], length 0
02:03:04.321287 IP 10.1.1.200.35890 > 10.1.1.1.22: Flags [P.], seq 1:80, ack 1, win 211, options [nop,nop,TS val 52461069 ecr 13211819], length 79
02:03:04.321293 IP 10.1.1.1.22 > 10.1.1.200.35890: Flags [.], ack 80, win 210, options [nop,nop,TS val 13211819 ecr 52461069], length 0
02:03:04.326160 IP 10.1.1.1.22 > 10.1.1.200.35890: Flags [P.], seq 1:42, ack 80, win 210, options [nop,nop,TS val 13211821 ecr 52461069], length 41
02:03:04.326683 IP 10.1.1.1.22 > 10.1.1.200.35890: Flags [R.], seq 42, ack 80, win 210, options [nop,nop,TS val 13211821 ecr 52461069], length 0
02:03:04.326899 IP 10.1.1.200.35890 > 10.1.1.1.22: Flags [.], ack 42, win 211, options [nop,nop,TS val 52461075 ecr 13211821], length 0
02:03:04.326911 IP 10.1.1.1.22 > 10.1.1.200.35890: Flags [R], seq 2270168672, win 0, length 0
^C
9 packets captured
9 packets received by filter
0 packets dropped by kernel
root@Ubuntu:/var/www#

Update: iptables output
Also, this box is installed on aws
root@Ubuntu:~# iptables -vL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
root@Ubuntu:~#

Comment: Do you have an ipv4 interface and an ipv6 interface? I'm not super familiar with netstat, but it looks like sshd is listening on both while the httpd is listening on just the ipv6 interface
Comment: Are you running a firewall? Add the output of `iptables -L` to your question.
Comment: Thanks Thomas & DTSCode. My question has been updated with iptables output
Answer: Apache is listening on IPv6, not IPv4:
tcp6       0      0 :::80                   :::*                    LISTEN      16950/apache2

tcp6 and :::80 are both clues that Apache is listening on IPv6, not v4 (these would be tcp and 0.0.0.0:80 otherwise).
There are many solutions to this problem.  Probably the best one is to tell Apache to explicitly listen on IPv4.  Change your Listen directive from something like this:
Listen 80

to:
Listen 0.0.0.0:80

Answer: Thanks guys for your feedback. Apparently, aws only open ssh (tcp22) for this connectivity.
Once http (tcp80) is permitted on aws, I can access this box remotely.
I knew something was blocking as nmap shows filtered on tcp80 and open on tcp22, but had no clue it was aws at that moment.
Before
Nmap scan report for 10.1.1.1
Host is up (0.062s latency).
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
80/tcp filtered  http    nginx 1.10.3 (Ubuntu)

After
Nmap scan report for 10.1.1.1
Host is up (0.062s latency).
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.10.3 (Ubuntu)


Complex numberss

Question: The solutions to the equation $x^2-(3-2i)x+(1-3i)=0$ are $a-i$ and $b-i$ where $a$ and $b$ are integers.  What is $a+b$?
$x^2-(3-2i)x+(1-3i) = (x+(a-i))(x-(a-i))$
$= x^2 - 2xi-a^2 - 1$
$1 = x^2 - 2xi - a^2$
I'm not sure where to go from here
Comment: Vieta's formula says $$a-i+b-i=3-2i$$
Comment: You can solve this using the same methods as in the answers to the [previous question you asked](http://math.stackexchange.com/questions/657927/linear-algebra-complex-numbers).
Answer: a + b - 2i = (a - i) + (b - i) = sum of roots = -[-(3 - 2i)]
Therefore, a + b - 2i = 3 - 2i
Thus, a + b = 3
Answer: Use the good, old, vanilla-flavored quadratic formula. Hint: It would certainly simplify matters if the imaginary part of the equation's discriminant were to vanish — which, happily, it does!

Complex numberss


Why is there two sets of black and white wires connected together in my wall?

Question:
Don't understand what this is, I was told it was probley a splice in the wires to extend wiring but I thought white had to be with white, black with black and ground to ground.....is this something that needs to be in a junction box ??
Comment: Is it possible that this box was at one point a light switch that was removed?  If those used to be switch loops, it would explain why black and white within the same cable are connected.
Comment: The photo shows them taped together but it is unknown whether or not they are a connection between the black and the white wires,  have you taken the black electrical tape off to see if the wires have been stripped of insulation and connected together or if the insulation was left on and they were just taped together. ??
Comment: Is any of that live?  Is this box at switch level, receptacle level, or maybe up in the attic floor?  I would not be surprised if these were wires that are no longer in use.
Comment: This definitely needs to be in a junction box, and moreover, the splice needs to use a listed connection method such as wire nuts, not just twist-and-tape.
Comment: Agree with batsplatsterson.  A non-contact voltage detector can tell you if anything is live without having to cut into the bundles, but switch loop or dead, disconnected wires are the two reasons I see.
Comment: Yes it is at switch level , I have not yet stripped the electric tape off to see if the insulation was stripped back and they are really connected .. And yes it is still live ... I wanted to get some advise before I went pulling tape off and wire butting them up to put in junction box .... now when I do the wire nuts do I leave them the way they are or do I put white with white and black with black ?? Thank ya for advise tho
Answer: It could be a switch loop, that box would be legal as a junction if a cover was installed. I would want to clean that up with wire nuts and tuck the wires in the box and add a cover.
Comment: Yes it is at switch level , I have not yet stripped the electric tape off to see if the insulation was stripped back and they are really connected .. And yes it is still live ... I wanted to get some advise before I went pulling tape off and wire butting them up to put in junction box .... now when I do the wire nuts do I leave them the way they are or do I put white with white and black with black ?? Thank ya for advise tho
Comment: The way they are is usually the best advice. I would trace them and figure out what they power or used to power.


Desktop icons shifting when external monitor is plugged in

Question: Whenever I plug in my external computer monitor for use with my Toshiba laptop, all of my desktop icons shift down. This started when I first plugged in the external monitor and since it isn't exactly level with my computer's screen, I had to go into System Settings to move the monitor up so windows would drag over correctly. When I changed my monitor arrangement, my desktop icons shifted down. Whenever I unplug the monitor, everything goes back to normal, but this is really irritating. Windows doesn't do this and Mac OS X doesn't do it either. Help? (Ubuntu 16.04 LTS, Toshiba Satellite C55-B, Dell E171FP External Monitor 1920x1280)
Answer: I have the same issue when I connect my 2nd monitor, haven't found a solution yet but I did found a workaround, there is a package called ARandR that helps. Its in Ubuntu's repository, so to install it you only need to run the following command:
sudo apt-get install arandr
Then run it using:
arandr
Once you run the command it will open a window on which you will able to position your laptop display up and down and avoid the desktop Icons moving to any extended portion. The Downside of this workaround is that once you unplug the 2nd monitor the desktop icons will shift to the extended portion of you laptop screen.


How to define a function that output another function?

Question: I want to define a function that takes some arguments as input, and uses them to make another function, then outputs the new function.
For example:
makeIncrease(n) --> return a function that takes an argument, and return (argument + n)
applyIncrease(increaseFn, m) --> will apply increaseFn to argument m
So if I do this: applyIncrease(makeIncrease(n), m) --> will return m+n
How can I do it in python?
Comment: Have you tried anything yet?
Comment: Look up python decorators
Comment: If you're doing functional programming with Python, look into the `functools` built in module. It has some useful stuff.
Comment: I tried what @Stephan described, it works like a charm XD! Will take a look into functools.
Answer: You can read about decorators in Python for more on this. For your specific question:
def applyIncrease(increaseFn, m):
    return increaseFn(m)

def makeIncrease(n):
    def _innerFn(arg):
        return arg + n
    return _innerFn

applyIncrease accepts a function and argument, and applies the function to the argument.
makeIncrease accepts an argument n.
Let's say n=2 for the sake of an example. makeIncrease(2) returns a function that takes an argument and adds 2 to it.
Although I began _innerFn with an underscore, this is only a convention - the underscore is not required for the decorator to work.
Note also that functions are first class objects in Python, and that makeIncrease returns _innerFn and not _innerFn(). Return functions exactly as you would variables or object references - no parentheses.
Here are your functions in the interpreter. Note that the object reference wrapped_function refers to _innerFn, i.e. the return value of makeIncrease(2)
>>> wrapped_function = makeIncrease(2)
>>> wrapped_function
<function _innerFn at 0x100496758>
>>> total = applyIncrease(wrapped_function, 3)
>>> total
5

Comment: Thanks you~ I just begin to understand the power of python. Take function as first class citizen is really expressive and intuitive for me to program.
Comment: Guess I need to know more coding conventions to participate open source project, because I do see lots of underscore.... I don't know how to interpret them XD.
Comment: There are some good answers on the underscore on [this question](http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python). You will see a lot of underscores in open source, especially double underscores, another useful convention. Please accept my answer if it was useful!
Answer: class Example:
    def result():
        def nestedResult(a,b):
            multiply = a*b
            return multiply
        return nestedResult

    if __name__ == "__main__":
        x = result()
        print "multiplication_result:", x(1,10)

Comment: Err, no, this does not return a function. It only _calls_ a nested function, and returns the result.
Comment: Yes, you are correct. I have now corrected the code to not actually call the inner function


Ubuntu 12.04 boot error, I/O error

Question: Ububtu is failing to boot into the gui. I have tried using boot repair but it failed to work: http://paste.ubuntu.com/5747328
I installed recommended updates yesterday.
Image of error for your reference:

Thank you for your help!
Comment: Sam - you appear to have multiple accounts.  Please click the contact-us link at the bottom of this page and request that your accounts are merged.  Thanks.
Answer: Use HDD Regenerator to solve your problem. See this video to check how to do it.
Answer: It might also be that when you were downloading the iso file, there might have been some errors. I would try and download the ubuntu iso again, reinstall, and see if that works. This issue has happened to me before too.

Ubuntu 12.04 boot error, I/O error


running maven integration tests in multi process single threaded mode

Question: I would like to run my integration tests in parallel so that:
* each test method is run by a different jvm
* and each uses a single thread
After reading the surefire docs I thought of using:
mvn test -DforkCount=2 -DreuseForks=false -Dparallel=methods -DthreadCount=1

but my tests appear to fail (of course, running just mvn test that runs them sequentially doesn't fail)
Any idea how I can achieve multi process single threaded?
Comment: First i would suggest to understand why they fail cause if those tests are unit tests they should work...Maybe you are doing not clean unit tests more integration tests...
Comment: Offtop: why do you need this?
Comment: I have some legacy code that I need to improve its performance.and some of it is not thread safe and my city is only 50% loaded.
Comment: @khmarbaise the tests are integration tests
Comment: This means using failsafe plugin instead of surefire....where you make a separate check of all integration tests and may be you need to fail the whole build...
Answer: Surefire plugin executes different classes in forkCount separate JVM processes, each JVM using threadCount threads and if parallel=methods then each method will be given a thread. In other words each fork is given a class, each method is given a thread. You cannot map between methods and forks.
From the Surefire's page, paragraph on combining forkCount and parallel:

However, you can use parallel=methods: classes are executed in forkCount concurrent processes, each of the processes can then use threadCount threads to execute the methods of one class in parallel.

TestNG has following annotation in case it could help:
@Test(threadPoolSize = 3, invocationCount = 6, timeOut = 1000)
EDIT: having just read the comments:
You have to make your unit tests correct first, and then speed the execution up.


Mystery Plastic cap/pipe in front yard

Question: Can someone please identify the purpose of this covered plastic pipe in my front yard.  I can provide further details as necessary.  I thought it was a drain clean-out, but the plumber disagreed.  In the back yard, there is a clean-out for the combined sewer/storm line.  Photos attached with cap on/off.
Answer: The cap is called a "popup emitter" and is used to cap a drain line.  When there is water pressure the center part "pops" up and allows the water to flow.
Perhaps it's from a downspout or a sump pump.  It looks as though it may be clogged up.
Popup Emitter
Answer: My neighbor has caps that look just like yours and were installed by an exterminator company. I would check with your neighbors and see if they may have the same things in their yards.
Comment: Good point, I doubt it tho.  1) he would be asking about a large quantity of these on his property.  2) the picture includes the makers name NDS which specializes in [storm water management products](https://www.ndspro.com/products/drainage/pop-up-emitters.html)
Answer: Get your garden hose and run water through any water drain lines in your back yard. If your downspouts go into buried drain lines, your basement sump, etc. Then watch and see if water comes out of this drain end.
One other option is that you have a buried french drain back there that runs to this drain end. In that case, the garden hose trick wouldn't help.
Hard to tell from the pic, but you can put a shop vac on it and try to suck out as much of the debris and standing water as possible. See if it fills back up by itself, which in that case may suggest it's from the water table under ground (french drain).
Answer: Thanks for all the responses.  It is a pop-up emitter for downspout drain line(s).  There are two downspouts in the front area of the property--one on the side of the house (same side) but the drain pipe bends to the front, and another downspout in the front (that was since abandoned/covered at ground level by previous owner).  I believe possibly both pipes connect with a Y-connection and then drain at the curb.  There is an opening at the curb on my side of the property line which is roughly in line following the downspouts
The downspouts at the rear of the house seem to feed into the sewer/storm line.  The plumber who was clearing my rear storm/sewer line thought it had to do with irrigation/sprinklers (but never pulled cap).
Comment: This place is for comments. You could add some of this info. to your question.

Mystery Plastic cap/pipe in front yard


Change notification daemon on 14.04

Question: In older versions of Ubuntu, /usr/share/dbus-1/services/org.freedesktop.Notifications.service could be edited to change the default notification daemon.
However changing this file no longer affects the default notification daemon in the newer version. Any ideas on how to change the default notification daemon?
Comment: You sure about file is exist and/or not was renamed?
Comment: sorry stupid question ... better, say please what desktop manager and desktop environment you use?
Comment: @swift, the file was not renamed or moved. The problem is that modifying this file no longer changes the notification daemon. I use the default Unity desktop environment.
Comment: there nice answer by @Magpie:
[Unity notifications messed up after installing Gnome](http://askubuntu.com/questions/451147/unity-notifications-messed-up-after-installing-gnome)
Comment: Ok I got it, Unity, however GDM or LightDM ?
Answer: It seems there is no priority or a single setting point to set which freedesktop notification daemon to run. I got such problem with XFCE installed on Ubuntu 14.04.
Unity notification launch xfce4-notifyd as it was  the default.

Check for available notification services, example:
$ grep -r org.freedesktop.Notifications /usr/share/dbus-1/services/
/usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service:Name=org.freedesktop.Notifications
/usr/share/dbus-1/services/org.freedesktop.Notifications.service:Name=org.freedesktop.Notifications

Disable non needed ones, leave only the one you want:
sudo mv /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service /usr/share/dbus-1/services/org.xfce.xfce4-notifyd.Notifications.service.disable

pkill xfce4-notifyd

Check
notify-send test

Unity notification style back (notify-osd)
Another way, Unity does not launch any default notifications daemon. So you can add the one you like to startup applications. See How do I start applications automatically on login?. I think it's better because it does not affect other desktop session that relays on the service file to start their notifications daemon.
Helpful Reference:

ArchLinux Wiki: Desktop notifications
Comment: @nealmcb, so you are looking for Gnome, Use D-feet tool and check which tool takes `org.freedesktop.Notifications` address.
Comment: This looks great, but on my Bionic 18.04 system, the grep line doesn't find any notification services. But I am properly getting notifications. Has something relevant changed in the last few releases?
Comment: This solution worked today in Ubuntu 18.04 and it was the only solution in order to stop notifications from stealing focus, I am using i3WM and after installing Budgie DE for testing, the notifications started appearing beautiful but stealing focus, which stopped the workflow so I had to do this with the budgie notification service. Thank you very much.
Comment: Ah - makes sense. My real goal is just to figure out what is showing my notifications these days so I can get it fixed so it can log timestamps and events. Amazing to me that with all the logging going on in Linux, User-visible notifications don't get logged. Any tips? The existing answers on those questions are either old (e.g. for notify-osd) or haven't worked for some other reason.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/85298/discussion-between-user-dz-and-nealmcb).
Answer: To begin need to say that behavior is reason to decide it is incorrect work of NotifyOSD with Compiz or Metacity what depends on your preferences. It can be also result of change desktop manager (alike GDM). So better solution for you will be better details what you want to do and where. "Where" is where your NotifyOSD server have works.
So if your details is Unity solutions is:
killall notify-osd
notify-osd

or if above trial was unsuccessful so you can try resolve most common environment:
sudo apt-get build-deps unity

Let's to find answer together.

Change notification daemon on 14.04


CakePHP restful API routing to a set of controllers

Question: I'm wondering if it's possible to set a route in Cakephp that will allow me to route to a set of controllers where a prefix is set. What I'm looking to do is duplicate most of my controllers but for a REST api.
I'd like to still have all the default controllers for the site itself but have a product controller for instance that only returns JSON. For this I would like to move all api controllers into a subfolder and route to them by detecting /api/controllername.
Is this possible or even the correct way to accomplish this?
Answer:
What I'm looking to do is duplicate most of my controllers but for a
  REST api.

Bad idea. IMHO. You're going to duplicate code very likely and scatter code everywhere. Keep it in one place. This sentence is an indicator that makes me think you have to much logic in your controllers. Move it to models, fat models.
There are several better ways to do this.

Use a prefix for routing to API methods inside your related controllers (api/v1/foo/bar -> ControllerName::api_actionName())
Implement a single API controller that dispatches model methods (api/v1/foo/bar -> FooModel::barMethod($queryParam1, $queryparam2,...)
Implement a service layer that sits between the model and the controllers and implement a dispatcher filter or the API controller from the 2nd suggestion to dispatch the service methods. You'll use services instead of models then. Controller <-> Service <-> Model. To implement this well some experience with the framework and design patterns is required. If its not well done  it will probably cause more problems than benefit - IMHO.
If it's a more or less simple API and the API logic is similar to your actions you can simple re-use the same controller actions you already have and just usethe built in REST and JSON/XML view serialization and could still use routing to create a fancy route (api/v1/...) for them. You can then do conditional checks as well if the controller is called as API.

It's up to you which one you pick, I've seen and used them all in action, they all work the difference is mostly the implementation and level of abstraction you need. However, the key point is to write clean and DRY code and care about SoC.


Convergence of the characteristic function

Question: Check that $$A_n \rightarrow A \iff 1_{A_n} \rightarrow 1_A$$ pointwise.
Is my proof correct?

Proof so far:
$A_n \rightarrow A \iff \limsup_{n \rightarrow \infty} A_n=\liminf_{n \rightarrow \infty}A_n=A$.
$\iff \limsup_{n \rightarrow \infty} 1_{A_n}=1_{\limsup_{n \rightarrow \infty} A_n}=1_A= 1_{\liminf_{n \rightarrow \infty} A_n}=\liminf
_{n \rightarrow \infty} 1_{A_n} \iff \lim_{n \rightarrow \infty}1_{A_n}=1_A \iff 1_{A_n} \rightarrow 1_A$ .
Comment: It looks okay to me.
Comment: @drhab Pls see my answer. I think we're supposed to have a.s.
Comment: The question is pure set theory. No measure is involved, neither in the statement nor in the proof.
Answer: I'm not sure the problem makes sensea. It seems like you are asked to prove:

Given a probability space $(\Omega, \mathscr F, \mathbb P)$, let $A_1, A_2, ...$ be events.

If $\limsup A_n = \liminf A_n := A$ and $\limsup 1_{A_n} = \liminf 1_{A_n}$, then $\lim 1_{A_n} = 1_A$
If $\lim 1_{A_n} = 1_A$, then $\limsup A_n = \liminf A_n := A$

If we change all your $\iff$ to $\rightarrow$, you've proven #1, but...
What does #2 even mean? By definition $\limsup A_n = \liminf A_n := A$.
I think #2 should be restated:

If $1_{A_n} \to 1_{\limsup A_n}$ and $1_{A_n} \to 1_{\liminf A_n}$,
  then $\limsup A_n = \liminf A_n$

which I'm not even sure is true:
We have $\lim 1_{A_n} = 1_{\limsup A_n} = 1_{\liminf A_n}$
$\to 1_{\limsup A_n} = 1_{\liminf A_n}$
$\to \limsup A_n = \liminf A_n?$
I think we merely have $\limsup A_n = \liminf A_n$ a.s.


Ubuntu 16.10 and .net core MVC Web app

Question: I try run asp.net core mvc web application with individual authorize, on Ubuntu 16.10. I have installed and succesfully set nginx. I can restore and run mvc app on this server, but I have problem with registration and login, seems to be problem with database. Web app is simply web with registration and login of users. This web app was created in Visual Studio 2017, but if I tried create Web app on Ubuntu result was same. Can you help please? So there is info:
.NET Command Line Tools (1.0.3)
Product Information: Version: 1.0.3
Runtime Environment:
OS Name: ubuntu
OS Version:  16.10
OS Platform: Linux
RID:         ubuntu.16.10-x64
Base Path:   /usr/share/dotnet/sdk/1.0.3
There is a error:
fail: Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory[1]
      An exception occurred in the database while iterating the results of a query.
      System.NotSupportedException: The keyword 'integrated security' is not supported on this platform.
         at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
         at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
         at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
         at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
         at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
         at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
         at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value()
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.d__31.MoveNext()
Comment: Can you switch to using username and password for authentication, instead of integrated security? That should solve the issue. If not, I believe there is no way to fix it on .Net Core 1.x.
Comment: Isn't the error message clear? .Net Core 1.x does not support integrated security on Linux. [It should be fixed on .Net Core 2.0.](https://github.com/dotnet/corefx/issues/4198)
Comment: So there is a way how to fix it? I can not find solution for this
Comment: I get this error on windows 10
Answer: If look at connection string specified in the appSettings.json, it refers the (localdb)\mssqllocaldb,Trusted_Connection=True; I'm not sure whether it supports mssqllocaldb, on top of it's looking for integrated security of the user who logged in.
So, in order to avoid the issue in either mac/ubuntu, we can change the db to either use in memory database (it will work if there is no migration you have to run) or sqllite database.
<code>/* In case if you want to run dotnet ef database update */
services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite("Data Source=CM-starter-4"));

/* or else */
    services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseInMemoryDatabase());
</code>
In order to make use of those, we can refer either one of those packages based on our requirement in the .csproj file.
<code> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="1.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="1.1.0" />
</code>

Ubuntu 16.10 and .net core MVC Web app