text:
Q: calling setBackgroundColor on UILabel causes crash Okay so I have been pulling my hair out, TRYING to find the cause of this problem in my code, and I've narrowed it down to a single line. The problem is, it doesn't make any sense. I create a UIViewController and put this code in the init method
- (id)init
{
    [super init];

    [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];

    iCodeAppDelegate*appDelegate = [[UIApplication sharedApplication] delegate];
    UIWindow*window = appDelegate.window;

    int headerY = appDelegate.rootNavigator.navigationBar.bounds.size.height;// + [UIApplication sharedApplication].statusBarFrame.size.height;

    //project options table
    int tableOffsetY = 250;
    UITableView* projectOptions = [[UITableView alloc] initWithFrame:CGRectMake(0, headerY+tableOffsetY, window.bounds.size.width, window.bounds.size.height-(headerY+tableOffsetY)) style:UITableViewStyleGrouped];
    projectOptions.delegate = self;
    projectOptions.dataSource = self;
    projectOptions.scrollEnabled = NO;

    [self.view addSubview:projectOptions];
    [projectOptions release];

    //xcode logo image
    int centerX = window.bounds.size.width/2;
    int logoOffsetY = 8;
    int logoScale = 200;
    UIImage* xcodeLogo = [UIImage imageNamed:@"Images/xcode_logo.png"];

    UIImageView* xcodeLogoView = [[UIImageView alloc] initWithFrame:CGRectMake(centerX-(logoScale/2), headerY+logoOffsetY, logoScale, logoScale)];
    [xcodeLogoView setImage:xcodeLogo];
    //[xcodeLogoView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];

    [self.view addSubview:xcodeLogoView];
    [xcodeLogo release];
    [xcodeLogoView release];

    //"Welcome to Minicode" text
    int welcomeLabelHeight = 50;
    UILabel*welcomeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, headerY+logoScale+8, window.bounds.size.width, welcomeLabelHeight)];
    [welcomeLabel setText:@"Welcome to miniCode"];
    [welcomeLabel setTextColor:[UIColor darkGrayColor]];
    [welcomeLabel setTextAlignment:UITextAlignmentCenter];
    [welcomeLabel setBackgroundColor:[UIColor clearColor]];
    [welcomeLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 24.0f]];
    [self.view addSubview:welcomeLabel];
    [welcomeLabel release];

    return self;
}

The problem lies in this specific line:
[welcomeLabel setBackgroundColor:[UIColor clearColor]];

if I comment it out, the code works fine, except that the label has a big white box behind it. I've scoured the internet, and it appears only one person has had a similar problem. The solution doesn't seem to have any sort of application to my code, however.


text:
Q: jQuery custom function - this.each I need some help regarding a jQuery plugin I'm creating.
$.fn.mymethod = {
  init : function(options){

      this.each(function() {
          var settings = {  };
          if(options){ $.extend(settings, options); }

      });

      return this;
  }
}

$("input[type=text]").mymethod.init();

It doesn't seem to work, I get an error:
TypeError: this.each is not a function on line
I hope someone can point me in the right direction.
Thanks!

A: You will want to do it this way without the extra level of object reference:
$.fn.mymethodInit = function(options){

      this.each(function() {
          var settings = {  };
          if(options){ $.extend(settings, options); }

      });

      return this;
}

When you interject the extra object in the way as in your original proposal, that means it then has to be called as:
$(...).mymethod.init()

And, calling it that way, means that the this pointer is mymethod, not the jQuery object which you need it to be.  This is just a consequence of how Javascript sets the this pointer when you call foo.bar.method().
There are some work-arounds, but all are generally ugly and complicated so just give up the extra level of the dot syntax.  A common work-around is to just use a common prefix on all your methods:
$.fn.mymethod_Init = function() {...}
$.fn.mymethod_Save = function() {...}

which is just as unique a namespace as you were attempting to use, but does not create the problem you ran into.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas datetime convert & filter issue I am using Pandas 0.8.1 to fetch Yahoo stock price
from datetime import datetime
from pandas.io.data import DataReader

stk_price = DataReader('600809.ss', 'yahoo', datetime(2006,1,1), datetime(2012,12,31)).reset_index()

>>> stk_price.Date
0    2010-01-04 00:00:00
1    2010-01-05 00:00:00
2    2010-01-06 00:00:00
3    2010-01-07 00:00:00
4    2010-01-08 00:00:00

And I want to convert the Date to string by:
>>>stk_price.Date.astype('|S10')
0     1970-01-15
1     1970-01-15
2     1970-01-15
3     1970-01-15
4     1970-01-15
5     1970-01-15

Why it shows "1970-01-15" instead of "2010-01-04" etc ? How to fix it?
And if I have a
DATE_LIST = [
 u'20090331', u'20090630', u'20090930', u'20091231', \
 u'20100331', u'20100630', u'20100930', u'20101231', \
 u'20110331', u'20110630', u'20110930', u'20111231', \
 u'20120331', u'20120630', u'20120930', u'20121231'
 ]

I just try to filter the rows of stk_price whose Date column is in DATE_LIST by below:
from datetime import datetime
from pandas.io.data import DataReader
import numpy as np

DATE_LIST = [
 u'20090331', u'20090630', u'20090930', u'20091231', \
 u'20100331', u'20100630', u'20100930', u'20101231', \
 u'20110331', u'20110630', u'20110930', u'20111231', \
 u'20120331', u'20120630', u'20120930', u'20121231'
 ]

DATE_ARRAY = np.array(DATE_LIST,dtype='datetime64[us]')
stk_price = DataReader('600809.ss', 'yahoo', datetime(2006,1,1), datetime(2012,12,31)).reset_index()
rst = stk_price[stk_price.Date.isin(DATE_ARRAY)].Close

but the rst is empty .
How to fix it or any Pandas function can filter the result ?

A: use df.Date=df.Date.apply(lambda x:x.date()) to convert the datetime column
>>> df=DataFrame({'Date':[datetime(2006,1,1)]})
>>> df
                  Date
0  2006-01-01 00:00:00
>>> df.Date=df.Date.apply(lambda x:x.date())
>>> df
         Date
0  2006-01-01

EDIT:
to format DATE_LIST
dates=[datetime.datetime.strptime(i, "%Y%m%d").date() for i in DATE_LIST]

and finally use isin to filter out the rows that are in DATE_LIST:
df[df['Dates'].isin(dates)]

in one go(given that you have stk_price dataframe that has a datecolumn called Date):
import datetime

stk_price = DataReader('600809.ss', 'yahoo', datetime(2006,1,1), datetime(2012,12,31)).reset_index()
stk_price.Date=stk_price.Date.apply(lambda x:x.date())
dates=[datetime.datetime.strptime(i, "%Y%m%d").date() for i in DATE_LIST]
stk_price[stk_price['Dates'].isin(dates)]

A: Instead of converting stk_price dates to strings (which shows the wrong dates due to a numpy bug, see also github issue #1802) you can also convert the DATE_LIST to timestamps and use these directly to index stk_price. Below an example on frame containing random data.
In [16]: DATE_LIST = [
 u'20090331', u'20090630', u'20090930', u'20091231', \
 u'20100331', u'20100630', u'20100930', u'20101231', \
 u'20110331', u'20110630', u'20110930', u'20111231', \
 u'20120331', u'20120630', u'20120930', u'20121231'
 ]

In [17]: timestamps = [pd.Timestamp(date) for date in DATE_LIST]

In [18]: df = pd.DataFrame(np.random.randn(100,3), index=pd.date_range('20090331', periods=100))

In [19]: df.ix[timestamps].dropna()
Out[19]:
                   0         1         2
2009-03-31  0.520235  1.158889 -0.310227
2009-06-30  1.036449  0.528931 -0.083166


text:
Q: Nodejs The "listener" argument must be of type function i am trying to use event handlers and want to make a online and offline function, but I get this error message: The "listener" argument must be of type function.
Can anyone explain why it happens?
app.js
'use strict';

const events = require('events');

const eventEmitter = new events.EventEmitter();

const checkStatus = require('./connection');

const connectionData = checkStatus({
    host: 'www.google.de',
    port: 443
}, (err, content) => {

    if(err) {
        return console.log(err.message);
    }

    console.log(content);

});

eventEmitter.on('status', connectionData);

connection.js
'use strict';

const needle = require('needle');
const events = require('events');
const eventEmitter = new events.EventEmitter();
const checkStatus = (options, callback) => {

    needle.get(`https://${options.host}:${options.port}`, (err, content) => {

        if(err) {
            return console.log(err.message);
        }
        eventEmitter.emit('status');

        callback(null, 'Content Success');

    });

}

module.exports = checkStatus;

A: In connection.js your function checkStatus = (options, callback) => {...} does not return a function which should've then be passed as the listener connectionData  to  eventEmitter.on('status', connectionData).
To fix this try converting connectionData to a function
// ...
// converted your code to occur inside a function

const connectionData = () => {
    checkStatus({
        host: 'www.google.de',
        port: 443
    }, (err, content) => {

        if (err) {
            return console.log(err.message);
        }

        console.log(content);

    })
};

eventEmitter.on('status', connectionData);


text:
Q: How to check if a Simple HTML element does not exist? SimpleHtmldom can be used to extract the contents of the first element with class a[itemprop="item"]
$html = str_get_html($html);
$item = $html->find('a[itemprop="item"]', 1)->innertext;

However if this class does not exist, PHP will throw an error

Trying to get property of non-object

How can I fix this?

A: Please check whether the element exists first:
// Create DOM from URL or file
$html = str_get_html($html);

if (($html->find('a[itemprop="item"]', 1))) {
$item = $html->find('a[itemprop="item"]', 1)->innertext;
}else{
$item = "element not exist";
}


text:
Q: How do I annotate a class that extends a HashMap for XML Marshalling How do I annotate a class that extends a HashMap for XML Marshalling using JAXB.
This example code
@XmlAccessorType(XmlAccessType.FIELD)
public class ExampleMap extends HashMap<String,String>{

   public String group= "Test Group";

}

Produces this xml
<ExampleMap>
  <group>Test Group</group>
</ExampleMap>

I can modify the class to this
@XmlAccessorType(XmlAccessType.FIELD)
public class ExampleMap extends HashMap<String,String>{

    public String group= "Test Group";
    public Map<String,String> self = this;

}

and I now get
<ExampleMap>
  <group>Test Group</group>
  <self>
    <entry><key>2</key><value>2</value></entry>
    <entry><key>1</key><value>1</value></entry>
  </self>
</ExampleMap>

Which is the result I want, but using that self referencing Map<String,String> self = this; feels wrong.
How should it be done?

A: Turns out that although it felt wrong, it is in fact a bonafide way of doing it.
Although this answer https://stackoverflow.com/a/4152683/3696510 uses a get method to return 'this' the results are the same.


text:
Q: How would I use Apple's IOS 8 private API for non-jailbroken devices for ad-hoc business distribution? Specifically, turning on Wifi or Cellular Data As the question suggests, I'd like to know how I can use private API in private, company IOS 8.1 - 8.1.2 app. It will NOT be going through the app store. I need to have programmatic control over airplane mode, wifi, bluetooth, and cellular data. I've read online over and over again that it's not possible, but I can't believe this to be true. I've tried creating an NSObject category and simply pasting the method I want to use to turn on wifi. However, I keep getting a Matcho-Link Error. I have added the corresponding 'sharing' framework to the library, so not sure what the problem is.
My Category
@interface NSObject (Wifi)
- (void)setWifiEnabled:(BOOL)arg1;
@end

My ViewController's Interface
    #import <UIKit/UIKit.h>
#import "NSObject+Wifi.h"
@interface ViewController : UIViewController

@end

Viewcontroller's Implementation
    #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)enableWifi:(UIButton *)sender {
    NSObject * wifi = [[NSObject alloc]init];
    [wifi setWifiEnabled:YES];
}

@end

Error Message:
ld: framework not found Sharing
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Again, the 'Sharing.framework' is added and linked to project and I've checked "Copy files if needed". How do I get passed this error?

A: That isn't how private APIs work. Sorry.
You can't just make up a method name for the feature you want; you need to define and call a class and/or method that matches with code that already exists in Apple's frameworks. Finding these classes/methods is the difficult part, and tends to involve a lot of poring through disassembly. Long story short, it's a nontrivial task.
There is apparently a method with a similar name on the SBWiFiManager class, although I can't confirm whether that still works. (It might not; undocumented interfaces are subject to change.) You might want to give that a try.
In any case, the Sharing framework you tried to link against is completely unrelated. Remove it from your project.


text:
Q: Prove $\int_a^b f(x)\,\mathrm dx>0$ if $f(x)>0$ at $\forall x\in [a,b]$ and Riemann integrable (via finite covering theorem). Given $f$ is Rimann integrable on $[a,b]$, and $f(x)$ is positive at $\forall x \in [a,b]$. Using Heine-Borel's finite covering theorem to prove $\int_a^b f(x) \,\mathrm{d} x>0$.

A: I have a proof using Closed interval theorem:
Because $\int_a^b f$ is exists, the upper sum
$$\sum M_i\Delta x_i \to \int_a^b f$$
when $\lambda=\max_i\Delta x_i\to0$. If the $\int_a^b f =0$ we have an interval $[a_1,b_1]:=[x_{j},x_{j+1}]$, on it
$$\sup_{x\in[a_1,b_1]} f(x)=M_i<1.$$
Due to the $f$ is still integrable on $[x_j,x_{j+1}]$ we could find the second interval $[a_2,b_2]\subsetneqq[a_1,b_1]$, for which
$$\sup_{x\in[a_2,b_2]}f(x)<1/2.$$
By induction we have $[a_n,b_n]_{n\in\mathbb N}$ satisfied:

*

*$[a_n,b_n]\subsetneqq[a_{n+1},b_{n+1}]$;

*$\sup_{x\in[a_n,b_n]}<1/n$;

*$b_n-a_n\to0$.

So $\lim b_n=\lim a_n=x_0$, and $f(x_0)=0$, it's a contradiction!
But, how to prove the proposition by finite covering theorem?


text:
Q: Не отправляется почта с сайта на почтовый сервер webmail На сервере настроены MX записи для отправки почты на ящик созданный в webmail,
имя ящика имеет вид example@finestra.biz

Если с простых почтовиков слать на этот ящик письма то проблем нет, а вот если с сервера на котором лежит сайт, то нечего не происходит, например даже просто через mail(example@finestra.biz,"test","test") проблема в неправильной настройке MX записей?
Или что то еще может быть?
До этого говорят почта вроде работала и еще знаю что ящик сей настроен с каким то почтовым клиентом,но это не как же влиять не может на работу ящика ? Скорее всего что на сервере у нас не правильно настроено?


text:
Q: Serial edit approving; a problem? Well, while approving edits today.. in my opinion I came across a slight problem.  Users serial-approving edits without even checking the content.
I question whether there should be some sort of penalty for this.. if x amount of approvals a user has made have been rejected by every other user doing the approval at the time... lock the privilege or something?
For the record, I do understand there are various other questions regarding this very same thing, however in my reading, while there were propositions for dealing with such..  what I had in mind didn't seem to appear.

A: Let's stop with the calling out of specific users. This sort of public shaming never ends well and it looks like a few folks here have already started retaliating.
Just flag one of the user's posts, explain what you're seeing, and let the moderators handle this privately.
For what it's worth, we already have an audit system in place that blocks folks from /review if they fail too many audits.


text:
Q: Invalid input focus is not working with FormArray So everything works fine with normal FormGroup but when it comes to FormArray it doesn't focus the invalid input.
My form initialization is below
initForm() {
    this.parentForm= this.fb.group({
      childFormArray: this.fb.array([this.createchildForm()])
    });
  }

after this, I initialize formarray like below
createChildForm(data?: any): FormGroup {
    var childForm = this.fb.group({
      name: [data?.name? data?.name: '']
    });
    childForm .valueChanges.subscribe(value => {
      var fieldWithValue = Object.keys(value).filter(key => value[key] == '');
      fieldWithValue.forEach(conName => {
         childForm .get(conName)?.addValidators([Validators.required]);
      });
    });
    return childForm ;
  }

My method to set errors after clicking submit (requirement);
   assignError(){
    this.parentForm.controls.childFormArray.value.forEach((v: any, index: number) => {
          var array = this.parentForm.controls.childFormArrayas FormArray;
          var item = array.at(index);
          var emptyItems = Object.keys(v).filter(key => v[key] == '');
          emptyItems.forEach(ele => {
            if (ele != "section") {
              item.get(ele)?.updateValueAndValidity({ emitEvent: false });
            }
          });
        });
       }

and after this I have made my validator which will check for invalid input and focus it.
import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
    selector: '[focusInvalidInput]'
})
export class FormDirective {
    constructor(private el: ElementRef) { }
    @HostListener('submit')
    onFormSubmit() {
        const invalidControl = this.el.nativeElement.querySelector('.ng-invalid');
        if (invalidControl) {
            invalidControl.focus();
        }
    }
}

after this I have used its selector in my corresponding form
focusInvalidInput (ngSubmit)="saveDetails()"

and inside submit method I call my error adding method which is
 saveDetails(){
  assignError();
}

After doing all this I am able to focus invalid input but somehow its not working for formarray.
and when I console invalidControl its prints all the invalid input which should not happen maybe bcz there are many invalid input and whome should it focus so I tried using .first() method but it gives error saying first is not a method

A: The actual reason was focus doesn't work on div and my input which were using formArray's controls were wrapped inside a div which is

                                    <input type="text" class="form-control no_shadow_input" id="name"
                                        placeholder="Enter Here" formControlName="name" autocomplete="off">

                                        Name is required

So all I had to change is add input.ng-invalid in my directive
const invalidControl = this.el.nativeElement.querySelector('input.ng-invalid');

Now everything is working fine


text:
Q: How to access a service inside TemplateRef which was provided in parent component? Recently I had a task where I needed to pass a TemplateRef to component, which provides some service, say SomeService. And inside that template I used a directive that injects service SomeService. I ended up with NullInjectorError.
So my question is how can I get service provided in component but not inside ViewContent.
Here is minimal representation of what I'm trying to do. Let's assume that all components and directives are declared in the same module.
root-component. All that's happening here is that I'm passing a template reference to the app-component and use the directive inside template.
@Component({
    selector: 'root-component',
    template: `
    <app-component [itemTemplate]="template"></app-component>

    <ng-template #template >

hello

    </ng-template>
    `
})
export class RootComponent {
}

app-component. Here I provide SomeService
@Component({
    selector: 'app-component',
    template: `
        <ng-container [ngTemplateOutlet]="itemTemplate"></ng-container>
    `,
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [
        SomeService // <-- HERE IS THE SERVICE THAT I'M TRYING TO INJECT INTO DIRECTIVE
    ],
})
export class AppComponent {
    @Input()
    itemTemplate: TemplateRef<unknown> | null = null;

    constructor(
    ) {

    }
}

testDirective
@Directive({
    selector: '[testDirective]'
})
export class TestDirective {
    constructor(
        private _someService: SomeService // <-- THIS CAUSE AN NullInjectorError
    ) {
    }
}

There is no need to show the implementation of SomeService as it is just a regular service.
I apologize if something is not clear, this is my first question on StackOverflow
Stackblitz here

A: Angular v14 solution
With Angular 14, you can pass injector to ngTemplateOutlet directive. And by that way, the embeddedView that is going to render inside ng-container will refer to the current component injector tree (and point to injected SomeService provider on the component level.
@Component({
  selector: 'app-component',
  template: `
      <ng-container
        [ngTemplateOutlet]="itemTemplate"
        [ngTemplateOutletInjector]="injector">
      </ng-container>
  `,
  ...
})
export class AppComponent {
  @Input()
  itemTemplate: TemplateRef<unknown> | null = null;

  constructor(
    public readonly injector: Injector
  ) {}
}

Angular v13 or less
You have to make some changes in the way the template has been passed. Rather than passing TemplateRef as Input binding. Pass that ng-template as a Content Projection.
@Component({
  selector: 'root-component',
  template: `
  <app-component>

    <ng-template #template>

hello

    </ng-template>
  </app-component>
  `,
})
export class RootComponent {}

And then AppComponent can use @ContentChild to lookup for that transcluded view (ng-template) thing checking #template template variable. And that's it. itemTemplate will fill in as soon as ContentChild query retrieves the result. Boom
@Component({
  selector: 'app-component',
  ...
})
export class AppComponent {
  // VVVV change here to ContentChild
  @ContentChild('template')
  itemTemplate: TemplateRef<unknown>;
}

In this case, the template is a part of AppComponent, and the injector tree resolves the SomeService correctly.
Demo


text:
Q: NUnit Addins with Resharper 5 The latest Resharper (v5) version is based on native NUnit code and allows NUnit addins.
I have a NUnit addin that works fine in NUnit GUI but I can not make it work with Resharper. Based on R# indication I have put my addins library in %ResharperPath%\Bin\addins but I doesn't work, my tests are marked as Ignored.
Question: How to use NUnit addins with ReSharper?

A: Unfortunately, ReSharper's test runner doesn't support NUnit add-ins. It's been requested, but hasn't been added, not even to the forthcoming ReSharper 6. (Feel free to vote for the feature request to let them know there's interest -- I just did.)
We use an NUnit add-in for some of our tests, and those tests don't show up in ReSharper at all -- no gutter icons, nothing in the Unit Tests window, nothing. Our only option is, when we want to run those tests, to fire up the NUnit GUI. It's a pain.

A: Now ReSharper supports NUnit addins. Try this link:
http://blogs.sourceallies.com/2013/06/nunit-addins-that-works-with-resharper/
Also you need to change default settings in resharper:
http://i.imgur.com/2qT0y2U.png
Options -> Tools -> Unit Testing -> NUnit
Load NUnit Addins -> Always
and copy dll with Addin to C:\Users...\AppData\Local\JetBrains\Installations\ReSharperPlatformVs12\addins
Also your dll with tests (not with addin) must not contain NUnit.AddinsDependencies package


text:
Q: Why is my recursive Fibonacci implementation so slow compared to an iterative one? I have created the following simple Fibonacci implementations:
#![feature(test)]
extern crate test;

pub fn fibonacci_recursive(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
    }
}

pub fn fibonacci_imperative(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        _ => {
            let mut penultimate;
            let mut last = 1;
            let mut fib = 0;
            for _ in 0..n {
                penultimate = last;
                last = fib;
                fib = penultimate + last;
            }
            fib
        }
    }
}

I created them to try out cargo bench, so I wrote the following benchmarks:
#[cfg(test)]
mod tests {
    use super::*;
    use test::Bencher;

    #[bench]
    fn bench_fibonacci_recursive(b: &mut Bencher) {
        b.iter(|| {
            let n = test::black_box(20);
            fibonacci_recursive(n)
        });
    }

    #[bench]
    fn bench_fibonacci_imperative(b: &mut Bencher) {
        b.iter(|| {
            let n = test::black_box(20);
            fibonacci_imperative(n)
        });
    }
}

I know that a recursive implementation is generally slower than an imperative one, especially since Rust doesn't support tail recursion optimization (which this implementation couldn't use anyways). But I was not expecting the following difference of nearly 2'000 times:
running 2 tests
test tests::bench_fibonacci_imperative ... bench:          15 ns/iter (+/- 3)
test tests::bench_fibonacci_recursive  ... bench:      28,435 ns/iter (+/- 1,114)

I ran it both on Windows and Ubuntu with the newest Rust nightly compiler (rustc 1.25.0-nightly) and obtained similar results.
Is this speed difference normal? Did I write something "wrong"? Or are my benchmarks flawed?

A: The algorithmic complexity between the two implementations differs:

*

*your iterative implementation uses an accumulator: O(N),

*your recursive implementation doesn't: O(1.6N).

Since 20 (N) << 12089 (1.6N), it's pretty normal to have a large difference.
See this answer for an exact computation of the complexity in the naive implementation case.
Note: the method you use for the iterative case is called dynamic programming.

A: As said by Shepmaster, you should use accumulators to keep the previously calculated fib(n - 1) and fib(n - 2) otherwise you keep calculating the same values:
pub fn fibonacci_recursive(n: u32) -> u32 {
    fn inner(n: u32, penultimate: u32, last: u32) -> u32 {
        match n {
            0 => penultimate,
            1 => last,
            _ => inner(n - 1, last, penultimate + last),
        }
    }
    inner(n, 0, 1)
}

fn main() {
    assert_eq!(fibonacci_recursive(0), 0);
    assert_eq!(fibonacci_recursive(1), 1);
    assert_eq!(fibonacci_recursive(2), 1);
    assert_eq!(fibonacci_recursive(20), 6765);
}

last is equivalent to fib(n - 1).
penultimate is equivalent to fib(n - 2).


text:
Q: using another javascript class within a different class In Swift I can instantiate one class within another as a property and call its methods using something like:
newClass.anotherClass.methodInTheOtherClass();

I am unable to do that in JavaScript. The following code produces an error in this line:
var cowCommunication = new CowCommunication();

What is the proper way to achieve this goal, and make the following script work?
<html >
  <script type = "text/javascript" >
  let CowCommunication = {
    sayMoo: function() {
      alert("hey");
    }
  };
let farmTools = {
  var cowCommunication = new CowCommunication();
};
farmTools.cowCommunication.sayMoo();

</script>
</html >

This is a real example of code I am actually trying to make work.

A: let farmTools = {
  cowCommunication : new CowCommunication(),
};

Not
let farmTools = {
  var cowCommunication = new CowCommunication();
};

Also :
class CowCommunication  {

    sayMoo() {
      alert("hey");
    }
}

Not :
let CowCommunication = {
    sayMoo: function() {
      alert("hey");
    }
  }

A: You can also use composition instead of Classes.
let cowCommunication = {
    sayMoo: function() {
      console.log('hey')
    }
};

const farmTools = function() {
  return Object.assign({}, cowCommunication)
}

let instance = farmTools()

instance.sayMoo()


text:
Q: Appcelerator Module - Instantiate UIViewController with .xib? I'm having problems instantiating a UIViewController with it's .xib.
My Code looks like this: ( actually, just look here: https://github.com/mrtnbroder/titanium-module-test )
- (void)open:(id)args
{
    ENSURE_UI_THREAD(open, args);

    CustomViewController *viewController = [[CustomViewController alloc] initWithNibName:@"CustomViewController" bundle:nil];

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];

    [[TiApp app] showModalController:navigationController animated:YES];
}

and my .xib file is named CustomViewController.xib
and looks like this:

however, when I build it, my App looks like this:

why? what's wrong?

A: The problem is that your nib is not in the main bundle. You should first copy all your nibs into a folder into module_folder/assets .
Rename that folder something like Titanium.bundle.
So your directory struction will look like module_folder/assets/Titanium.bundle
This will make sure your nib gets copied into the module when it gets compiled.
I make a category on NSBundle like this:
//Shortcut if you want to name the bundle Titanium you'll be ahead of the game
+ (NSBundle *)titaniumBundle
{
    return [NSBundle titaniumBundleWithName:@"Titanium"];
}

//Bundles are put in a folder called modules inside the application's main bundle
+ (NSBundle *)titaniumBundleWithName:(NSString *)bundleName
{
    //Change this to accommodate the module's id
    static NSString *appId = @"com.companyname.module";
    NSString *bundlePath = [NSString stringWithFormat:@"modules/%@/%@.bundle", appId, bundleName];
    bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundlePath];

    return [NSBundle bundleWithPath:bundlePath];
}

Then you're going to include that category in the file you're using and code this up:
 CustomViewController *viewController =
   [[CustomViewController alloc] initWithNibName:@"CustomViewController"
                                          bundle:[NSBundle titaniumBundle]];

Then you'll at least be loading the view from the right directory.

A: are you doing with sotryboard??
if not than check your didFinishLaunchingWithOptions method in AppDelegate
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];

A: This line:
  CustomViewController *viewController =
       [[CustomViewController alloc] initWithNibName:@"CustomViewController"
                                              bundle:nil];

suggests you should call your xib file "CusomViewController.xib".
update
With your question edit (and your comments) you reveal that you are developing a module for Appcelerator Titanium.
From what I can gather, Titanium does not use Xib files or viewControllers (it uses 'View Proxies' instead). According to this answer, using Xib files in Titanium is a very convoluted process:

You need to convert your XIB to a NIB. The easiest way is to add the XIB to a native project, compile the project, and then pull out the NIB. Dump it in the assets for the module, and then reference it from your module code. ... Note that we usually don't use NIBs unless we have something from a third party that forces us to. It's easier just to create the views imperatively rather than declaratively.

As I only know native, not Titanium, I cannot help you further with this. But I suggest that you follow the Titanium documentation, and don't confuse it with native iOS development.

A: First of all in your xxxmodule.m
    -(void)startup
    {
        // this method is called when the module is first loaded
        // you *must* call the superclass
        [super startup];

        yourViewController *controller = [[yourViewController alloc] init];
        controller.delegate = self;
[[TiApp app] showModalController: controller animated: YES];

    }


text:
Q: how to escape double quotes inside a json I'm trying to create a JSON file which will hold a regular expression.
for example:
    {
    "FrameworksData": [{
            "name": "jquery",
            "regexes": ["script\s+src\s*=\s*\"jquery", "b", "c"],
            "extensions": [".js"],
            "conditions":"t1=r1||r2||r3; t2=t1&&e1; res=t2;"
        }
    ]
}

I need to use the double/single quotes as part of the regex that is located inside the JSON. However this JSON is not valid as a result of the structure \"jquery.
how do I use the single quotes and the double quotes in the JSON so I can achieve the correct regex?
Thanks!

A: Multiple techniques can be adopted:

*

*Escape the backslash \ i.e to \\. For scripted escaping you can use this solution
"FrameworksData": [{"regexes": ["script\\s+src\\s*=\\s*\"jquery", "b", "c"]}]

*You can use encodeURIComponent to transfer the regexes if you don't want to escape.


text:
Q: How to select SQL Server data based on today's date and time? I'm using SQL Server to COUNT some data which originates from a HTML table. I want to COUNT total rows in the database based on today's date. And then after the date hits tomorrow's date, to set the COUNT value back to zero and to restart the count back from the start.
Is there a query that can help me fetch data based on current date and time?
Something like this:
SELECT COUNT(data_id)
FROM table1
WHERE clock_time BETWEEN 000000 AND 235959
  AND date_time IS TODAY's DATE (or something like that)
GROUP BY XXX
ORDER BY XXX

After the clock hits tomorrow's date, I want to reset the COUNT back to zero, and to start a new count back from 00:00:00.
I know there is NOW() query but as far as I know it only shows the date.
Someone told me I could use WHERE DATE(date)=CURDATE() but the SQL Server won't work with that.
Thank you...

A: You can use convert function like this
where convert(Date,date_time)= CONVERT(Date,GETDATE())

A: Need not to use time as you want today's data.
Try this one
SELECT COUNT(data_id) FROM table1
WHERE convert(date,date_time) = getdate()


text:
Q: Cannot find FakeInput I am trying add a fake input to simple_form using the following suggestion (rails simple_form fields not related to the model), but it does not work for me.
This is my HAML code for adding a fake input field.
= f.input :agrees_to_terms, :as => :fake

I put the following class in app/inputs/fake_input.rb
class FakeInput < SimpleForm::Inputs::StringInput
  # This method only create a basic input without reading any value from object
  def input
    template.text_field_tag(attribute_name, nil, input_html_options)
  end
end

I get the following runtime error
No input found for fake

I have two initializers that were generated by Rails Composer: simple_form.rb and simple_form_bootstrap.rb
How can I make Rails find my FakeInput class?

A: I had the same issue, and a server restart resolved it.


text:
Q: Get all the rows with max value in a pandas dataframe column in Python I have a pandas dataframe with following columns.
col1  col2  col3   col4
A101  3     LLT    10028980
A101  7     LLT    10028980
A101  7     PT     10028980
A102  5     LLT    10028981
A102  3     PT     10028981
A103  2     PT     10028982
A103  4     LLT    10028982

I would like to extract all those rows where col2 is max for each value of col1. The expected output is:
col1  col2  col3   col4
A101  7     LLT    10028980
A101  7     PT     10028980
A102  5     LLT    10028981
A103  4     LLT    10028982

I am using following lines of code but it is filtering the rows where there are multiple rows with max value (row 1 is excluded).
m = df.notnull().all(axis=1)
df = df.loc[m].groupby('col1').max().reset_index()
I am getting this output:
col1  col2  col3   col4
A101  7     PT     10028980
A102  5     LLT    10028981
A103  4     LLT    10028982

A: You can widen the maximum per group with transform, check equality against it to detect maximums and index with that mask:
>>> df.loc[df["col2"].eq(df.groupby("col1")["col2"].transform("max"))]

   col1  col2 col3      col4
1  A101     7  LLT  10028980
2  A101     7   PT  10028980
3  A102     5  LLT  10028981
6  A103     4  LLT  10028982

here's what .agg would do:
>>> df.groupby("col1")["col2"].agg("max")
col1
A101    7
A102    5
A103    4
Name: col2, dtype: int64

and what .transform does
>>> df.groupby("col1")["col2"].transform("max")

0    7
1    7
2    7
3    5
4    5
5    4
6    4
Name: col2, dtype: int64

which allows for an element-wise comparison with the col2 column.


text:
Q: Import sales_flat_order table from one db to another db Is it possible to import the data of sales_flat_order table to existing database from another database. Can anyone kindly guide me. Thanks in adv.
PS: By mistake I deleted all my orders at the back end. I require all the orders back. It is present in another db. However do I have to replace the entire db or just the sales_flat_order table alone can be replaced.

A: You should not attempt to do this via a direct database transfer. If you want to import/export orders you should look at a way to do this programmatically as you will run into issues in the database.
I would recommend this extension to accomplish what you are trying to do
http://www.magentocommerce.com/magento-connect/dataflow-batch-import-export-orders-to-csv-xml.html


text:
Q: Problems creating matrices from user input in C++ I'm trying to just make a simple program where the user inputs every value of a matrix, then the program prints the matrix. So far I have
#include <iostream>

using namespace std;
int main()
{
    int n;
    cout << "A is an nxn matrix.\nn=";
    cin >> n;
    int matrix[n-1][n-1];
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            cout << "A[" << i+1 << "][" << j+1 << "]=";
            cin >> matrix[i][j];
        }
    }
    cout << "[[ ";
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<n;j++)
        {
            cout << matrix[i][j] << " ";
        }
        if (i!=n-1) //Just to make the output pretty
            cout << "]\n [ ";
        else
            cout << "]]";
    }
}

`
However, whenever I put in a matrix of any size, for instance [[1,2,3][4,5,6][7,8,9]], the program returns [[1,2,4][4,5,7][7,8,9]].
Can anyone tell me why this is happening and how to fix it?

A: You're getting an undefined behavior for accessing out of range in matrix[i][j] when i or j equals n-1 for your matrix declared as matrix[n-1][n-1]
Use:
int matrix[n][n]; // will say 0 to n-1
instead of
int matrix[n-1][n-1];

A: Should be int matrix[n][n].  Generally, an array A[n] has indexes from 0 to n-1.
You are overflowing the boundaries of the row, for example, if you have int matrix[2][2] and set matrix[0][2] = 42, you are actually assigning matrix[1][0], and when you set matrix[2][0] you are writing beyond the array boundaries potentially destroying some other variables or even call stack, which may cause undefined behavior.


text:
Q: Cloning of rows and columns from the old table into the new with colSpan and rowSpan I am using clone jQuery. It is necessary to clone a gray area in the new table.
The problem is that the cloned rows and columns can has rowSpan and colSpan.
The gray area is the intersection data-fix-cols and data-fix-rows.
My solution does not work:

            CLONE ME
            CLONE ME
            Ashgabat
            Barcelona
            Berlin

            CLONE ME
            Bucharest
            Warsaw
            Washington

            CLONE ME
            CLONE ME
            Hamburg
            Guatemala
            Dakar

            CLONE ME
            CLONE ME
            Dresden
            Dublin
            Geneva

            Zagreb
            Kinshasa
            Kishinev
            Krakow
            Lima
            Lisbon

            London
            Los Angeles
            Luxembourg
            Madrid
            Manila
            Mexico

            Milan
            Montreal
            Mumbai
            Nairobi
            Nicosia
            New York

            Osaka
            Oslo
            Ottawa
            Paris
            Prague
            Riga

            Rome
            Rotterdam
            Salvador
            Samarkand
            Sydney
            Singapore

            Sofia
            Istanbul
            Taipei
            Tbilisi
            Zurich
            Chicago

JavaScript code:
var old_table = $("#old-table");
var my_clone = $('#old-table tbody').clone();
var fix_cols = old_table.data('fix-cols');
var fix_rows = old_table.data('fix-rows');

fix_cols--;
fix_rows--;

my_clone.find('tr:gt(' + fix_rows + ')').remove();
my_clone.find('tr').each(function(i,e)
{
    my_clone.find('tr:eq(' + i + ')').find('td:gt(' + fix_cols + ')').remove();
});

$('#new-table').html(my_clone);
$('#new-table').show();

In example http://jsfiddle.net/djmartini/u8ov43tn/5/

A: This fiddle contains your required answer
http://jsfiddle.net/u8ov43tn/13/
var old_table = $("#old-table");
var my_clone = $('#old-table tbody').clone();
var fix_cols = old_table.data('fix-cols');
var fix_rows = old_table.data('fix-rows');

//fix_cols--;
fix_rows--;
var tDsInRow = [];
my_clone.find('tr:gt(' + fix_rows + ')').remove();
my_clone.find('tr').each(function (i, e) {
    if (typeof tDsInRow[i] == "undefined") {
        tDsInRow[i] = fix_cols;
    }

    my_clone.find('tr:eq(' + i + ')').find('td:lt(' + fix_cols + ')').each(function (j, td) {

        if (td.colSpan > 1 && td.rowSpan > 1) {
            tDsInRow[i] = tDsInRow[i] - (td.colSpan - 1)
            for (var j = 1; j  1) {
            tDsInRow[i] = tDsInRow[i] - (td.colSpan - 1)
        } else if (td.rowSpan > 1) {
            for (var j = 1; j  0) {
        my_clone.find('tr:eq(' + i + ')').find('td:gt(' + (tDsInRow[i] - 1) + ')').remove();
    } else {
        my_clone.find('tr:eq(' + i + ')').find('td').remove();
    }
});

$('#new-table').html(my_clone);

$('#new-table').show();


text:
Q: Generate all strings within a given Hamming distance I'm looking for an efficient C++ function that given a string (of a given alphabet that happens to be: A,C,G,T,N) will generate all sequences that are at a certain Hamming distance from it. Ideally, the output will be a map with key as each of these strings and the value as the input string.
Is there such an implementation?

A: The number of sequences depends on the length of original sequence and the hamming distance. If hamming distance is one, you could just scan through the sequence and change the character in every position.


text:
Q: Android FATAL EXCEPTION: IntentService[lectorc2dmuser@gmail.com] @Override
protected void onMessage(Context context, Intent intent) {
    Log.e("C2DM", "Neue Message.");
    Intent resultIntent = new Intent(context, ResultActivity.class);
    resultIntent.putExtra("message", "Message received");
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

I can see from my logcat that i get into this method, then when it tried to start the activity, it throws the fatal exception as written in title with the following comment:
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
(my reply to AndroidRuntime is: "Isn't that what I'm doing?") ;-)

A: You are passing the wrong intent variable to startActivity() call. You want to use resultIntent to start the new activity and you are adding FLAG_ACTIVITY_NEW_TASK flag to resultIntent but when starting the new activity you are passing intent by mistake i.e
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

change this to
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(resultIntent);


text:
Q: Is there a definition of force? Well, Newton's three laws talks about forces, but no definition is given. In truth, Newton's second law gives an idea of what total force is: the time change rate of momentum. But, if we have a force amongst others, this force alone isn't the time rate change of momentum, so that we cannot use Newton's second law to define force, but just to try defining total force.
Knowing all of this, is there a definition of force or we take force as a primitive concept like that of time?
Thanks very much in advance!

A: It's a matter of taste. You can take $F=ma$ to be merely a definition of force, in which case what's testable in Newton's laws are the ancillary statements such as the claim that forces add like vectors. Or you can take force to be defined operationally, e.g., in terms of scales and balances, and then $F=ma$ is a law that can be tested empirically.

Knowing all of this, is there a definition of force or we take force as a primitive concept like that of time?

Time might or might not be a primitive notion. Again, it's a matter of taste. For example, one could define it operationally as what a clock measures (but if that is going to work, then clock comparison experiments had better give null results).

A: Many physical science and introductory physics texts define a force as a push or pull on an object. While I have often thought this possibly too simple, it actually works pretty well. I have personally pondered the same question myself quite a bit, and I think the difficulty lies in the fact that we have an intuitive idea of what a force is in common language. It may have been the same for Newton, and remember that before Principia Mathematica there weren't a lot of resources or well-defined terms. As of Newton's day, the only recognized forces were contact forces, which is why the story of Newton's apple is so profound. That the earth could pull the apple down with touching it meant that the sun could pull the planets, and the earth could pull on the moon.
Presently, with centuries of continued study and new fields of research, depending on what you decide is the fundamental area of physics, one can find several "definitions" of force. It can be the rate of change of momentum over time ($F = \Delta p /\Delta t$) or the change of potential energy over space ($F = -\Delta U /\Delta x$ or $F = -\nabla U$).
I wonder what Newton himself would say. I imagine that if he were pressed for a definition, he could at least say "A force is something that causes acceleration." That definition would be well supported by his 1st and 2nd laws; nothing accelerates without a force, and when there is a force, the acceleration is proportional to it (and inversely proportional to mass).


text:
Q: Uninstall does not remove registry entry - how to find the reason I have built a setup project (vdproj from Visual Studio 2010) for a product. When uninstalling on my test machine, it does not remove everything it should. Specifically, it doesn't delete some registry entries it created in the installation.
A similar project DOES the cleanup; I compared the projects and found no error, so I assume that windows installer believes to have a good reason for this. I need to make him forget the reason, so that I get a clean test base for my product without reinstalling windows.
So I tried a manual cleanup:
- uninstall -> registry entries are not deleted
- regedit -> cleanup manually
- install -> registry entries are created by my MSI
- uninstall -> registry entries still not deleted.
I think there is a (probably obsolete) reference somewhere in the installer database that says: the component that contains these entries is still used by this feature, so you cannot delete them. Perhaps I have duplicate component keys, because I copied a setup project, so that I get this confusion.
I think I might be able to find the component and feature ID to which my registry keys belong, but how can I fix this in the installer database? Where Do I have to look? Are there any tools that could help me? It's Windows 7 Ultimate.

A: Mixed up component ids could cause that, yes. You can run a vbscript like this to identify all the component ids and their product owners, make it a vbs file. The other reason might be that you once marked it permanent. That is a system setting on the object, not just a project setting at build time, so if it was ever installed with permanent true it will remain installed.
When this writes the guids and owners and paths to a file, if it's a registry path it will start with 2 digits to denote a registry location.
Option Explicit
Public installer, fullmsg, comp, a, prod, fso, pname, ploc, pid, psorce

Set fso = CreateObject("Scripting.FileSystemObject")
Set a = fso.CreateTextFile("comps.txt", True)

' Connect to Windows Installer object
Set installer = CreateObject("WindowsInstaller.Installer")

a.writeline ("MSI Components")

on error resume next

For Each comp In installer.components

   a.writeline (comp & " is used by the product:")

   for each prod in Installer.ComponentClients (comp)

      pid = installer.componentpath (prod, comp)

      pname = installer.productinfo (prod, "InstalledProductName")

      a.Writeline ("     " & pname & " " & prod & "and is installed at " & pid)

   Next

Next

A: Phil has already provided a really good answer with the debugging info required. Just want to add that I tend to just give the problematic component a new GUID and then try it again.
You should only do this if the setup in question has not gone live yet and exist only on your test computers.
(If this works it is because the new GUID thinks it "owns" the registry key, and removes it on uninstall. GUID changes such as these cause missing files and settings after upgrades - and changing the GUID in this case is just a hack you can use if the setup isn't used by anyone but you yet - otherwise it should never be done).
Here is another answer describing the issue of component GUIDs. When they should be changed, why and what the consequence will be: Change my component GUID in wix?


text:
Q: Keeping global objects in ASP.NET In my case, I have a custom forum shared among several users in asp.net and C#. I found the loading process pretty costly (several tables joined for different purposes). The users can modify and add new entries. But I don't want to load the object per user.
Considering that the static variables - especially when editable- are not thread safe. I wonder what is the best practice to do so.

A: There is a short answer... and a very long answer to this question. The long answer can be found over on programmers.stackexchange.com the short answer is what I'll give you here.
I would recommend (very conditionally as I don't know the nature of the query) that you create a view in your database for that complicated join, the reason being that the database will cache the view for you and will update it every time the tables touched by the query are updated. This would mean that you only have to do a query for that view and not the massively complicated query you're doing now. Mind you this is a short term solution, if your user count grows this will likely cause your DB to start chewing CPU and ram.


text:
Q: Parabola in Processing I was transferring tasks from my maths textbook to Processing. One of the problems required the use of a parabola. I decided to write it as a Bézier curve, wrote the code, but something didn't work.
Could anyone please explain to me what I did wrong here?
The code:
def setup():

    background(255,255,255)

    size(800,800)

    rectMode(CENTER)

    line(400,0,400,800)

    line(0,400,800,400)

    #B 0 to know the start and the end points

    a=1

    x=3

    b=0

    c=10

    translate(width/2, height/2)

    noFill()

    beginShape()

    #Parabola formula

    y=-(a*x*x+b*x+c)

    #X of the point of the symetry

    Sx=(-b)/(2*a)

    #Y of the point of the symetry

    Sy=-(a*Sx*Sx+b*Sx+c)

    #Derivative

    Ny=-(800+b)

    #Y of the starting point

    By=-(a*400*400-b*400+c)

    #Y of the end point

    Ey=-(a*400*400+b*400+c)

    #Y3 Y4

    Ty=Ny*(x+400)-By

    bezier(-400,By,Sx,Ty,400,Ey,Sx,Ty)

    endShape()

    noFill()

    beginShape()

    for i in range (-400,400):

        x=i

        y=-i

        vertex(x,y)

    endShape()

(It had to be an 800x800 coordinate plane, a parabola and a straight line.)

A: Your resulting y coordinates are way too high for the bezier curve.
If you want to draw the curve with line segments, you need to calculate the y coordinates inside the loop:
def setup():
    size(400, 400)

    background(255,255,255)
    rectMode(CENTER)
    line(width/2, 0, width/2, height)
    line(0, height/2, width, height/2)
    translate(width/2, height/2)

    a, b, c = 1, 10, -100
    scaleX = 0.1;
    noFill()
    strokeWeight(4)
    beginShape(LINES)
    for i in range (-400, 400):
        x = i * scaleX
        y = -(a*x*x +b*x + c)
        vertex(i, y)
    endShape()


text:
Q: WSL2 (docker) ports are not openend on host When I run an image through docker in WSL2, the ports are not published on the host machine. Why is this? What can I do to make this work?

A: So while I still don't know why this happens (sometimes) it appears a restart fixes it (temporarily?):
(on windows cmd)
> wsl --shutdown

Re-running the same commands as above yields mapped ports also visible ob the windows host machine:
C:\WINDOWS\system32>netstat -ano | findstr 55580
  TCP    127.0.0.1:55580        0.0.0.0:0              ABHÖREN         12392
  TCP    [::1]:55580            [::]:0                 ABHÖREN         12392

The 12392 PID is wslhost.exe


text:
Q: TimeUnit Java returning zero days Hi wanted to get the number of days in between dates.
Below is the logic I tried
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
final Date endDate = cal.getTime();
final Date currentDate = new Date();
System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()));

It is always printing 0. Expectation is to print 1.
Any ideas?

A: A day is 24*60*60*1000 milliseconds.
endDate.getTime() - currentDate.getTime() is always shorter than that.
So you should always add 1 to the result:
System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()) + 1);

A: The result of endDate.getTime() - currentDate.getTime() is just a few millisecond less than a day, so the result is rounded to 0.
You would have the expected result if you initialize your calendar with the currentDate:
final Date currentDate = new Date();
final Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.DATE, 1);
final Date endDate = cal.getTime();
System.out.println(TimeUnit.MILLISECONDS.toDays(endDate.getTime() - currentDate.getTime()));


text:
Q: ionic - ion-nav-view not working I am building a ionic pacakage, having multiple views. I use the route provider to navigate between different views.
app.js
.config(function($routeProvider,$locationProvider){

    $routeProvider
    .when('/search',
        {
            controller : 'MyController',
            templateUrl : 'partials/search.html'
        })

    .when('/not-found/:className',
        {
            controller : 'MyController',
            templateUrl : 'partials/not-found.html'
        })

My index.html
  <body ng-app="MyApp">
        <ng-view></ng-view>

      </body>
    </html>

The problem is that the back button on my phone does not work.i.e it does not remember the history.
e.g If I go from search.html to not-found.html, when I press the back button on my phone, I expect it to come back to search.html instead it closes my app.
I looked and ionic forum and the suggest way to make back button work is to use ion-nav-view. If I replace ng-view with ion-nav-view, the search/not-found page are not rendering, I even tried adding the ion-view on the search/not-found html page.
1) Could you please suggest a way to get my back button working?

A: In order to achieve that, you actually need to capture the hardware back button pressed event and perform the navigation accordingly or You can use ion-nav-back-button..

*

*Capture the hardware back button event :
$ionicPlatform.registerBackButtonAction(function () {
  if (condition) {
    navigator.app.exitApp();
  } else {
    // handle back action!
  }
}, 100);

More Details can be found here

*Using ion-nav-back-button
<ion-nav-bar>
  <ion-nav-back-button class="button-clear">
    <i class="ion-arrow-left-c"></i> Back
  </ion-nav-back-button>
</ion-nav-bar>

More Details about this can be found here

A: registerBackButtonAction is already handled as part of ion-nav-back-button as part of the ng-click attribute within the ion-nav-back-button definition: buttonEle.setAttribute('ng-click', '$ionicGoBack()') , since $ionicGoBack executes $ionicHistory.goBack() which in turn handles the hardware back button. A simple change to use state configuration should work fine as below:
angular
  .module('app', ['ionic'])
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
     .state('search', {
        url: '/search',
        controller : 'MyController',
        templateUrl : 'partials/search.html'
    })
   .state('not-found', {
        url: `/not-found/:className',
        controller : 'MyController',
        templateUrl : 'partials/not-found.html'
    });

    $urlRouterProvider.otherwise('/search');
  });

HTML:
<body ng-app="app">
    <ion-nav-bar>
      <ion-nav-back-button></ion-nav-back-button>
    </ion-nav-bar>

    <ion-nav-view></ion-nav-view>
  </body>
</html>


text:
Q: vanishing fourier series Let $f(x)=\sum\limits_{k\geq 2} a_k \cos(kx)+b_k\sin(kx)$ a Fourier series of a real-valued continuous function $f$ (with $2\pi$-periodicity).Note here that $f$ is orthogonal to $1,\cos$ and $\sin$ on $[-\pi,\pi]$. Is it true that $f$ vanishes on $[0,\pi]$ ?
Indeed, that is a particular case $N=1$ of a more general question : if the Fourier series of a real-valued function $f$ contains no terms in $\cos(kx)$ or $\sin(kx)$ with $|k|< N$, is it true that $f$ has a zero on any interval of lengh $2\pi/N$ ?

A: If we partition the $[-\pi,\pi]$ into 4 intervals, where $[0,\pi]$ is a sub interval of one of partitioned intervals... say
$[-\pi, -\frac {2\pi}{3}), [-\frac {2\pi}{3},-\frac {\pi}{3}),[-\frac {\pi}{3},0),[0,\pi]$
Suppose is constant in each of the 4 intervals
i.e. $f(x) = \begin {cases}a &x\in[-\pi, -\frac {2\pi}{3})\\b&x\in[-\frac {2\pi}{3},-\frac {\pi}{3})\\c&x\in[-\frac {\pi}{3},0)\\d&x\in[0,\pi]\end{cases}$
We must find $a,b,c,d$ such that.
$\int_{-\pi}^{\pi} f(x) = 0\\
\int_{-\pi}^{\pi} f(x)\sin x = 0\\
\int_{-\pi}^{\pi} f(x)\cos x = 0$
That will be  system of linear equations and will have a non-trivial kernel.
This is not a continuous function, and it does cross $0$ at the endpoints of the interval $[0,\pi]$.  Nonetheless, we can use this approach to structure a function that is continuous and has parameters such that
$\int_{-\pi}^{\pi} f(x) = 0\\
\int_{-\pi}^{\pi} f(x)\sin x = 0\\
\int_{-\pi}^{\pi} f(x)\cos x = 0$
Produce the necessary set of linear equations.

A: So $f(x)=\cos(2 x)$ sounds valid, and $f(\pi/4)=0$.

A: If $a_k=b_k =0$ Except  for $a_2=1$  then F(x)=cos(2x)  which certainly does not vanish on all of  [0,$\pi$] . If you mean vanish at some point ,I don't know .


text:
Q: Is it a good idea to call a function that returns a boolean for ng-show? Does watching a value of function call  or using that in a directive like ng-show has performance hit in terms of that function getting called each time the cycle runs ?
Is it a better approach to have just a have a boolean value determine this and keep on modifying that value in different scenarios ?

A: Yes, if the watch is a function call, it will be called on every digest cycle. The performance hit is the additional time required for making a function call and executing its body compared to reading a value from an object.
If however the body of the watched function is not taking too long to execute the difference will probably be negligible; it is not a bad practice to do it, at least from the few cases I have seen.


text:
Q: Display single item price html below product title in checkout page From Display on sale cart item formatted prices range in WooCommerce answer to my previous question, I was able to display on sale cart item formatted prices.
Unfortunately I was not able to use the product title filter to add the single product price below the product title in the checkout page. The first image shows what i try to achieve - the second how it looks like right now.

*

*My cart page already shows the price below the title:

*My checkout page should show the price too:

Any idea how to add the single product price html below the product title in the checkout page?

A: Based on your previous question answer, simply use also the following:
add_filter( 'woocommerce_checkout_cart_item_quantity', 'filter_checkout_cart_item_quantity', 10, 3 );
function filter_checkout_cart_item_quantity( $item_quantity, $cart_item, $cart_item_key ) {
    return $cart_item['data']->get_price_html() . ' ' . $item_quantity;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.


text:
Q: How to stream C# console output to an ASP webpage textbox I'm currently developing a webpage that calls a C# console application executable on the server. This is great, however, I'd really like to be able to stream the console application output in real time to a textbox on the application that called the application. I have managed to redirect the output of the console to a text file after the console application has completed, but what would be great would be to find out how to stream in real time from the application as it runs to a text box on the webpage.

A: This is not a simple scenario that you can accomplish with C# alone.You have to use AJAX(Jquery)
Here is a link to an example that discuss regarding the creation of realtime log.
http://forums.asp.net/t/1602013.aspx
You will need to use UpdatePanel

A: Have your web page, serverside, read the txt file and put the read text into any control you like. Then have your web page refresh itself / that control every 10 seconds.


text:
Q: Can i exclude a file from a folder but not exclude files with same name from sub folder - InstallShield 2016 Dynamic Linking? In InstallShield 2016 [Basic MSI Project] Dynamic Linking settings for a component, Can i exclude a file say with name A and not exclude the files with name A in subfolders.
Below settings, today excludes file with name A from all folders including the sub folders.

A: No, the settings for a single dynamic file link are unable to do that. Depending on the number of subdirectories involved, you may prefer to create one dynamic link for the top-level directory, excluding the file name, and one dynamic link for each subdirectory, not excluding the file name.
(In general I prefer avoiding dynamic file links. They make it too easy to violate component rules, or drop required files, on accident.)


text:
Q: Unzip a list of files whose path has to be read from a table in Pentaho kettle I am new to Pentaho kettle and have a requirement where we want to unzip a set of files and the paths to those files are there in a table. I am wondering how to go about  it.

A: This should be your main Job:

First transformation connects to your database and extract the paths, after this another Job is called (Unzip) which extracts those files. I'll be more clear, the next is the transformation called "Table input":

Use the "Table input" step to connect to your database. When you open it you have to create a new connecion and then put your query in the canvas. (make a query which extract values just from the interested column, not every columns). The step "Copy rows to result" gives the values form the database to the next job.
The following is the job "Unzip":

This job receives the values from the previous transformation and pass tose to the "Unzip file" job entry.
Things to know:
1) In the main job double click on the Unzip job icon, go to "advanced" and specify "Copy previous result to parameters" and "Execute for every input row". Of course in the Job specification you have to specify the path of this job.
2) Also double click on the Unzip job icon, go to parameters and put a parameter named as the value which you extract from the database:

3) Enter in the sub-Job (Unzip in my case) and right click, then go to "Job settings" and then to "parameters". Now put the same parameter name as before:

4) Remember to set the destination folder of the files and the receving parameters in the "Unzip files" job entry:


text:
Q: Add class to a DOM element on click I need to add a class to element on click. The click gets registered, however, when I try to add a class to the target it has no effect.
<ellipse data-part-id="147" class="body_part" cx="112.75" cy="25" rx="20" ry="20" transform="rotate(0 ,111.663,25)"></ellipse>

$(document).ready(function () {
    $('.body_part').click(function (event) {
        //has no effect
        $(this).addClass('clicked');
        //has no effect either
        $(event.target).addClass('clicked');
        //works & returns the value
        $(event.target).attr('data-part-id');
    });
});

When I try to access the object to get some data, it works with no issue. Am I doing something wrong?


text:
Q: Multiple authentication methods working as OR instead of AND in .NET Framework 4.8 Web API I have a Web api in FW 4.8. I currently have it rigged with 2 authentication methods: Salesforce auth and Basic auth. Some of the controllers require Salesforce, some require basic auth, but so far they have worked independently.
As per a new requirement from the client, we need to keep those auth methods exactly as they are, but we need to add a new one: Okta authentication.
This is the code that I used to add it to the IAppBuilder, which will run at startup:
public static void AddAuthenticationConfiguration(this IAppBuilder app)
    {
        app.UseOktaWebApi(ApiAuthenticationScheme, new OktaWebApiOptions
        {
            OktaDomain = "https://some.domain.com",
            AuthorizationServerId = "default"
        });
    }

So now if I add this to one of my controllers:
[Authorize]
    public class SomeController : ApiController
    {
      ...
    }

...I'll be able to authenticate using the Okta token.
The problem, however, is that if I do this, my old authentication methods (Salesforce or basic auth) stop working altogether.
What I need to do is make it so Okta starts working in parallel with those auth methods.
So, for example, the controllers that once required only Salesforce Auth, will now require
either Okta OR Salesforce, and the ones that required Basic Auth, will also be accesible using Okta.
So, in summary, I wish to keep the auth methods that I already have in place, untouched, but make them coexist with Okta.
I know this is somewhat easy to do with .Net Core and up, since it has multiple authentication schemas, but sadly I cannot upgrade to Core at the moment.
Is there a way to add multiple authentication schemas to a web api controller in Framework 4.8, that behave as an OR rather than an AND (I think this is the case of chaining together multiple Authentication Filters), or is it not possible?
Some more context: here's how I set up both Okta and Salesforce in my Startup class:
var saleforceoption = new SalesforceAuthenticationOptions
        {
            ClientId = authSettings.SaleforceClientId,
            ClientSecret = authSettings.SaleforceClientSecret,
            AuthenticationType = "Salesforce",
            AuthenticationMode = AuthenticationMode.Active,
            Prompt = "login",
            Endpoints =
                new SalesforceAuthenticationOptions.SalesforceAuthenticationEndpoints
                {
                    AuthorizationEndpoint = $"https://{authSettings.SalesforceCompanyDomain}/services/oauth2/authorize",
                    TokenEndpoint = $"https://{authSettings.SalesforceCompanyDomain}/services/oauth2/token"
                }
        };
        app.UseSalesforceAuthentication(saleforceoption);

        app.AddAuthenticationConfiguration();

As per the controller that uses Basic auth, I registered it with a IAutofacAuthorizationFilter.


text:
Q: Delete three lines in specific step I have data like that (this is only a small part):
  454SOL     OW20704   0.317   0.251   5.525
  454SOL    HW120705   0.388   0.322   5.531
  454SOL    HW220706   0.229   0.290   5.553
  462SOL     OW20728   0.130   1.821   5.295
  462SOL    HW120729   0.120   1.806   5.394
  462SOL    HW220730   0.044   1.857   5.259
  469SOL     OW20749   0.461   1.266   5.451
  469SOL    HW120750   0.411   1.267   5.365
  469SOL    HW220751   0.398   1.248   5.527
  500SOL     OW20842   1.754   1.223   5.312
  500SOL    HW120843   1.845   1.184   5.299
  500SOL    HW220844   1.762   1.319   5.336
  502SOL     OW20848   1.592   1.629   5.349
  502SOL    HW120849   1.619   1.663   5.259
  502SOL    HW220850   1.671   1.591   5.395
  515SOL     OW20887   1.587   0.779   5.394
  515SOL    HW120888   1.495   0.817   5.389
  515SOL    HW220889   1.647   0.826   5.329
  516SOL     OW20890   1.013   0.105   5.494
  516SOL    HW120891   1.019   0.190   5.442
  516SOL    HW220892   1.045   0.029   5.437
  522SOL     OW20908   1.728   0.935   5.578
  522SOL    HW120909   1.682   0.928   5.489
  522SOL    HW220910   1.666   0.979   5.644

I want to delete three lines, the next 9 lines leave alone, and then again delete 3 lines. In this case, I want to delete lines 10,11,12 and 22,23,24.
Expected output
  454SOL     OW20704   0.317   0.251   5.525
  454SOL    HW120705   0.388   0.322   5.531
  454SOL    HW220706   0.229   0.290   5.553
  462SOL     OW20728   0.130   1.821   5.295
  462SOL    HW120729   0.120   1.806   5.394
  462SOL    HW220730   0.044   1.857   5.259
  469SOL     OW20749   0.461   1.266   5.451
  469SOL    HW120750   0.411   1.267   5.365
  469SOL    HW220751   0.398   1.248   5.527
  502SOL     OW20848   1.592   1.629   5.349
  502SOL    HW120849   1.619   1.663   5.259
  502SOL    HW220850   1.671   1.591   5.395
  515SOL     OW20887   1.587   0.779   5.394
  515SOL    HW120888   1.495   0.817   5.389
  515SOL    HW220889   1.647   0.826   5.329
  516SOL     OW20890   1.013   0.105   5.494
  516SOL    HW120891   1.019   0.190   5.442
  516SOL    HW220892   1.045   0.029   5.437

I tried this:
#!/bin/bash
awk 'NR%10==0 || NR%11==0 || NR%12==0' sol.txt | tee sol_after.txt

and it doesn't work.
I need to dele lines on the whole file, so delete 10-12, then 22-24, then 34-36, 46-48, etc

A: Using any awk in any shell on every Unix box:
$ seq 30 | awk 'NR%12 !~ /^(10|11|0)$/'
1
2
3
4
5
6
7
8
9
13
14
15
16
17
18
19
20
21
25
26
27
28
29
30

or if you prefer:
$ seq 30 | awk 'NR%12 == 10{c=3} !(c&&c--)'
1
2
3
4
5
6
7
8
9
13
14
15
16
17
18
19
20
21
25
26
27
28
29
30

See https://stackoverflow.com/a/17914105/1745001 for what c&&c-- does and more information.

A: Using GNU sed, with its "skip" operator:
$ printf 'Line %2d\n' {1..25} | sed  -n '10~12{n;n;n};p'
Line  1
Line  2
Line  3
Line  4
Line  5
Line  6
Line  7
Line  8
Line  9
Line 13
Line 14
Line 15
Line 16
Line 17
Line 18
Line 19
Line 20
Line 21
Line 25

A: With each awk :
awk -v n=9 -v d=3 '
    ((NR - skip) > n && (NR - skip) <= n+d){f = 1;next}
    NR > n && f {f=0;skip = NR-1} 1
' file

Tested with more lines :
for i in {1..50}
do printf '%d\n' "$i"
done | awk -v n=9 -v d=3 '
    ((NR - skip) > n && (NR - skip) <= n+d){f = 1;next}
    NR > n && f {f=0;skip = NR-1} 1
'

you can wrap it in a sh script and choose which lines to omit by simply changing the bounds:
n the number of lines to print and
d the number of lines to omit once the n limit is reached


text:
Q: TextBlock displaying list of objects If I use following code to display objects in a ListBox, how can I display it in a TextBlock?
listStudents.Items.Clear();
foreach (Student sRef in StudentList)
{
    listStudents.Items.Add(sRef);
}

A: If you want to display several lines of students in a single TextBlock, you could append to the Text property of the TextBlock:
foreach (Student sRef in StudentList)
{
    textBlock1.Text += sRef.Firstname + " " sRef.Lastname + Environment.NewLine;
}

But you probably want to define an ItemTemplate that defines the appearance of each Student object in the view:
<ListBox x:Name="listStudents">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Firstname}" />
                <TextBlock Text="{Binding Lastname}" Margin="2 0 0 0" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

A: listStudent.Items.Clear();
        foreach (Student sRef in StudentList)
        {
            listSubjects.Items.Add(sRef.firstname + " " + sRef.lastname);
        }

A: If you want just to display a list of objects without selection and other ListBox functionality, it's convenient to use ItemsControl - it has ItemTemplate property to control an appearance of each item and other useful stuff (actually, ListBox inherits ItemsControl). Just use itemsStudent variable of type ItemsControl and use the same code:
itemsStudent.Items.Clear();
foreach (Student sRef in StudentList)
{
    itemsStudent.Items.Add(sRef);
}


text:
Q: Como retornar dados de um evento pelo Graph API Estou começando a testar integrações com o Facebook em meu site e ao tentar retornar informações de um evento utilizando o código que consta na documentação da API recebo o seguinte erro:
code: 104
 message: "An access token is required to request this resource."
 type: "OAuthException"
sei que tenho que informar o token de acesso para a API retornar as informações (como visto no Graph Explorer) mas não sei como utilizá-lo via Javascript. Alguém poderia me passar um feedback?

A: Olá, tudo bem?!,
Dei uma lida rápida pela documentação, descobri esse link que tem exatamente o que você precisa:
https://developers.facebook.com/docs/opengraph/getting-started
Se tiver alguma dúvida posta de novo aqui..
vlw!


text:
Q: Glassfish 3.1.2.2: admin console won't load When I try to access the admin-console with
http://localhost:4848

it says the admin console is loading, but it won't go further. If I refresh the the page as advised, I get a HTTP 404.
There are several other answered questions on Stack Overflow with similar issues, but none of the answers helped. So I set the global logging-level to FINEST and looked at the server.log.
The first and most prominent exception I get is:
[#|2013-05-07T11:04:52.187+0200|FINE|glassfish3.1.2|com.sun.enterprise.v3.admin.adapter.AdminConsoleAdapter|_ThreadID=81;_ThreadName=Thread-2;ClassName=com.sun.enterprise.v3.admin.adapter.AdminConsoleAdapter;MethodName=initRest;|java.io.IOException: Server returned HTTP response code: 401 for URL: http://0.0.0.0:4848/management/domain
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at com.sun.enterprise.v3.admin.adapter.AdminConsoleAdapter.initRest(AdminConsoleAdapter.java:557)
at com.sun.enterprise.v3.admin.adapter.AdminConsoleAdapter$1.run(AdminConsoleAdapter.java:372)

(here the complete log from starting glassfish to accessing admin-console)
This happens on my development machine (Windows XP). Tried several re-installations to different locations. My JVM is from JDK 7u21.
This does not happen on my other development machine (Ubuntu 13.04) with similar configuration. The main difference - apart from OS - is the proxy-configuration. It is set to a proxy for all protocols, port 8080, except localhost.
I'm really out of answers myself...
EDIT
Additional weird behaviour. At times (every second restart of glassfish) it is possible to access to login to the admin console via
http://127.0.0.1:4848/j_security_check

I may then log in and edit any setting there. When I log off I get a HTTP 500:
javax.servlet.ServletException: java.lang.reflect.InvocationTargetException while attempting to process a 'beforeCreate' event for 'sun_html53'.

root cause

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException while attempting to process a 'beforeCreate' event for 'sun_html53'.

root cause

java.lang.reflect.InvocationTargetException

root cause

java.lang.IllegalStateException: REST Server Name not set!

After that I cannot login anymore via the above trick until restart of glassfish.
Also at time access via
http://localhost:4848/login.jsf

is possible, but then I may not alter any value but get directly a log error that says the same as above.

A: Good afternoon !!!!
I had the same exact problem the publisher described, and tried everything !!!, but after having feedback from different friends, I did the next steps:
Before starting... my environment was working OK (everything, if possible was installed in 64bits), until some web page required 32bits JRE, I downloaded it and installed it, after this, glassfish just went crazy and started doing what is described in this discussion.
I did lots of test, installing, uninstalling, unzipping and deleting JDK, Glassfish versions.... nothing worked until one friend told to search in the users (due to thar every version of glassfish just crashed) folder; In here I searched for every folder names "java" or "Oracle" and I found in the route:

*

*C:\Users\\AppData\LocalLow\Sun\Java\Deployment

The file "deployment.properties", Inside I found a properties:
1. deployment.javaws.jre.0.path=C\:\\Program Files (x86)\\Java\\jre7\\bin\\javaw.exe
2. deployment.javaws.jre.1.path=C\:\\Program Files\\Java\\jre7\\bin\\javaw.exe

Then I deleted property 1
(deployment.javaws.jre.0.path=C\:\\Program Files (x86)\\Java\\jre7\\bin\\javaw.exe)

and modified property 2 to:
+ deployment.javaws.jre.0.path=C\:\\Program Files\\Java\\jre7\\bin\\javaw.exe

That just resolved the problem !!
Hope this can help you guys.

A: Not sure you ened up solving the situation.
I came here having the exact same problem.
After reading here, I could access the admin gui using the link you gave. I saw that one portlet that I deployed as an application was causing the havock.
Undeployed the "portlet" and everything was ok again.

A: It looks like something is wrong with your glassfish installation.
These lines in your log:
[#|2013-05-07T11:04:59.953+0200|FINE|glassfish3.1.2|org.apache.naming.resources.FileDirContext|_ThreadID=82;_ThreadName=Thread-2;ClassName=org.apache.naming.resources.FileDirContext;MethodName=file;|PWC4451: File cannot be read D:\glassfish3\glassfish\lib\install\applications\__admingui\WEB-INF\classes\com\sun\webui\jsf\component\Label.class|#]

[#|2013-05-07T11:04:59.953+0200|FINE|glassfish3.1.2|org.apache.naming.resources.FileDirContext|_ThreadID=82;_ThreadName=Thread-2;ClassName=org.apache.naming.resources.FileDirContext;MethodName=file;|PWC4451: File cannot be read D:\glassfish3\glassfish\lib\install\applications\__admingui\WEB-INF\classes\com\sun\webui\jsf\component\CheckboxGroup.class|#]

[#|2013-05-07T11:04:59.968+0200|FINE|glassfish3.1.2|org.apache.naming.resources.FileDirContext|_ThreadID=82;_ThreadName=Thread-2;ClassName=org.apache.naming.resources.FileDirContext;MethodName=file;|PWC4451: File cannot be read D:\glassfish3\glassfish\lib\install\applications\__admingui\WEB-INF\classes\com\sun\webui\jsf\component\RbCbSelector.class|#]

indicate that the files for the glassfish admin GUI can't be loaded...you'll have to fix this.
Maybe there is something wrong with your user permissions.


text:
Q: accessibilityElementsHidden for OS X? How to protect my app's UI internals from stealing eyes? I need to protect my WebView's URL (make it unavailable for Accessibility Inspector).
Don't write me that all traffic can be sniffed anyway and etc. I am an reverse-engineer, I know all it enough, and I know what I want.
I need to protect my WebView's URL, point.
URL of WebView is storing not in WebView, but nested in 1st child of its child, with WebAccessibilityObjectWrapper class and "HTML content" type.
Unfortunately, WebAccessibilityObjectWrapper class is Apple's "closed" class and we can't extend it.
iOS (from 5.0+) has wonderful feature, accessibilityElementsHidden, which solves my problem.
But OS X doesn't.
My solutions:

*

*Override NSAccessibilityChildrenAttribute for WebView with passing empty array for its value. It really protects from walking through "children" property in Inspector. But, unfortunately, not from Inspector's "point" feature.

*Programmatically find "HTML content" in Accessibility children and work with it. Unfortunately, we need to do it after every URL load and where are no special event for this, it's too dirty.

How to solve it more elegant?

A: Accessibility protocol in iOS and macOS are slightly different. In iOS making a "view" transparent to the VO technology is simpler than in macOS.
Properties you can play with are:

*

*Accessibility element: that you set to false;

*Accessibility role: that you need to set to none;

*Accessibility role description: you could set to "";

The problem is that when a view is disabled as an accessibility element, all of its subviews become visible. One example of this is the NSButton. Simply disabling the "external" button object, i.e.:
let b = NSButton(...)
// setup your b
b.setAccessibilityElement(false)

doesn't solve the problem. VO still can see the button cell.
Making an UI element hidden for VO is not trivial, but it is tricky. You need to play a while understanding the very nature of the specific object you would like to hide.


text:
Q: Drawing a simple circle with Java swing does not work I think I am missing something really obvious but somehow this code does give me an empty window but it does not paint the red oval. What am I missing?
public class Test extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        g = this.getGraphics();
        Graphics2D g2 = (Graphics2D) g;

        // Anti-aliasing
        g2.setColor(new Color(255, 0, 0));
        g2.fillOval(0, 0, 20, 20);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Ball");
        Test panel = new Test();

        frame.getContentPane().add(panel);
        frame.setPreferredSize(new Dimension(250, 200));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setVisible(true);
    }

}

A: the paintComponent is not correct, remove this g = this.getGraphics();
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D)g;

   Ellipse2D.Double circle = new Ellipse2D.Double(xR, yR, diameter, diameter);
   g2d.fill(circle);
   ...
}


text:
Q: How do I create a program that switches my default browser in macOS 10.15.6? I want to create a program that switches between two browsers as default browser. For example, if my default browser is set to Brave Browser, the program will change it to Chrome and vice versa.
Unfortunately, I don't know apple script so I was hoping you guys could help me. Thanks in advance.

A: using your command line (via the terminal):
brew install defaultbrowser

and then (for example)
defaultbrowser chrome


text:
Q: How does use_for_related_fields work in Django? I'm unable to grasp that from the docs. It's totally unclear to me, more specifically:

*

*Is it a global setting? So if I specify this attribute it on one of the model managers, will it be used globally by all the model classes?

*If it's not a global setting then which relationships exactly will be affected?

*Is it possible to have one model manager for one relationship and another one for another relationship with the same model?

Most of all I would appreciate any good minimal example usages as the documentation lacks those afaik. Thanks.

A: Is it a global setting? So if I specify this attribute it on one of the model managers, will it be used globally by all the model classes?
If I have understood what you mean by global, the answer is no. It will only be used for a class if the default manager (the first manager specified in the class) has it set. You could re-use the manager in several models, and the attribute would only have an effect on those classes it was the default manager for.
This is something I thought an example would help with understanding. Lets use the following member and profile models, linked in a one-to-one relationship:
from django.db import models

class Member(models.Model):
    name = models.CharField(max_length=100)
    active = models.BooleanField()

    def __unicode__(self):
        return self.name

class Profile(models.Model):
    member = models.OneToOneField(Member)
    age = models.PositiveIntegerField()

    def __unicode__(self):
        return str(self.age)

We'll create a couple of members, the active John and the inactive Phil, and set up a profile for each of them:
>>> m1 = Member(name='John', active=True)
>>> m1.save()
>>> p1 = Profile(member=m1, age=18)
>>> p1.save()
>>> m2 = Member(name='Phil', active=False)
>>> m2.save()
>>> p2 = Profile(member=m2, age=35)
>>> p2.save()

How Django stores relationships
First, lets look at how Django stores a relationship. We'll take John's profile and look at its namespace:
>>> p = Profile.objects.get(id=1)
>>> p.__dict__
{'age': 18, '_state': <django.db.models.base.ModelState object at 0x95d054c>, 'id': 1, 'member_id': 1}

Here we can see the relationship is defined by storing the ID value of the member instance. When we reference the member attribute, Django uses a manager to retrieve the member details from the database and create the instance. Incidentally, this information is then cached in case we want to use it again:
>>> p.member
<Member: John>
>>> p.__dict__
{'age': 18, '_member_cache': <Member: John>, '_state': <django.db.models.base.ModelState object at 0x95d054c>, 'id': 1, 'member_id': 1}

Which manager to use
Unless told otherwise, Django uses a standard manager for this relationship lookup rather than any custom manager added to the model. For example, say we created the following manager to only return active members:
class ActiveManager(models.Manager):
    def get_queryset(self):
        return super(ActiveManager, self).get_queryset().filter(active=True)

And we then added it to our Member model as the default manager (in real life, this is a Bad Idea™ as a number of utilities, such as the dumpdata management command, exclusively use the default manager, and hence a default manager which filters out instances could lead to lost data or similar nasty side effects):
class Member(models.Model):
    name = models.CharField(max_length=100)
    active = models.BooleanField()

    objects = ActiveManager()

    def __unicode__(self):
        return self.name

Now that the manager filters out inactive users, we can only retrieve John's membership from the database:
>>> Member.objects.all()
[<Member: John>]

However, both profiles are available:
>>> Profile.objects.all()
[<Profile: 18>, <Profile: 35>]

And hence we can get to the inactive member through the profile, as the relationship lookup still uses a standard manager rather than our custom one:
>>> p = Profile.objects.get(id=2)
>>> p.member
<Member: Phil>

However, if We now set the use_for_related_fields attribute on our manager, this will tell Django it must use this manager for any relationship lookups:
class ActiveManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super(ActiveManager, self).get_queryset().filter(active=True)

Hence we can no longer get Phil's membership record from his profile:
>>> p = Profile.objects.get(id=2)
>>> p.member
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)

/home/blair/<ipython console> in <module>()

/usr/lib/pymodules/python2.6/django/db/models/fields/related.pyc in __get__(self, instance, instance_type)
    298             db = router.db_for_read(self.field.rel.to, instance=instance)
    299             if getattr(rel_mgr, 'use_for_related_fields', False):
--> 300                 rel_obj = rel_mgr.using(db).get(**params)
    301             else:
    302                 rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)

/usr/lib/pymodules/python2.6/django/db/models/query.pyc in get(self, *args, **kwargs)
    339         if not num:
    340             raise self.model.DoesNotExist("%s matching query does not exist."
--> 341                     % self.model._meta.object_name)
    342         raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s"
    343                 % (self.model._meta.object_name, num, kwargs))

DoesNotExist: Member matching query does not exist.

Note that this only has an effect if the custom manager is the default manager for the model (i.e., it is the first manager defined). So, lets try using the standard manager as the default manager, and our custom one as a secondary manager:
class Member(models.Model):
    name = models.CharField(max_length=100)
    active = models.BooleanField()

    objects = models.Manager()
    active_members = ActiveManager()

    def __unicode__(self):
        return self.name

The two managers work as expected when looking directly at the members:
>>> Member.objects.all()
[<Member: John>, <Member: Phil>]
>>> Member.active_members.all()
[<Member: John>]

And since the default manager can retrieve all objects, the relationship lookup succeeds too:
>>> Profile.objects.get(id=2)
>>> p.member
<Member: Phil>

The reality
Having made it this far, you now find out why I chose a one-to-one relationship for the example models. It turns out that in reality (and in contradiction of the documentation) the use_for_related_fields attribute is only used for one-to-one relationships. Foreign key and many-to-many relationships ignore it. This is ticket #14891 in the Django tracker.
Is it possible to have one model manager for one relationship and another one for another relationship with the same model?
No. Although, in this discussion of the bug mentioned above this came up as a possibility in the future.

A: The short answer is: until this bug is fixed, 'use-for-related-fields' doesn't work in django, except for one-to-one relationships, so don't bother if your use case is m2m or m2one, or you'll be disappointed.


text:
Q: Using onmouseover and onmouseoff with images to change text I have 6 images and I wish to change the text next to them based on which image is being "hovered" over with the mouse.
I tried doing this using JavaScript with the onmouseover and onmouseout events, with some of the code direct copies from working examples, yet my code is currently not working.
Here is a jsfiddle: https://jsfiddle.net/schanz/xh4pb9n6/
Additionally, here is the raw code: `

Cruise Destinations

Mouse over an image to learn about that destination.

`

A: There is a typo in your javascript. Instead of innerhtml, it should be innerHTML.

A: First, you should not use inline HTML event attributes, such as onmouseover and onmouseout. Always separate your JavaScript from your HTML. [Here's why.]1
Second, don't use tables for page layout. They should just be used for tabular data representation.
Third, you have a typo with .innerhtml, which should be innerHTML. But, since you aren't actually providing any HTML, you should be using textContent, which performs better because the HTML parser doesn't have to do any parsing.
If you simply gather all the image elements into an array, you can map the index of the image being moused over/out to the correct string from your string array.

var textFields = ["Stellwagen Bank offers thrilling whale-watching opportunities.",
               "Hyannis is filled with great food and fun clubs in a downtown setting.",
               "Falmouth is perfect for beach-lovers.",
               "Oak Bluffs feature some of Massachusetts best cottages.",
               "Nantucket is one of our favorites and we think you will love it too.",
               "Plymouth rock is a must for history buffs.",
               "Mouse over an image to learn about that destination."];

// Get reference to output area
var output = document.getElementById("caption");

// Set the default text for the output to be the last string in the array.
output.textContent = textFields[textFields.length-1];

// Get all the images as an array
var imgs = Array.prototype.slice.call(document.querySelectorAll("img"));

// Loop through the images...
imgs.forEach(function(img, index){
  // Assign a mouseover event handler...
  img.addEventListener("mouseover", function(){
    // Set the output to the index in the strings array that matches the
    // index of the image being moused over.
    output.textContent = textFields[index];
  });

  // Assign a mouseout event handler...
  img.addEventListener("mouseout", function(){
    // Reset the output
    output.textContent = textFields[textFields.length-1];
  });

});

Cruise Destinations


text:
Q: Retrieve google scholar number of search results by year using R or Python? I have no idea how to start so I have no code that I tried and I apologize...Is there a way to loop the following url by a sequence of number (year):
https://scholar.google.com/scholar?hl=en&as_sdt=0%2C22&as_ylo=2021&q=%22TERM1%22+AND+%22TERM2%22&btnG=
where 2021 is replace by a sequence and just get the simple number of search results by year?
Thank you so much!
Edit:
This works for Google search but not for Google Scholar...Generates an empty set.
ua <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
url <- "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C22&as_ylo=2021&q=%22causal+inference%22+AND+%22statistics%22&btnG="
doc <- htmlTreeParse(getURL(url, httpheader = list(`User-Agent` = ua)), useInternalNodes = TRUE)

nodes <- getNodeSet(doc, "//div[@id='result-stats']")
nodes

A: There is an approximate results count below the search bar. A lot of the attribute values look dynamic so I would look for a relationship between more stable elements and attributes (based on experience). In this case, I would use :contains() to look for the text with "results" in a div. I would anchor this div by a css selector list that references the expected div location with respect to the search bar and the elements in between.
library(rvest)
library(httr)

headers = c("User-Agent" = "Safari/537.36")
r <- httr::GET(url = "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C22&as_ylo=2021&q=%22TERM1%22+AND+%22TERM2%22&btnG=",
               httr::add_headers(.headers=headers))
r |> content() |> html_element('form[method=post] + div div > div:contains("results")') |> html_text()

You can then perhaps using a simple regex to extract the result count e.g.
library(stringr)

r |>
  content() |>
  html_element('form[method=post] + div div > div:contains("results")') |>
  html_text() |>
  str_extract("(\\d+)") |>
  as.integer()


text:
Q: After Parsing a JSON string to become an object how do you access those properites? So I parsed a string to turn it inton an object. Now after trying to access the properties in that object to display an input I get the errorproperty does not exist on type string I am reaally using a service but for simplicity purposes I manually made a JSON string.
info: string = '{"a":1,"b":2,"c":{"d":3, "e":4}}'
dataTodisplay: string;

 ngOnInit() {
 console.log(typeof this.info); //string
 this.info= JSON.parse(this.info);
 console.log(typeof this.info); //object
 this.dataToDisply = this.info.a; //error 'a' does not exist on type string
}

A: Try declaring your variable as any, right now you have declared it as string so it can only contain a string property.
info: any = '{"a":1,"b":2,"c":{"d":3, "e":4}}'


text:
Q: Supabase file uploading occasionally fails Sometimes I can upload a file and sometimes I get this error:
{statusCode: '403', error: '', message: 'new row violates row-level security policy (USING expression) for table "objects"'}

I got the uploading code from this page. I duplicated the component with different bucket names and only changed htmlFor, id, accept and bucket url, both with the same policies but sometimes the other works/fails or both. One is for image upload and the other video, both have worked at some point so idk why I keep getting the error. And none of the files exceeds the max upload size(50mb). Heres SQL snippet I used:
insert into storage.buckets (id, name)
  values ('avatars', 'avatars');

create policy "Avatar images are publicly accessible." on storage.objects
  for select using (bucket_id = 'avatars');

create policy "Anyone can upload an avatar." on storage.objects
  for insert with check (bucket_id = 'avatars');

Also I'm using Typescript and no error in my code.


text:
Q: Accumulating values from SQL database table that refers to itself TASK
I am currently trying to work out a viable structure for a simple application for the costing of jobs. I have decided to create one table to house all the operations and then link the operation together via a ParentID field. Below is a simplified structure of this table:

As you can see, the primary key is an integer field that does auto increment to keep it unique. Any operations that stem off another operation will have it under the parent ID field to create a simplistic breakdown of work flow. Also on this data table is a field for costs, this is a field that I am most interested in.
THE PROBLEM
I would like  to run a query where I could throw in an operation ID and it would recursively run through that operation AND all of its children and its children's children etc. This would then accumulate all of the cost fields in the records that it retrieves. The only way I can think to do this is through recursive loops which in my opinion are not the best way to do this.
THE QUESTION
So, my question is, is there a way to do this without recursive loops? If there is not, can anyone suggest the cleanest and quickest way with the loops?

A: This kind of query is recursive by definition. There is no way to get that information using that table structure.
You could make another table in which you would store all hierarchy information. On inserting an Operation you would have to add a parent, grandparent, grand-...-parent recursively, which may also not be a good idea, because the table would grow very large very quickly. It would make the queries much simpler though.
And a side note: I'd suggest naming the ParentID ParentOperationID. ParentID is too general.