text:
Q: Use IntersectionObserver with rootMargin to change when reaching 50% viewport height I'm completely flummoxed by the rootMargin property of intersection observer.
My goal is to add a class to an element when half it's height has crossed the vertical center of the viewport.

In my current project, nothing I do seems to impact the "root intersection rectangle" and the class is always added immediately. I've tested in latest Chrome and Firefox.
Here's the reduced test case:

// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

const options = {
  root: null, // default, use viewport
  rootMargin: '0px 0px -50% 0px',
  threshold: 0.5 // half of item height
}

const circle = document.getElementById('circle');

const observerCallback = function(entries, observer) {
  console.log('intersected');
  circle.classList.add('intersected');
}

window.addEventListener('load', function(event) {

  const observer = new IntersectionObserver(observerCallback, options);

  observer.observe(circle);

}, false);
.circle {
  margin: 100vh auto;
  width: 200px;
  height: 200px;
  background-color: tomato;
  border-radius: 50%;
  transition: background-color 2s ease-in-out;
}

.circle.intersected {
  background-color: mediumseagreen;
}

A: I am quite perplexed by IntersectionObserver myself sometimes, but referring to this post, it was a lot easier to grasp for me.
What was probably giving you trouble was checking for if it actually was intersecting or not. So I added an if-statement along with the property isIntersecting that is found on IntersectionObserver entries.
I also added a check for IntersectionObserver if it is available on the client and removed root: null from the options as it should default to the viewport anyway.
If you only use this IntersectionObserver for adding a class once, don't forget to observer.unobserve(circle) or observer.disconnect() when it isn't needed anymore to prevent memory leaks.

// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

const options = {
  rootMargin: '0px 0px -50% 0px',
  threshold: 0.5 // half of item height
}

const circle = document.getElementById('circle');

const observer = new IntersectionObserver(entries => {
  const [{ isIntersecting }] = entries
  if (isIntersecting) {
    console.log('intersected');
    circle.classList.add('intersected');
  } else {
    console.log('not-intersecting');
  }
}, options);

window.addEventListener('load', () => {
  if ('IntersectionObserver' in window) observer.observe(circle);
}, false);
.circle {
  margin: 100vh auto;
  width: 200px;
  height: 200px;
  background-color: tomato;
  border-radius: 50%;
  transition: background-color 2s ease-in-out;
}

.circle.intersected {
  background-color: mediumseagreen;
}


text:
Q: how to show only textarea field, but not line under it? I cannot solve an issue:
I have an html:
  <md-input-container class="itemDescription">
                <label class="itemFont">Description</label>
                <textarea placeholder="Add a description..."
                ></textarea>
            </md-input-container>

and CSS:
.itemDescription{
 width:100% !important;
 border: 1px solid black;
}

the result is next:

BUT I don't want to show white area under  text: "Add description..."
So if descripiton has 1 row = show just 1 row. if 2 rows = show just 2 rows, but without additional white area. How to do it?

A: Add below css, it will remove the line under the textarea
border-bottom : 0px

A: Fixed.I've put styles on textarea. and border on it. so it works now.
thanks!!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Join Table issue with rails 6 I have a Color model:
class Color < ApplicationRecord
  belongs_to :sector

A sector model:
class Sector < ApplicationRecord
  has_many :colors

I created a join table like:
class CreateJoinTableColorSector < ActiveRecord::Migration[6.0]
  def change
    create_join_table :color, :sectors do |t|
      t.index %i[color_id sector_id]
      t.index %i[sector_id colore_id]
   end
 end
end

Now I want to get all the Colors who belongs to a specific sector. I tried :
Color.joins(:sectors).where({ sector: sector })

But it returns me an error → uninitialized constant Color::Sectors

A: If you have a Color model like:
# == Schema Information
#
# Table name: colors
#
#  id           :integer          not null, primary key
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class Color < ApplicationRecord
  has_many :color_sectors
  has_many :sectors, through: :color_sectors
end

And a Sector model like:
# == Schema Information
#
# Table name: sectors
#
#  id           :integer          not null, primary key
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class Sector < ApplicationRecord
  has_many :color_sectors
  has_many :colors, through: :color_sectors
end

Then you create your ColorSector model like:
# == Schema Information
#
# Table name: color_sectors
#
#  id           :integer          not null, primary key
#  color_id     :integer
#  sector_id    :integer
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class ColorSector < ApplicationRecord
  belongs_to :color
  belongs_to :sector
end

And when you have an @color and you want to get all the associated Sector records, you can do:
@color.sectors

And when you have an @sector and you want to get all the associated Color records, you can do:
@sector.colors

If you want to associate a @color with a @sector, then you do:
@sector.colors << @color

This, and more, is all covered thoroughly in the docs.

A: If you need many-to-many relationships, use has_and_belongs_to_many association


text:
Q: Postgres on OS X can't find postgis extension control file Using mac OSX Yosemite 10.10.1.  I uninstalled and re-installed both postgres and postgis with homebrew.  I understand that postgres is looking in the wrong place for the postgis control file.  Also noticed that 'which psql' path seems incorrect.  How/where do I fix this?
psql
(9.4.0, server 9.3.5)

ERROR:  could not open extension control file "/usr/local/Cellar/postgresql/9.3.5_1/share/postgresql/extension/postgis.control": No such file or directory

find /usr -name postgis.control
/usr/local/Cellar/postgresql/9.4.0/share/postgresql/extension/postgis.control

which psql
/usr/local/bin/psql

which pg_config
/usr/local/bin/pg_config

brew info postgis
postgis: stable 2.1.5, HEAD
http://postgis.net
/usr/local/Cellar/postgis/2.1.5 (45 files, 8.6M) *
  Built from source
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/postgis.rb

brew info postgres
postgresql: stable 9.4.0 (bottled)
http://www.postgresql.org/
Conflicts with: postgres-xc
/usr/local/Cellar/postgresql/9.4.0 (3049 files, 74M) *
  Poured from bottle
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/postgresql.rb

Both .bashrc and .bash_profile have
export PGDATA='/usr/local/Cellar/postgresql/9.4.0/bin/postgres'
alias postgres-log='cd /usr/local/var/postgres/ && subl server.log'

mdfind -name "postgres" | grep -G "postgres$"
/usr/local/Cellar/postgresql/9.4.0/bin/postgres
/usr/local/var/postgres
/Users/lionelramos/macports/var/macports/sources/rsync.macports.org/release/tarballs/ports/ruby/rb-postgres

Looks like I have different a local version of postgres in addition to the homebrew version.

A: How I solved my problem:

*

*I uninstalled postgres 9.3.5_1 with brew uninstall postgres 9.3.5_1.

*I uninstalled postgis with brew uninstall postgis

*Made sure that I only had postgres 9.4 installed with brew info postgres

*Made sure that psql command worked.

*I reinstalled postgis with brew install postgis.

This solved my problem.  If you're having trouble with step 4 you might need to use initdb or createdb commands to create database needed.


text:
Q: HighChart.js error while importing highmaps.js on vs code I am new to highcharts.js and facing this error while importing a map map code
while importing this on my local machine I am facing this error down below
console error
 //importing this src


text:
Q: Mockito & Junit null pointer exception: name must not be null I have been trying to run the following test using mockito and junit and I keep on getting "java.lang.NullPointerException: name must not be null"
Can anyone tell me why this is happening?
On debugging, I found out that this exception is thrown when the test executes the following statement in isStopValid(String) method:
FacilityValidationUtil facUtil = new FacilityValidationUtil();
@RunWith(MockitoJUnitRunner.class)
public class MyFormTest{
    @InjectMocks MyForm form = new MyForm();
    @Mock FacilityValidationUtil facUtil;
    @Test
    public void testIsStopValid() throws FinderException{
        when(facUtil.isFacilityValid("")).thenReturn(false);
        form.setOrigin("");
        assertEquals(false, form.isStopValid(form.getOrigin()));
    }
}

Class with method to be tested:
public class MyForm{
    FacilityValidationUtil facUtil = new FacilityValidationUtil();
    public boolean isStopValid(String stop){

        try {
            return facUtil.isFacilityValid(stop);
        } catch (FinderException e) {
            log.error("Error finding the stop. "+e.getCause());
            return false;
        }
    }
}

public class FacilityValidationUtil{
    private FacilityDAO facilityDao = new HibernateFacilityDAO();
    public boolean isFacilityValid(String facility) throws FinderException{
        boolean test;
        FacilityImpl facilityImpl = facilityDao.findFacilityByNassCode(facility);
        test = (facilityImpl==null)?false : true;
        return test;
    }
}

public class HibernateFacilityDAO extends HibernateAbstractDeltaDAO implements FacilityDAO {
    public HibernateFacilityDAO() {
        super(false);
    }
}

A: Short Answer: You are trying to mock a variable (facUtil) that is local to your isStopValid method, so the mock version of this object in your test is never going to be called because you are 'newing it up" each time.
Long Answer: It looks like you are trying to mock the call to your FacilityValidationUtil class, and if this is the case, then you need to either make the class a field so that Mockito can inject the object by reflection (if this object is thread safe, which it looks like it is) or explore a mocking framework like PowerMockito that will allow you to mock a constructor (google for PowerMockito when new).
PowerMockito.whenNew(FacilityValidationUtil.class).withNoArguments().thenReturn(facUtil);

Mockito doesn't support any mocking of constructor args by default.
EDIT
If you are still having trouble, then I would suggest starting with a smaller example. I've put together one for you that works and uses the code you are trying to test (It's using inner classes though, which Mockito has some quirky rules about, but I'm just doing it to compress the example).
@RunWith(MockitoJUnitRunner.class)
public class MyFormTest {

    @InjectMocks
    private MyForm form = new MyForm();
    @Mock
    private FacilityValidationUtil facUtil;

    @Test
    public void testIsStopValid_false() {
        when(facUtil.isFacilityValid("")).thenReturn(false);
        assertEquals(false, form.isStopValid(""));
    }

    @Test
    public void testIsStopValid_true() {
        when(facUtil.isFacilityValid("")).thenReturn(true);
        assertEquals(true, form.isStopValid(""));
    }

    public class MyForm {
        private FacilityValidationUtil facUtil = new FacilityValidationUtil();

        public boolean isStopValid(String stop) {
            try {
                return facUtil.isFacilityValid(stop);
            } catch (FinderException e) {
                return false;
            }
        }
    }

    public class FacilityValidationUtil {
        public boolean isFacilityValid(String facility) throws FinderException {
            throw new RuntimeException(facility);
        }
    }

    public class FinderException extends RuntimeException {
        public FinderException(String message) {
            super(message);
        }
    }

}

What's really important is that your mock is not getting injected correctly. Until you get that resolved, you are going to keep getting the same error. Set a break point in your MyForm at the point you call facUtil.isFaciltyValid and look at the object. It should be a mockito object, not your class.
Good luck.


text:
Q: Xcode XCTest measure performance with async queues A framework that I have written for my app downloads different chunks of data that get processed. Naturally, larger sets of data take more time to process. To better investigate how to improve, I thought about writing Tests to measure performance to see where/if it's worth looking into.
Generally, the measure block works, however, to avoid blocking the main thread, I process the data asynchronously. Because of that, I'm unable to measure "from start to finish" as the measure block disregards async blocks and finishes the Test before my async queue has finished processing all the data.
I have written a minimal example to demonstrate what I mean.
DownloadHandler is the class that receives the data in my framework. Database is a class in my app and models where the data ends up and gets processed. In my app, the AppDelegate connects these two, but for the sake of the Test, the Test class does that in this case.
This is the console output of what's happening:
File A
Sent A to Database

File B
Sent B to Database

File C
 Processed file A in Database
 Processed file B in Database
Sent C to Database
[End of Test]

But what I would need is to wait for the Test to have the queue to finish processing all the data before stopping. In other words, it's missing a final
 Processed file B in Database

Below you will find my example code to demonstrate. The actual implementation is much more complex with different handlers for different purposes but I simulate the "work done" with the usleep
DownloadHandler.swift
import Foundation

public protocol HandlerDelegate {
    func interpretData(s: Character)
}

class DownloadHandler {

    var delegate: HandlerDelegate!

    func receivedFiles(files: String) {

        for file in files {
            print("\nFile \(file)")
            usleep(100000)
            delegate.interpretData(s: file)
            print("Sent \(file) to database")
        }
    }

}

Database.swift
class Database {

    let serialQueue = DispatchQueue(label: "databaseSerial")

    var entries = [Character]()

    func interpretData(s: Character) {
        serialQueue.async {
            usleep(100000)
            self.entries.append(s)
            print(" Processed file \(s) in database")
        }
    }

}

TestFrameworkTests.swift
import XCTest
@testable import TestFramework

class TestFrameworkTests: XCTestCase, HandlerDelegate {

    func interpretData(s: Character) {
        database.interpretData(s: s)
    }

    var handler = DownloadHandler()
    var database = Database()

    var testData = "ABC"

    func testPerformanceExample() throws {

        handler.delegate = self

        let options = XCTMeasureOptions()
        options.iterationCount = 0

        measure(options: options) {
            print("\n\nTEST ITERATION")
            handler.receivedFiles(files: testData)

        }
    }

}

I suppose there is some XCTest feature that I'm not aware of but I can't wrap my head around what to search for in order to find something I can adapt.


text:
Q: Why my iPhone app was rejected? Here is the message that appears in iTunes Connect Resolution Center:

Reasons
3.5: Small and large app icons should be similar, so as to not to cause confusion
  3.5
We found that the app icon displayed on the device does not
  sufficiently match the large icon displayed on the App Store, which
  does not comply with the App Store Review Guidelines.
In your case, the app icon displayed on the device is blank.
< More explanation...>

So, to my understanding the app was rejected because the app icon is blank on the device, but when I install the app on my iPhone 5 via Ad Hoc distribution (which is the closest to App Store distribution) everything looks fine.
Following is the assets App Icon configuration in XCode. Is it looks fine?

Any help will be appreciated.

A: I found the reason why my app was rejected and I just wish to share the solution for anyone that will face the same issue.
It appears that my app was rejected since the app icon was blank on iPad devices. (Note that iPad devices are still being used by the Apple App Review team testers even though my app is an iPhone only app)
I recently started using images.xcassets for managing my app icon and loading page images. I therefore removed all related files from my app resources but the target plist file had some leftovers that eventually found as the cause to the blank icon on the iPad...
Once I removed an entry called "CFBundleIcons~ipad" from the plist file, the issue was fixed.
Thank you @Leijonien for you comment that helped me to resolve this issue!

A: You not meet App Icon Requirements
Create different sizes of the app icon for different devices. If you're creating a universal app, you need to supply app icons in all four sizes.
For iPhone and iPod touch, both of these sizes are required:
120 x 120 pixels
60 x 60 pixels (standard resolution)
For iPad, both of these sizes are required:
152 x 152
76 x 76 pixels (standard resolution)
Referenced by Apple inc for more information visit Apple icon guidelines


text:
Q: How do you add a featured image to a page (not post)? There's no "add featured image" in the settings section in a page I created. On the other hand, a similar blogpost I created has this setting. I went over some websites which told me that I needed to enable it in screen options for it to be displayed in the settings, but that didn't work either. Please help me out (I am not coding in PHP or CSS, just using the wordpress editor to create my website).

A: You can enable featured image for pages (and other post types) by using the line below. This goes in your functions.php file.
add_theme_support( 'post-thumbnails', array( 'post', 'page' ) );

If you're not comfortable with editing theme files then you should contact your theme developer. If featured images are not enabled by default in your theme they have to be enabled first.


text:
Q: Flutter FutureBuilder refresh when TextField value changes The _futureData is to used for the FutureBuilder after retrieving value from the _loadPhobias() function.
entry_screen.dart
Future _futureData;
final TextEditingController _textEditingController = TextEditingController();

_loadPhobias() function does not seem to have any problem.
entry_screen.dart
Future<List<String>> _loadPhobias() async =>
    await rootBundle.loadString('assets/phobias.txt').then((phobias) {
    List _listOfAllPhobias = [];
    List<String> _listOfSortedPhobias = [];
    _textEditingController.addListener(() {
      ...
    });
    return _listOfSortedPhobias;
});

@override
void initState() {
super.initState();
    _futureData = _loadPhobias();
}

@override
Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(
    title: TextField(
        // When the value is changed, the value returned from the _loadPhobias will also change. So I want the FutureBuilder to be rebuilt.
        onChanged: (text) { setState(() => _futureData =  _loadPhobias()) },
        ),
    ),
    body: FutureBuilder(
        future: _futureData,
        builder: (context, snapshot) {
            return snapshot.hasData
                ? ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) => Column(
                            children: <Widget>[
                                PhobiasCard(sentence: snapshot.data[index]),
                            )
                        ],
                    ))
                    : Center(
                        child: CircularProgressIndicator(),
                    );
                },
            ),
        ),
    );
}

This is the error that I got:

FlutterError (setState() callback argument returned a Future.
The setState() method on _EntryScreenState#51168 was called with a closure or method that returned a Future. Maybe it is marked as "async".
Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)

A: The solution can be inferred in the third line of the error message:

Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)

So this means you'll have to perform the operation before refreshing the widget. You can have a temporary variable to hold the result of the asynchronous work and use that in your setState method:
onChanged: (text) {
     setState(() => _futureData =  _loadPhobias())
},

Could be written as:
onChanged: (text) async {
    var phobias = _loadPhobias();
    setState(() {
        _futureData = phobias;
    });
},

A: The first thing to note, you mentioned that you want to rebuild your app every time there's a change in the text. For that to happen, you should use StreamBuilder instead. FutureBuilder is meant to be consumed once, it's like a fire and forget event or Promise in JavaScript.
Here's to a good comparison betweenStreamBuilder vs FutureBuilder.
This is how you would refactor your code to use StreamBuilder.
main.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyAppScreen(),
    );
  }
}

class MyAppScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppScreenState();
  }
}

class MyAppScreenState extends State<MyAppScreen> {
  StreamController<List<String>> _phobiasStream;

  final TextEditingController _textEditingController = TextEditingController();

  void _loadPhobias() async =>
      await rootBundle.loadString('lib/phobia.txt').then((phobias) {
        List<String> _listOfSortedPhobias = [];
        for (String i in LineSplitter().convert(phobias)) {
          for (String t in _textEditingController.text.split('')) {
            if (i.split('-').first.toString().contains(t)) {
              _listOfSortedPhobias.add(i);
            }
          }
        }
        _phobiasStream.add(_listOfSortedPhobias);
      });

  @override
  void initState() {
    super.initState();
    _phobiasStream = StreamController<List<String>>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextField(
          controller: _textEditingController,
          onChanged: (text) {
            print("Text $text");
            _loadPhobias();
          },
        ),
      ),
      body: StreamBuilder(
        stream: _phobiasStream.stream,
        builder: (context, snapshot) {
          return snapshot.hasData
              ? Container(
                  height: 300,
                  child: ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      print("Data ${snapshot.data[index]}");
                      return Text(snapshot.data[index]);
                    },
                  ),
                )
              : Center(
                  child: CircularProgressIndicator(),
                );
        },
      ),
    );
  }
}

As seen in the code above, I eliminated unnecessary text change callbacks inside the for a loop.
lib/phobia.txt
test1-test2-test3-test4-test5

Let me know if this is the expected scenario.
Hope this helps.


text:
Q: Adding address book in contact page I want to add an address book in my contact page and I want to do that programmatically i.e without using nib files. Can anyone suggest me a nice tutorial or sample code for that. i have used the codes of the answer given by iPatel and when i am running it is throwing exception and app is getting terminated.
thanks and regards.
Here is the edited code.
#import "ContactInfoViewController.h"

@interface ContactInfoViewController ()

@end

@implementation ContactInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor yellowColor];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(gotohomepage:)]autorelease];
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];

picker.displayedProperties = displayedItems;
[self presentModalViewController:picker animated:YES];
[picker release];

}
- (IBAction)gotohomepage:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{

ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = @"";
NSString* company = @"";
NSString *address = @"";
NSString *suburb = @"";
NSString *postalcode = @"";
NSString *state = @"";
NSString *country = @"";
NSString *mobile = @"";
NSString *phone = @"";
NSString *emailid = @"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company  = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray*  allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);

for (i = 0; i < [allPeople count]; i++)
{
    ABRecordRef record = [allPeople objectAtIndex:i];

    ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
    for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
    {
        NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
        if([HomeLabel isEqualToString:@"_$!<Home>!$_"])
        {
            CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
            address = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
            suburb = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
            postalcode = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
            state = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
            country = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict,  kABPersonAddressCountryKey)];
            CFRelease(dict);
        }
        CFRelease(HomeLabel);
    }
    CFRelease(multiValue);
}
CFRelease(allPeople);

ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
    mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
    if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
    {
        mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
        NSLog(@"phone   %@",mobile);
    }
    else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
    {
        phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
        NSLog(@"phone   %@",phone);

        CFRelease(mobileLabel);
        break ;
    }
    CFRelease(mobileLabel);

}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
    value = ABMultiValueCopyValueAtIndex(multi, 0);
    emailid = (NSString*) value;
    NSLog(@"self.emailID   %@",emailid);
    CFRelease(value);
}
else
{
    for (CFIndex i = 0; i < count; i++)
    {
        label = ABMultiValueCopyLabelAtIndex(multi, i);
        value = ABMultiValueCopyValueAtIndex(multi, i);
        if (CFStringCompare(label, kABWorkLabel, 0) == 0)
        {
            emailid = (NSString*) value;
            NSLog(@"self.emailID   %@",emailid);
        }
        else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
        {
            emailid = (NSString*) value;
            NSLog(@"self.emailID   %@",emailid);
        }
        CFRelease(label);
        CFRelease(value);
    }
}
CFRelease(multi);
 CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController  *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end

A:
EDIT :

First Add all Delegate and Datasource method in your class .h file
<ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate,ABNewPersonViewControllerDelegate,ABUnknownPersonViewControllerDelegate>

Create ABPeoplePickerNavigationController
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
        [[picker navigationBar] setBarStyle:UIBarStyleBlack];
        picker.peoplePickerDelegate = self;
        // Display only a person's phone, email, and birthdate
        NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];

        picker.displayedProperties = displayedItems;
        // Show the picker
        [self presentModalViewController:picker animated:YES];
        [picker release];

Add Following Delegate and DataSource method of ABPeopelPickerNavigationController
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    return YES;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
    return YES;
}

please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    ABAddressBookRef addressBook = ABAddressBookCreate();

    int i;
    NSString *strName = @"";
    NSString* company = @"";
    NSString *address = @"";
    NSString *suburb = @"";
    NSString *postalcode = @"";
    NSString *state = @"";
    NSString *country = @"";
    NSString *mobile = @"";
    NSString *phone = @"";
    NSString *emailid = @"";

    strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
    CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
    company  = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);

    NSArray*  allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
    CFRelease(name);

    for (i = 0; i < [allPeople count]; i++)
    {
        ABRecordRef record = [allPeople objectAtIndex:i];

        ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
        for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
        {
            NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
            if([HomeLabel isEqualToString:@"_$!<Home>!$_"])
            {
                CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
                address = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
                suburb = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
                postalcode = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
                state = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
                country = [NSString stringWithFormat:@"%@", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];

                CFRelease(dict);
            }
            CFRelease(HomeLabel);
        }
        CFRelease(multiValue);
    }
    CFRelease(allPeople);

    ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString* mobileLabel = nil;
    for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
    {
        mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
        if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
        {
            mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
            NSLog(@"phone   %@",mobile);
        }
        else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
        {
            phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
            NSLog(@"phone   %@",phone);

            CFRelease(mobileLabel);
            break ;
        }
        CFRelease(mobileLabel);

    }
    CFStringRef value, label;
    ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
    CFIndex count = ABMultiValueGetCount(multi);
    if (count == 1)
    {
        value = ABMultiValueCopyValueAtIndex(multi, 0);
        emailid = (NSString*) value;
        NSLog(@"self.emailID   %@",emailid);
        CFRelease(value);
    }
    else
    {
        for (CFIndex i = 0; i < count; i++)
        {
            label = ABMultiValueCopyLabelAtIndex(multi, i);
            value = ABMultiValueCopyValueAtIndex(multi, i);

            // check for Work e-mail label
            if (CFStringCompare(label, kABWorkLabel, 0) == 0)
            {
                emailid = (NSString*) value;
                NSLog(@"self.emailID   %@",emailid);
            }
            else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
            {
                emailid = (NSString*) value;
                NSLog(@"self.emailID   %@",emailid);
            }

            CFRelease(label);
            CFRelease(value);
        }
    }
    CFRelease(multi);

        }

    CFRelease(phones);
    CFRelease(addressBook);
    [self dismissModalViewControllerAnimated:YES];

    return NO;

}

For more information read this and this tutorial.
Thanks :)


text:
Q: webview draw white trace over other layout when moving I'm moving a webview inside a nested layout. The webview is positioned behind the others part of the view (drawn first).When I rotate it and a corner goes under another part of the layout (atop of the webview), the part of the view supposed to cover the webview become white.
I managed to correct this bug by redrawing the view when I'm moving the webview. However, I am now trying to use animation. I cannot redraw the whole thing during the animation (or I didn't find how to do it), so now a ugly white trace is left over the other view during the animation duration. How can I get ride of that?
Here is my XML layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:background="#00000000"
android:id="@+id/root">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_horizontal"
    android:layout_alignParentLeft="false"
    android:layout_marginLeft="0dp"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:id="@+id/AdContent"
    android:layout_above="@+id/FollowAd"
    android:layout_below="@+id/DateView">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/SlideBg"
        android:layout_gravity="center"
        android:visibility="visible">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/DismissBg"
            android:scaleType="centerInside"
            android:src="@drawable/icon_widget_unlock_ad_a"
            android:background="#ff6eff21" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/FollowBg"
            android:scaleType="centerInside"
            android:src="@drawable/icon_widget_unlock_a"
            android:background="#ff6eff21" />
    </LinearLayout>

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webView"
        android:layout_gravity="center"
        android:background="#00000000"
        android:theme="@android:style/Theme.Translucent" />
</FrameLayout>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/DateView"
    android:background="#ff000000"
    android:layout_alignParentTop="true"
    android:maxLines="1"
    android:gravity="center_horizontal" />

<SurfaceView
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:id="@+id/surfaceView"
    android:layout_alignBottom="@+id/NavigLogo"
    android:layout_below="@+id/AdContent"
    android:background="#ff000000"
    android:layout_alignParentBottom="true" />

<ImageView
android:layout_width="50dp"
android:layout_height="40dp"
android:id="@+id/FollowAd"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="false"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:layout_alignParentBottom="true"
android:paddingLeft="10dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:src="@drawable/icon_widget_unlock_w"/>

<ImageView
    android:layout_width="50dp"
    android:layout_height="40dp"
    android:id="@+id/DismissAd"
    android:layout_alignParentEnd="false"
    android:layout_alignParentRight="true"
    android:layout_alignParentLeft="false"
    android:layout_alignParentStart="false"
    android:layout_alignParentBottom="true"
    android:paddingRight="10dp"
    android:layout_marginBottom="20dp"
    android:src="@drawable/icon_widget_unlock_ad_w"/>

<ImageView
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:id="@+id/NavigLogo"
    android:src="@drawable/logo_rond"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="10dp" />

A: I managed to work around this bug.
RotateAnimation rotateAnimationWeb = new RotateAnimation([...]){
        @Override
        protected void applyTransformation(float i, Transformation t){
            super.applyTransformation(i, t);
            DateView.invalidate();
        }
    };

I override the applyTransformation function of the rotate function so that the Dateview is redrawn each time the rotation is done. But this is not a real solution, since the problem is still there, and this means adding more work on top of the animation, which can be heavy.


text: Q: HttpSession Attribute vs SessionScoped CDI Bean In my project I have a @Stateful UserSessionData bean that only stores user data. Upon a user logging in, it gets brought forth with a JNDI lookup, populated, and stored in a HttpSession attribute. My question is: shouldn't I instead create a @SessionScoped UserSessionData CDI bean and inject and populate it in my login bean? Then I can inject it in the backing beans that need the data instead of using HttpSession.getAttribute. What is the preferred method?


text:
Q: Adjust insets of UISearchController's searchBar I'm trying out some designs and I'd like to have an equal 25px margin for all my subviews. UISearchController's searchBar has a 16px padding on either sides out of the box. Do I have to write the search bar textfield from scratch, or is there ANY way, undocumented, swizzling, or otherwise, to accomplish offsetting the native bar to my taste?

A: If you are using a UISearchController you can set the margins of the searchBar like this (assuming searchBar is the UISearchController instance):
let directionalMargins = NSDirectionalEdgeInsets(top: 0, leading: 25, bottom: 0, trailing: 25)
searchController.searchBar.directionalLayoutMargins = directionalMargins

A: For UISearchBar text position use:
searchBar.searchTextPositionAdjustment = .init(horizontal: 25, vertical: 0)


text:
Q: Multiplication of large numbers, e.g. $97\times 96$: why does this work?
I've seen various versions of the above image floating around social media on how to multiply large numbers in your head. I know it doesn't work for all numbers, but why does it work for some numbers and what is the rule for knowing whether it will work or not for a certain pair of numbers? A brief Google search didn't pull anything up for me, but perhaps I missed something. I tried multiplying 97 and 96, 98 and 99, 90 and 90, 89 and 89, 89 and 87, and then  I tried 50 and 50, the first for which it didn't work for me, and I could not figure out why. Thanks so much!

A: $(A-B)(A-C)\;=\;A^2-AB-AC+BC\;=\;A(A-(B+C))+BC.$
Therefore, with $A=10^2$ and $B=3$ and $C=4$, we have  $$(97)(96)=(10^2-3)(10^2-4)=10^2(10^2-(3+4))+3\cdot 4= (100)(93) +12.$$
Another example: $(91)(92)=10^2(10^2-(9+8))+9\cdot8=8300 +72.$


text:
Q: Improving my OLS Rolling Regression with lapply This is the code of my rolling regression:
# betas from rolling regression will be in betas_rolling_250 matrix
fixed.window<-30
models<-c("A~B+E","A~B+C","A~B+D","A~B+C","A~B+F","A~B+B","A~B+F","A~B+C")
betas_rolling_250<-matrix(,nrow=length(models),ncol=250-fixed.window)
rownames(betas_rolling_250)<-models;

#Sample Matrix

sample_matrix_250<-matrix(rexp(10, rate=.1),nrow=250, ncol=6)
colnames(sample_matrix_250)<-c("A","B","C","D","E","F")

for(i in 1:(length(sample_matrix_250[,1])-fixed.window)){
  for(k in 1:length(rownames(betas_rolling_250))){
    coefs<-lm(rownames(betas_rolling_250)[k],data=as.data.frame(sample_matrix_250[(221-i):(251-i),]))$coefficients[3]
    betas_rolling_250[k,i]<-coefs }
}

First question:
Is it possible to implement this by using lapply function?
I am asking this beacause I will have to do this 4 times. Because I have more 4 differents size dataframes: (sample_matrix_220, sample_matrix_200and sample_matrix_180). I dont want my code to be huge.
Ive been thinking in using list. Thats why I though about lapply function.
Is it possible?

A: Consider generalizing your setup by passing the only changed variable, matrix column size, as input parameter. Then, past list of numeric values into an lapply call.
Below replaces any 250 to a variable (adjust as needed). The static models and fixed.window should be assigned once outside the function.
get_coeffs <- function(mat_size) {
    betas_rolling <- matrix(,nrow=length(models), ncol=mat_size-fixed.window)
    rownames(betas_rolling) <- models

    sample_matrix <- matrix(rexp(10, rate=.1), nrow=mat_size, ncol=6)
    colnames(sample_matrix) <- LETTERS[1:6]

    for(i in 1:(length(sample_matrix[,1])-fixed.window)){
       for(k in 1:length(rownames(betas_rolling))){
          coefs <- lm(rownames(betas_rolling)[k],
                      as.data.frame(sample_matrix[(mat_size-fixed.window)-i):(mat_size+1-i),]))$coefficients[3]
          betas_rolling[k,i] <- coefs
       }
    }

    return(betas_rolling)
}

matrix_list <- lapply(c(180, 200, 220, 250), get_coeffs)


text:
Q: What's the best way to mutate complex state in React.js? Here's a simple React component that renders a list, when a list item get clicked, the item adds a className called selected.
var CX = React.addons.classSet;
var List = React.createClass({
  getInitialState: function(){
    return {
      items: this.props.items
    }
  },

  handleItemClick: function(item){
    item.isSelected = true;
    //hack
    this.forceUpdate();
  },

  render: function(){
    var self = this;
    var items = this.state.items.map(function(item, index){
      var className = CX({
        'item': true,
        'selected': item.isSelected
      });
      return (

            item.name

      );
    });

    return (

        {items}

    );
  }
});

var items = [{
  name: 'Apple',
  value: 1
}, {
  name: 'Microsoft',
  value: 2
}];

React.renderComponent(<List items={items} />, document.body);

Question is, since the state is a reference type that holds an array of object, and in my event handler handleItemClick I only get the corresponding item. I currently mutate the item directly then call this.forceUpdate(), the result is as expected.
However as React documentation suggests, mutating the state directly is a bad behaviour, and I come across the other method that use React.addons.update to mutate a complex object, but I didn't get it working.
So, can anyone tell me how to do this mutation properly? Thanks in advance!
React.addons.update

A: I could be wrong (haven't really used React.addons.update), but I guess it looks something like
var index = this.state.items.indexOf(item);
var mutation = {}; // can't have dynamic keys in object literals :( [ yet :) ]
mutation[index] = {isSelected: {$set: true}};
var newData = React.addons.update(this.state.items, mutation);
// `mutation` looks something like
// {0: {isSelected: {$set: true}}}
// i.e. set `isSelected` of the element at index 0 to true

It would be a bit simpler if you bound the index instead of the item.


text:
Q: Websocket Connection using CURL Had a question about how to use CURL to initiate a WebSocket connection to a server to read from it.
Been referring to the below:
curl --include \
     --no-buffer \
     --header "Connection: Upgrade" \
     --header "Upgrade: websocket" \
     --header "Host: example.com:80" \
     --header "Origin: http://example.com:80" \
     --header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
     --header "Sec-WebSocket-Version: 13" \
     http://example.com:80/

From the below links
How to read websocket response in linux shell
Test a WebSocket using curl.

*

*Question
We have a secure WebSocket connection. How would I go about doing the same above for a [wss] secure WebSocket connection, and add certs to it as well? I have not been able to find the "Sec-WebSocket-Key:", where would this usually be at?
P.S Also wondering if the secure WebSocket connection can be made using Postman?


text:
Q: Error adding a repository to /etc/apt/sources.list On ubuntu 14.04, I followed http://mirror.its.dal.ca/cran/bin/linux/ubuntu/README which says
Installation and compilation of R or some of its packages may require Ubuntu packages from the "backports" repositories. In particular, this is the case for Tcl/Tk 8.5 on Hardy. Therefore, it is suggested to activate the backports repositories with an entry like

   deb http://<my.favorite.ubuntu.mirror>/ raring-backports main restricted universe

in your /etc/apt/sources.list file. See https://launchpad.net/ubuntu/+archivemirrors for the list of Ubuntu mirrors.

So in https://launchpad.net/ubuntu/+archivemirrors, I chose "Open Computing Facility at UC Berkeley", and copied the link (http://mirrors.ocf.berkeley.edu/ubuntu/) of its "http", and add to my /etc/apt/sources.list:
deb http://mirrors.ocf.berkeley.edu/ubuntu/ raring-backports main restricted universe

When I run sudo apt-get update, I run into the following errors:
Err http://mirrors.ocf.berkeley.edu raring-backports/main amd64 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/restricted amd64 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/universe amd64 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/main i386 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/restricted i386 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/universe i386 Packages
  404  Not Found
Ign http://mirrors.ocf.berkeley.edu raring-backports/main Translation-en_US
Ign http://mirrors.ocf.berkeley.edu raring-backports/main Translation-en
Ign http://mirrors.ocf.berkeley.edu raring-backports/restricted Translation-en_US
Ign http://mirrors.ocf.berkeley.edu raring-backports/restricted Translation-en
Ign http://mirrors.ocf.berkeley.edu raring-backports/universe Translation-en_US
Ign http://mirrors.ocf.berkeley.edu raring-backports/universe Translation-en
W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/main/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/restricted/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/universe/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/main/binary-i386/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/restricted/binary-i386/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/universe/binary-i386/Packages  404  Not Found

E: Some index files failed to download. They have been ignored, or old ones used instead.

The whole output is at the end of this post. I wonder why the problem happens and how to solve it?
Thanks!
$ sudo apt-get update
Ign http://us.archive.ubuntu.com trusty InRelease
Ign http://security.ubuntu.com trusty-security InRelease
Ign http://us.archive.ubuntu.com trusty-updates InRelease
Hit http://security.ubuntu.com trusty-security Release.gpg
Ign http://dl.google.com stable InRelease
Ign http://us.archive.ubuntu.com trusty-backports InRelease
Hit http://security.ubuntu.com trusty-security Release
Hit http://us.archive.ubuntu.com trusty Release.gpg
Hit http://us.archive.ubuntu.com trusty-updates Release.gpg
Hit http://security.ubuntu.com trusty-security/main Sources
Hit http://us.archive.ubuntu.com trusty-backports Release.gpg
Hit http://security.ubuntu.com trusty-security/restricted Sources
Hit http://us.archive.ubuntu.com trusty Release
Hit http://security.ubuntu.com trusty-security/universe Sources
Hit http://us.archive.ubuntu.com trusty-updates Release
Hit http://us.archive.ubuntu.com trusty-backports Release
Hit http://security.ubuntu.com trusty-security/multiverse Sources
Ign http://archive.canonical.com trusty InRelease
Hit http://us.archive.ubuntu.com trusty/main Sources
Hit http://security.ubuntu.com trusty-security/main amd64 Packages
Hit http://us.archive.ubuntu.com trusty/restricted Sources
Ign http://extras.ubuntu.com trusty InRelease
Hit http://security.ubuntu.com trusty-security/restricted amd64 Packages
Hit http://us.archive.ubuntu.com trusty/universe Sources
Hit http://security.ubuntu.com trusty-security/universe amd64 Packages
Hit http://us.archive.ubuntu.com trusty/multiverse Sources
Ign http://stat.ethz.ch trusty/ InRelease
Hit http://security.ubuntu.com trusty-security/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com trusty/main amd64 Packages
Hit http://security.ubuntu.com trusty-security/main i386 Packages
Hit http://us.archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://security.ubuntu.com trusty-security/restricted i386 Packages
Ign http://archive.canonical.com trusty InRelease
Hit http://us.archive.ubuntu.com trusty/universe amd64 Packages
Hit http://security.ubuntu.com trusty-security/universe i386 Packages
Hit http://extras.ubuntu.com trusty Release.gpg
Hit http://us.archive.ubuntu.com trusty/multiverse amd64 Packages
Hit http://security.ubuntu.com trusty-security/multiverse i386 Packages
Hit http://us.archive.ubuntu.com trusty/main i386 Packages
Hit http://security.ubuntu.com trusty-security/main Translation-en
Ign http://mirrors.ocf.berkeley.edu raring-backports InRelease
Hit http://us.archive.ubuntu.com trusty/restricted i386 Packages
Hit http://security.ubuntu.com trusty-security/multiverse Translation-en
Ign http://dl.google.com stable InRelease
Hit http://security.ubuntu.com trusty-security/restricted Translation-en
Hit http://archive.canonical.com trusty Release.gpg
Hit http://stat.ethz.ch trusty/ Release.gpg
Hit http://extras.ubuntu.com trusty Release
Hit http://us.archive.ubuntu.com trusty/universe i386 Packages
Ign http://mirrors.ocf.berkeley.edu raring-backports Release.gpg
Hit http://us.archive.ubuntu.com trusty/multiverse i386 Packages
Hit http://dl.google.com stable Release.gpg
Hit http://security.ubuntu.com trusty-security/universe Translation-en
Hit http://archive.canonical.com trusty Release.gpg
Hit http://us.archive.ubuntu.com trusty/main Translation-en
Hit http://dl.google.com stable Release.gpg
Hit http://stat.ethz.ch trusty/ Release
Hit http://us.archive.ubuntu.com trusty/multiverse Translation-en
Hit http://extras.ubuntu.com trusty/main Sources
Hit http://dl.google.com stable Release
Ign http://mirrors.ocf.berkeley.edu raring-backports Release
Hit http://us.archive.ubuntu.com trusty/restricted Translation-en
Hit http://archive.canonical.com trusty Release
Hit http://dl.google.com stable Release
Hit http://us.archive.ubuntu.com trusty/universe Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/main Sources
Hit http://us.archive.ubuntu.com trusty-updates/restricted Sources
Hit http://dl.google.com stable/main amd64 Packages
Hit http://us.archive.ubuntu.com trusty-updates/universe Sources
Hit http://extras.ubuntu.com trusty/main amd64 Packages
Hit http://stat.ethz.ch trusty/ Packages
Hit http://us.archive.ubuntu.com trusty-updates/multiverse Sources
Hit http://archive.canonical.com trusty Release
Hit http://us.archive.ubuntu.com trusty-updates/main amd64 Packages
Hit http://dl.google.com stable/main i386 Packages
Hit http://us.archive.ubuntu.com trusty-updates/restricted amd64 Packages
Hit http://us.archive.ubuntu.com trusty-updates/universe amd64 Packages
Hit http://us.archive.ubuntu.com trusty-updates/multiverse amd64 Packages
Hit http://extras.ubuntu.com trusty/main i386 Packages
Hit http://us.archive.ubuntu.com trusty-updates/main i386 Packages
Hit http://archive.canonical.com trusty/partner Sources
Hit http://dl.google.com stable/main amd64 Packages
Hit http://us.archive.ubuntu.com trusty-updates/restricted i386 Packages
Hit http://us.archive.ubuntu.com trusty-updates/universe i386 Packages
Hit http://dl.google.com stable/main i386 Packages
Hit http://us.archive.ubuntu.com trusty-updates/multiverse i386 Packages
Hit http://archive.canonical.com trusty/partner amd64 Packages
Hit http://us.archive.ubuntu.com trusty-updates/main Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/multiverse Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/restricted Translation-en
Hit http://us.archive.ubuntu.com trusty-updates/universe Translation-en
Hit http://us.archive.ubuntu.com trusty-backports/main Sources
Ign https://private-ppa.launchpad.net precise InRelease
Hit http://us.archive.ubuntu.com trusty-backports/restricted Sources
Hit http://archive.canonical.com trusty/partner i386 Packages
Hit http://us.archive.ubuntu.com trusty-backports/universe Sources
Hit http://us.archive.ubuntu.com trusty-backports/multiverse Sources
Hit http://us.archive.ubuntu.com trusty-backports/main amd64 Packages
Hit http://us.archive.ubuntu.com trusty-backports/restricted amd64 Packages
Hit http://us.archive.ubuntu.com trusty-backports/universe amd64 Packages
Hit https://private-ppa.launchpad.net precise Release.gpg
Hit http://us.archive.ubuntu.com trusty-backports/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com trusty-backports/main i386 Packages
Hit http://us.archive.ubuntu.com trusty-backports/restricted i386 Packages
Hit http://archive.canonical.com trusty/partner Sources
Hit https://private-ppa.launchpad.net precise Release
Hit http://us.archive.ubuntu.com trusty-backports/universe i386 Packages
Hit http://us.archive.ubuntu.com trusty-backports/multiverse i386 Packages
Hit http://us.archive.ubuntu.com trusty-backports/main Translation-en
Hit http://us.archive.ubuntu.com trusty-backports/multiverse Translation-en
Hit http://archive.canonical.com trusty/partner amd64 Packages
Hit http://us.archive.ubuntu.com trusty-backports/restricted Translation-en
Hit http://us.archive.ubuntu.com trusty-backports/universe Translation-en
Hit https://private-ppa.launchpad.net precise/main amd64 Packages
Hit http://archive.canonical.com trusty/partner i386 Packages
Hit https://private-ppa.launchpad.net precise/main i386 Packages
Ign http://us.archive.ubuntu.com trusty/main Translation-en_US
Ign http://us.archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://us.archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://us.archive.ubuntu.com trusty/universe Translation-en_US
Ign http://dl.google.com stable/main Translation-en_US
Ign http://extras.ubuntu.com trusty/main Translation-en_US
Ign http://dl.google.com stable/main Translation-en
Ign http://dl.google.com stable/main Translation-en_US
Ign http://dl.google.com stable/main Translation-en
Ign http://archive.canonical.com trusty/partner Translation-en
Ign http://extras.ubuntu.com trusty/main Translation-en
Ign http://stat.ethz.ch trusty/ Translation-en_US
Ign http://archive.canonical.com trusty/partner Translation-en
Ign http://stat.ethz.ch trusty/ Translation-en
Ign https://private-ppa.launchpad.net precise/main Translation-en_US
Ign https://private-ppa.launchpad.net precise/main Translation-en
Err http://mirrors.ocf.berkeley.edu raring-backports/main amd64 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/restricted amd64 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/universe amd64 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/main i386 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/restricted i386 Packages
  404  Not Found
Err http://mirrors.ocf.berkeley.edu raring-backports/universe i386 Packages
  404  Not Found
Ign http://mirrors.ocf.berkeley.edu raring-backports/main Translation-en_US
Ign http://mirrors.ocf.berkeley.edu raring-backports/main Translation-en
Ign http://mirrors.ocf.berkeley.edu raring-backports/restricted Translation-en_US
Ign http://mirrors.ocf.berkeley.edu raring-backports/restricted Translation-en
Ign http://mirrors.ocf.berkeley.edu raring-backports/universe Translation-en_US
Ign http://mirrors.ocf.berkeley.edu raring-backports/universe Translation-en
W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/main/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/restricted/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/universe/binary-amd64/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/main/binary-i386/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/restricted/binary-i386/Packages  404  Not Found

W: Failed to fetch http://mirrors.ocf.berkeley.edu/ubuntu/dists/raring-backports/universe/binary-i386/Packages  404  Not Found

E: Some index files failed to download. They have been ignored, or old ones used instead.

A: Support for Ubuntu 13.04 "Raring Ringtail" ended 2014-01-27 so most mirrors don't provide raring-backports any more.
As you are using Ubuntu 14.04 und already have trusty-backports activated there isn't any reason to use the package source anyway. Just remove it.

A: The README seems to be outdated (you don't want raring backports). Just add a line for a CRAN mirror, e.g. the CRAN master in Vienna:
deb http://cran.at.r-project.org/bin/linux/ubuntu trusty/

Alternatively you could use the Ubuntu R PPA, which can be added using the following syntax:
sudo add-apt-repository ppa:marutter/rrutter

A: Remove this line:
deb http://mirrors.ocf.berkeley.edu/ubuntu/ raring-backports main restricted universe

and use this list to select a mirror.
As Florian Diesch has already answered:

Support for Ubuntu 13.04 "Raring Ringtail" ended 2014-01-27 so most
  mirrors don't provide raring-backports any more.


text:
Q: Catch all exceptions in Javascript Class methods Is there a way to catch all exceptions in Javascript Class methods?
class Foo {
  method1() {}
  method2() {}
  methodToCatchAllError() {}
}

And handle the exceptions local to this class?
In the similar way rescue_from works in Ruby

A: One way to do it without repeating yourself for every method would be for the constructor to return a Proxy, and when a method is accessed, return that method wrapped in a try//catch:

const handler = {
  get(target, prop) {
    return !Foo.prototype.hasOwnProperty(prop)
      ? target[prop]
      : function(...args) {
        try {
          target[prop].apply(this, args);
        } catch(e) {
          target.methodToCatchAllError('Error thrown...');
        }
      };
  }
};
class Foo {
  constructor(id) {
    this.id = id;
    return new Proxy(this, handler);
  }
  method1() {
    console.log(this.id);
  }
  method2() {
    throw new Error();
  }
  methodToCatchAllError(error) {
    console.log('Caught:', error);
  }
}

const f = new Foo(5);
f.method1();
f.method2();

Still, this is pretty weird, and Proxies are slow. I wouldn't recommend it.


text:
Q: ArchBang - Missing wireless interface, or how to remap fn+F1-F1 Hello I am using ArchBang on old laptop Dell D410 (Dell D410 Technical Specification). I have troubles with wifi. My assumption (please read bellow explanation why I deducted this) is that I cannot even enable the wifi adapter with keyboard shortcuts (fn+F2). Before current installation of ArchBang release, the box was running on Windows XP with legacy version (unfortunately I do not remember the exact version) of ArchBang in dual boot. On Windows XP the wifi was running correctly. On legacy  version of ArchBang there was the same problem which I have with actual version of ArchBang. When I tried to enable wifi (using fn+F2) on legacy ArchBang the message: "problem with mapping of keyboard shortcut (or something similar)" was written to dmesg (or maybe /var/log/messages sorry I do not remember exactly). The box was then reinstalled to recent version of ArchBang hoping it will solve the problem. Now when I press fn+F2 I do not get any message not in dmesg nor in /var/log/messages. However I've tried to issue xev and see what happens: and the result is that all shortcuts (brightness, sound control etc.) are working fine (also in real, and in the xev the codes are returned as well), except those which controls wifi (fn+F2). So my assumption is that I have problem not directly with wifi but with enabling the adapter. Wireless is enabled in BIOS, the wireless LED is not flashing. Can I issue some command from command line to enable wifi interface instead of using fn+F2 shortcut? Bellow are output of commands that I have issued:
[root@arch ~]$ uname -a
Linux arch 3.11.5-1-ARCH #1 SMP PREEMPT Mon Oct 14 08:49:01 CEST 2013 i686 GNU/Linux

[root@arch ~]# ifconfig -a
enp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.170  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::212:3fff:fe21:70fe  prefixlen 64  scopeid 0x20<link>
        ether 00:12:3f:21:70:fe  txqueuelen 1000  (Ethernet)
        RX packets 1369  bytes 1326271 (1.2 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1250  bytes 160246 (156.4 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 16

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 0  (Local Loopback)
        RX packets 4  bytes 240 (240.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 4  bytes 240 (240.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@arch ~]# dmesg | grep -i wireless
[    9.064627] ipw2200: Intel(R) PRO/Wireless 2200/2915 Network Driver, 1.2.2kmprq
[    9.065083] ipw2200: Detected Intel PRO/Wireless 2200BG Network Connection

[root@arch ~]# lshw -C network
  *-network
       description: Ethernet interface
       product: NetXtreme BCM5751 Gigabit Ethernet PCI Express
       vendor: Broadcom Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       logical name: enp1s0
       version: 01
       serial: 00:12:3f:21:70:fe
       size: 100Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm vpd msi pciexpress bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.132 duplex=full firmware=5751-v3.29a ip=192.168.1.170 latency=0 link=yes multicast=yes port=twisted pair speed=100Mbit/s
       resources: irq:16 memory:dfdf0000-dfdfffff
  *-network UNCLAIMED
       description: Network controller
       product: PRO/Wireless 2200BG [Calexico2] Network Connection
       vendor: Intel Corporation
       physical id: 3
       bus info: pci@0000:02:03.0
       version: 05
       width: 32 bits
       clock: 33MHz
       capabilities: pm cap_list
       configuration: latency=64 maxlatency=24 mingnt=3
       resources: memory:dfcff000-dfcfffff

[root@arch ~]# lsmod | grep -i intel
snd_intel8x0           23721  1
snd_ac97_codec         89336  1 snd_intel8x0
snd_pcm                63876  2 snd_ac97_codec,snd_intel8x0
snd_page_alloc          5974  2 snd_intel8x0,snd_pcm
snd                    44566  6 snd_ac97_codec,snd_intel8x0,snd_timer,snd_pcm
intel_agp               8688  1 i915
intel_gtt              10172  3 i915,intel_agp
agpgart                22047  3 drm,intel_agp,intel_gtt
[root@arch ~]# lsmod | grep -i ipw2200
ipw2200               128525  0
libipw                 22318  1 ipw2200
lib80211                3037  2 libipw,ipw2200
cfg80211              336964  2 libipw,ipw2200

[root@arch ~]# modinfo ipw2200
filename:       /lib/modules/3.11.5-1-ARCH/kernel/drivers/net/wireless/ipw2x00/ipw2200.ko.gz
firmware:       ipw2200-bss.fw
firmware:       ipw2200-sniffer.fw
firmware:       ipw2200-ibss.fw
license:        GPL
author:         Copyright(c) 2003-2006 Intel Corporation
version:        1.2.2kmprq
description:    Intel(R) PRO/Wireless 2200/2915 Network Driver
srcversion:     DC12C86CD79304BB5E0D6DB
alias:          pci:v00008086d00004224sv*sd*bc*sc*i*
alias:          pci:v00008086d00004223sv*sd*bc*sc*i*
alias:          pci:v00008086d00004221sv*sd*bc*sc*i*
alias:          pci:v00008086d00004220sv*sd*bc*sc*i*
alias:          pci:v00008086d0000104Fsv*sd*bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002762bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002761bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002754bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002753bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002752bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002751bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002742bc*sc*i*
alias:          pci:v00008086d00001043sv0000103Csd00002741bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002741bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002732bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002731bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002722bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002721bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002712bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002711bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002702bc*sc*i*
alias:          pci:v00008086d00001043sv00008086sd00002701bc*sc*i*
depends:        cfg80211,libipw,lib80211
intree:         Y
vermagic:       3.11.5-1-ARCH SMP preempt mod_unload modversions 686
parm:           disable:manually disable the radio (default 0 [radio on]) (int)
parm:           associate:auto associate when scanning (default off) (int)
parm:           auto_create:auto create adhoc network (default on) (int)
parm:           led:enable led control on some systems (default 1 on) (int)
parm:           debug:debug output mask (int)
parm:           channel:channel to limit associate to (default 0 [ANY]) (int)
parm:           rtap_iface:create the rtap interface (1 - create, default 0) (int)
parm:           qos_enable:enable all QoS functionalitis (int)
parm:           qos_burst_enable:enable QoS burst mode (int)
parm:           qos_no_ack_mask:mask Tx_Queue to no ack (int)
parm:           burst_duration_CCK:set CCK burst value (int)
parm:           burst_duration_OFDM:set OFDM burst value (int)
parm:           mode:network mode (0=BSS,1=IBSS,2=Monitor) (int)
parm:           bt_coexist:enable bluetooth coexistence (default off) (int)
parm:           hwcrypto:enable hardware crypto (default off) (int)
parm:           cmdlog:allocate a ring buffer for logging firmware commands (int)
parm:           roaming:enable roaming support (default on) (int)
parm:           antenna:select antenna 1=Main, 3=Aux, default 0 [both], 2=slow_diversity (choose the one with lower background noise) (int)

xev:
###

fn+F2 (Wireless)
##########
KeyPress event, serial 48, synthetic NO, window 0x1e00001,
    root 0x7f, subw 0x0, time 1416790, (14,261), root:(578,476),
    state 0x0, keycode 248 (keysym 0x0, NoSymbol), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 48, synthetic NO, window 0x1e00001,
    root 0x7f, subw 0x0, time 1416790, (14,261), root:(578,476),
    state 0x0, keycode 248 (keysym 0x0, NoSymbol), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

fn+F3 (Some battery event - No one knows because batery is old and not used)
################################################
KeyPress event, serial 48, synthetic NO, window 0x1e00001,
    root 0x7f, subw 0x0, time 1481398, (-28,389), root:(536,604),
    state 0x0, keycode 244 (keysym 0x1008ff93, XF86Battery), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 48, synthetic NO, window 0x1e00001,
    root 0x7f, subw 0x0, time 1481398, (-28,389), root:(536,604),
    state 0x0, keycode 244 (keysym 0x1008ff93, XF86Battery), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

fn+F3 (Enables/Disable NumLock)
#####################
KeyPress event, serial 48, synthetic NO, window 0x1e00001,
    root 0x7f, subw 0x0, time 1558307, (-50,327), root:(514,542),
    state 0x0, keycode 77 (keysym 0xff7f, Num_Lock), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 48, synthetic NO, window 0x1e00001,
    root 0x7f, subw 0x0, time 1558370, (-50,327), root:(514,542),
    state 0x10, keycode 77 (keysym 0xff7f, Num_Lock), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

PS: I am writing here because this post was deleted from ArchLinux forums with statement that ArchLinux forums do not support ArchBang, so I registered do ArchBang forums but so far I am unable to post questions (there was troubles with spam or something like this, so now the registration takes longer)

A: The following command does the trick:
pacman -S ipw2200-fw
The wifi is now working but there is still issues with LED. It is not flashing nor lighting


text:
Q: Create A treenode with List I have a table in this structure
ListA   labelName
  1      Colorado
  1      Wyoming
  1      Illinois
  2      New York
  2      Ohio

I am trying to create a tree where if LISTA = 1, it goes under one node called "header one" and Colorado, Wyoming, Illinois as its Leaf and samething with value "2"... by doing this I am getting 3 "Header one" nodes instead of having all those three nodes under one...

SqlCommand cmd = con.CreateCommand();

        comd.CommandText = "SELECT * FROM myTable";
        con.Open();
        SqlDataReader reader = comd.ExecuteReader();
        while (reader.Read())
        {
            City MyData = new City();

            MyData.ListA = reader["ListA"].ToString().Trim();
            MyData.labelName = reader["labelName"].ToString().Trim();
            giveData.Add(MyData);
        }

        int count = 1;

        List<TreeNode> myNode = new List<TreeNode>();
        foreach (City MyData in giveData)
        {
            // 1st foreach
                if (MyData.ListA != "1")
                {

                    TreeNode treeNode = new TreeNode();
                    treeNode.id = count++;
                    treeNode.name = "Header One";
                    treeNode.leaf = false;

                    List<TreeNode> Level1 = new List<TreeNode>();
                    foreach (City labelName  in giveData)
                    {
                        if (labelName.ListA == "1")
                        {// 2nd foreach
                            TreeNode node1 = new TreeNode();
                            node1.id = count++;
                            node1.name = labelName.labelName;
                            node1.leaf = true;

                            Level1.Add(node1);
                        }
                    }

                    treeNode.children = Level1;
                    myNode.Add(treeNode);
            }
            else if (MyData.ListA != "2")
                {

                    TreeNode treeNode = new TreeNode();
                    treeNode.id = count++;
                    treeNode.name = "Header Two";
                    treeNode.leaf = false;

                    List<TreeNode> Level1 = new List<TreeNode>();
                    foreach (City labelName  in giveData)
                    {
                        if (labelName.ListA == "2")
                        {// 2nd foreach
                            TreeNode node1 = new TreeNode();
                            node1.id = count++;
                            node1.name = labelName.labelName;
                            node1.leaf = true;

                            Level1.Add(node1);
                        }
                    }

                    treeNode.children = Level1;
                    myNode.Add(treeNode);
            }
        }
        return JsonConvert.SerializeObject(myNode);

What would be the best way to handle this

A: What you need to do is group the data on ListA.
var groups = giveData.GroupBy(state => state.ListA);

foreach(var group in groups)
{
    //add header to treeview
    string header = group.Key;

    foreach(var state in group)
    {
        //add this state as a child of the group you just added
    }
}

I'd also suggest creating a lookup to help you map the ListA number to it's textual representation:
var headerLookup = new Dictionary<string, string>()
{
    {"1", "Header One"},
    {"2", "Header Two"},
    {"3", "Header Three"}
};

This will allow you to do the following:
string headerText = headerLookup[group.Key];


text:
Q: How to stop an unstoppable windows 7 service? I have recently installed a program that deploys an agent which "protects" from peripherals.
What it actually does at this point is to block any kind of media I plug to my PC.
I've done some checking and I found the name of this service blocking my peripherals. So, naturally, I've tried stopping it.
First I tried the sc stop, but I was denied the access.
Trying to do it by services.msc will result in not even giving me the priviledge to use stop on that service.
Same response from taskkill: Access denied...
Then I figured I'd try net stop resulting with the 2191 message which if I try net helpmsg 2191 does not give any information.
I then decided to surf Superuser and found out about these pstools. But as soon as I try to do the cmd switch with psexec -s cmd I get the message:
Couldn't install PsExec service: access is denied.
Strangely, if I try to use just psexec it does prompt me with the help info. So this was a dead end again.
After all these fails I have decided to just remove it from startup right? So I open msconfig and remove the service from startup, save and finally reboot. Unfortunately, when PC reboots so does the service. By the time I can access the task manager the service is already running, again. Can't really imagine how though.
All these access failures made me think I might not have the required privileges or something, but my user account is set as administrator so I think there's nothing more I can do.

A: What about opening regedit.exe and go to
HKLM\SYSTEM\CurrentControlSet\services\[service name]

Than change the service to disable (I think you can do that by changing the "Start" value to 4).
The valid service Start types are:

*

*SERVICE_BOOT_START (0): A device driver started by the system loader. This value is valid only for driver services.

*SERVICE_SYSTEM_START (1): A device driver started by the IoInitSystem function. This value is valid only for driver services.

*SERVICE_AUTO_START (2): A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services.

*SERVICE_DEMAND_START (3): A service started by the service control manager when a process calls the StartService function. For more information, see Starting Services on Demand.

*SERVICE_DISABLED (4): A service that cannot be started. Attempts to start the service result in the error code ERROR_SERVICE_DISABLED.

A: Use taskkill command followed by the service's process ID. This will kill the service.

A: Many security software installs a special driver that intercepts any changes to its services and processes.
However, the driver is normally not loaded in Safe Mode, so you can disable the service there. If the service is still started after reboot, you may want to find and disable the driver in Device Manager. This kind of driver is normally under the "Non-plug and play drivers" section which is viewable by selecting "Show hidden devices" from the View menu. The name of the driver is normally well-known for each provider.

A: Have you tried opening Services.msc as an administrator or running an elevated command prompt?
This should give you the required permissions to stop the task.

A: Autoruns run in administrator let you disable services at startup.

A: It could be a permission issue.
Click on Start, Services, shift + right click on Services, Run as Administrator or Run as a Different User.

A: *

*Boot into linux, mount the windows partition, load the registry hive and disable the service through the registry.

*If that doesn't work, just delete or rename the EXE file that the service starts.

A: Some services do not accept SERVICE_ACCEPT_STOP messages, by the time it was developed. And that is hard coded into the executable. Period. A workaround would be not to have it started, and as you cannot change its properties, forcibly do the following:

*

*Boot into safe mode (Windows 10 users might need msconfig > boot > safe boot)

*Regedit into HKLM > System > ControlSet001 > Services

*Locate your service entry

*Change 'Start' key to 3 (manual startup) or 4 (disabled)

If you cannot change the entry, right-click on your service name on the left pane, select 'Permissions', check that 'Everyone' has full access and try step 4 again.
Don't forget to disable safe boot from msconfig again, and reboot !

A: Boot into safe mode.
Click start. type services
disable EDPA and WDP services
in program files (x86) - delete manufacture folder.


text:
Q: Set volume for notification without set the ringtone volume I want to manage the volume of all system notifications.
If I use this the call volume is changed too.
    audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);

How can I change only the notifications volume?
Thanks

A: You can change the notification sound using Notification class. i.e
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(context.getResources().getString(R.string.app_name))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
            .setContentIntent(contentIntent).setContentText(message);

Notification notification = mBuilder.build();
notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/generic");
mNotificationManager.notify(notificationId, notification);


text:
Q: Como fazer o Hibernate Search ordenar o resultado de uma busca? Tenho uma busca indexada com o Hibernate Search mas não consigo fazer com que o Hibernate Search ordene o resultado da busca pela ordem de uma determinada coluna, como por exemplo a coluna nome.
Mas existe uma peculiaridade. Quando a busca é feito utilizando algum termo, o resultado então é ordenado perfeitamente por ordem alfabética. No entanto, se eu não colocar nenhum termo na busca (quero que retorne todos os resultados), então o Hibernate Search já não ordena mais nada.
Veja os códigos relativos as duas buscas:
Usando um filtro (funciona)
Abaixo está o meu método que busca filtrando através de um termo. Essa busca funciona perfeitamente e ordena certinho pelo nome (alfabeticamente).
public List<Colaborador> filtrar(String termo) throws DAOException {
    try {
        FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
        QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Colaborador.class).get();
        Query query = qb.keyword().onFields("nome", "email", "usuario").matching(termo).createQuery();
        FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query);

        // Ordenação ocorre corretamente aqui!
        Sort sortField = new Sort(new SortField("nome", SortField.STRING));

        fullTextQuery.setSort(sortField);
        return fullTextQuery.getResultList();
    }
    catch (Exception e) {
        logger.error("Erro ao filtrar colaboradores com termo: " + termo, e);
        throw new DAOException(e);
    }
}

Trazendo todos os registros (não funciona a ordenação)
Abaixo está um método muito similar ao que postei acima, no entanto o método abaixo apenas não ordena corretamente os registros que são retornados pelo Hibernate Search. Repare que é a mesma entidade (Colaborador.class) e mesmo assim a ordem pelo nome não funciona corretamente.
public List<Colaborador> listarColaboradores() throws DAOException {
    FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(this.entityManager);
    QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Colaborador.class).get();
    FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(qb.all().createQuery());

    // A mágica deveria ser feita aqui!
    Sort sortField = new Sort(new SortField("nome", SortField.STRING));

    fullTextQuery.setSort(sortField);
    return fullTextQuery.getResultList();
}

Alguém já passou por isso? Sabe o que pode estar acontecedo?

A: O problema estava na minha entidade.
@Entity
@Indexed
@Table(name = "my_view")
public class Colaborador implements Serializable {

    private static final long serialVersionUID = 244555315052436669L;

    @Id
    @Field(store = Store.YES, index = Index.YES, analyze = Analyze.YES)
    @Column(name = "id", insertable = false, updatable = false)
    private Long id;

    @Field(store = Store.YES, index = Index.YES, analyze = Analyze.YES)
    @Column(name = "name", insertable = false, updatable = false)
    private String nome;

    @Field(store = Store.YES, index = Index.YES, analyze = Analyze.YES)
    @Column(name = "email", insertable = false, updatable = false)
    private String email;

    @Field(store = Store.YES, index = Index.YES, analyze = Analyze.YES)
    @Column(name = "user", insertable = false, updatable = false)
    private String usuario;

    //Getters e Setters omitidos
}

Vejam que o atributo private String nome;, na qual eu quero ordenar minha busca, está anotado da seguinte maneira:
@Field(store = Store.YES, index = Index.YES, analyze = Analyze.YES)
@Column(name = "nome", insertable = false, updatable = false)
private String nome;

Fazendo pesquisas e mais pesquisas, achei um trecho na documentação do Hibernate Search que diz o seguinte:

Fields used for sorting must not be analyzed.

Então alterei o mapeamento da minha entidade para:
@Field(store = Store.YES, index = Index.YES, analyze = Analyze.NO)
@Column(name = "nome", insertable = false, updatable = false)
private String nome;

E fui testar minha aplicação. Para minha surpresa a ordenação funcionou, mas o filtro pelo atributo name, parou de funcionar. Ou seja, arrumei uma coisa e quebrei outra. E voltei as minhas pesquisas e acabei na documentação do Hibernate Search novamente.
Descobri que um mesmo atributo pode ser mapeado duas vezes para o Hibernate Search. Então você pode, em um mapeamento usar o Analyze.YES e rodar a query em cima desse mapeamento e um segundo mapeamento com Analyze.NO para fazer a ordenação. Parece complicado? Veja o código:
@Fields({
    @Field(name = "nome_ordem", store = Store.YES, index = Index.YES, analyze = Analyze.NO),
    @Field(name = "nome", store = Store.YES, index = Index.YES, analyze = Analyze.YES)
})
@Column(name = "nome", insertable = false, updatable = false)
private String nome;

Reparem que eu crio dois índices para um mesmo atributo. Um é usado como campo de filtro e o outro como ordenação. Fazendo dessa forma, consigo então buscar por esse atributo e também ordena-lo!


text:
Q: BlackBerry WebWorks app scrolling I built an app which loads data dynamically and displays it. On the simulator (Torch 9800, v.6) everything is fine, but on the real device, (same as the simulator), I have a very strange scrolling problem - the scrolling in the app is slow and jumpy. There is no JS or some thread running in the back, so scrolling should be fine. The scroller itself I accomplish by simple overflow-y:scroll.

A: This is how I solved it, since you are using html and not jQuery-mobile, I am sure you can "translate" the code to suit your language of choice.
For blackberry Os5, Os6 and Os7 using jQuery-mobile I removed the attribute "data-position: fixed" for headers and footers in pages that required inputting dates, text, e.t.c. and applied this styling:
.header {    //.footer
position:fixed;
z-index:10;
top:0;
width:100%;
}

for pages that did not neither require scrolling up and down nor inputting fields, I still applied the same styling but added the following attributes in the dynamically injected html  (you do the same for blackberry smartphones that have a virtual qwerty keyboard):
 data-position="fixed" data-tap-toggle="false"

To translate this to standard css for these properties you can look at any jquery-mobile.css file.
http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.css and look for the styling applied to .ui-header-fixed .ui-footer-fixed for example.
In my case the apps were not as smooth as the iOS and android versions but at least not as jumpy nor as slow as without the workaround.


text:
Q: Create contour from Intersecting of triangle mesh and plane i have problem with creating contour.
I have an STL file, the STL file includes many facets,by intersecting facets with cutting plane(Z=dz,x=y=0), we have an array of lines at each incremental Z.
However lines are not in order.I want to sort and connect them to form closed contour or continuous path. Please help me with a program or code to solve this problem.

A: You can do that with the Marching algorithm for contour creation, presented by Rock and Wozny (1). The idea is quite simple, you will be marching from a face to a neighbour face, determine the intersection at their common edge and proceed to the next neighbour. You will repeat this until you get to the starting face. That way you will be building closed contours. For each height flag visited edges in case there is more contours at it.

Marching algorithm, source: (1)
For the algorithm to work, you need to have topological information of the mesh. Each
face must reference its three neighboring faces and three edges. Each edge must reference
its two vertices and the two faces which define that edge (1). See (2) for how to get that information from an STL file.
Sources:

*

*(1) Utilizing Topological Information to Increase Scan Vector Generation Efficiency; Rock and Wozny (the marching algorithm)

*(2) Generating Topological Information from a "Bucket of Facets"; Rock and Wozny, 1992 (how to create topology from a STL file)


text:
Q: Swift Hides back button I want to hide the back button and set a title.
I'm using the following code:
    override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Einstellungen"
    navigationItem.hidesBackButton = true }

But the title isn't shown and the back button is still there but if I touch it nothing happens. Can anybody help me please?

A: I found a solution on my own.
If I'm setting the title and the hidesBackButton from my previous ViewController everything works fine.
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destinationVC = segue.destination as? ViewControllerFirstSettings {

        destinationVC.navigationItem.hidesBackButton = true
        destinationVC.navigationItem.title = "Einstellungen"
    }
}

A: This code may help :
 // MARK: - CUSTOM METHODS
        func createNavBar() {

            let leftNavigationButton =  UIButton()
            leftNavigationButton.setImage(UIImage(named: "ic_back.png"), forState: .Normal)
            leftNavigationButton.frame = CGRectMake(10, 10, 20, 15)
            leftNavigationButton.addTarget(self, action: "onBackButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
            let customBarItem = UIBarButtonItem(customView: leftNavigationButton)
            self.navigationItem.leftBarButtonItem = customBarItem;

            //set TitleAppIcon
            let GR = UITapGestureRecognizer(target: self, action: Selector("headerLogoTapAction:"))
            let imageView = UIImageView(frame: CGRect(x: 90, y: 0, width: ((UIScreen.mainScreen().bounds.width)/3), height: 40))
            imageView.addGestureRecognizer(GR)
            imageView.userInteractionEnabled = true
            navigationItem.titleView = imageView
        }


text:
Q: python pandas parse string based on row values I have a pandas dataframe containing several columns including 'text', 'start', 'tend', and I want to create a new column that extracts a substring of 'text' based on the 'start' and 'tend'.
text               start              tend      subtext
'Sample text'        2                 8        'mple te'
'Sample text'        4                10        'le text'

This works:
df['subtext']= df['text'].str[2:6]

This produces 'nan' instead of text:
df['subtext']= df['text'].str[df['start']:df['tend']]

I'm guessing it has something to do with passing a series rather than a single value. Any help would be appreciated, and I'm open to another approach if this strategy is bad.

A: Use apply, because each row needs to be process separately:
data = {

    "text":["sample text","sample text"],
    "start":[2,4],
    "tend":[8,10]

}
df = pd.DataFrame(data)
df['subtext']= df.apply(lambda x: x['text'][x['start']:x['tend']], 1)

Output
    text        start   tend    subtext
   sample text   2       8      ample t
   sample text   4      10      ple tex


text:
Q: Xcode 7 add trailing/leading/top/bottom constraints In Xcode 6, I could use the Editor menu to Pin:

*

*Leading Space to Superview

*Trailing Space to Superview

*Top Space to Superview

*Bottom Space to Superview

I can't find a way to do this in Xcode 7 beta. If I press the Align button in the Storyboard view, I see:

*

*Leading Edges

*Trailing Edges

*Top Edges

*Bottom Edges

Which I assume is the same thing, but they are all greyed out.
Adding these 4 constraints in Xcode 6 would have taken about 20 seconds, but it took me 30 minutes to put it in Xcode 7 and can't figure it out.

A: Well, I also meet this problem in Xcode 7.2, and have found out a way to solve it.
In Xcode 7.2 (and perhaps also in your version of Xcode), firstly select the view that you want to add constraint to, and then press the "control" button on your keyboard and keep doing it, and then drag the view to the super-view. Then a menu will appear, and then you can select to add some constraints. After adding the constraint you can release the "control" button. Note that the direction you drag will affect the available constraints at this time. For example, if you drag left, then the trailing constraint may be unavailable.

A: Unfortunately they removed this option from the Editor Menu but there is a drop-down menu. There you can select another view to which you can assign your margins. .

A: To pin Top, Bottom, Leading, and Trailing to the Superview, do this:

*

*Select the view.

*Click the Pin button (looks like a TIE Fighter).

*Under Add New Constraints, uncheck Constrain to margins.

*Click the left, right, and top and bottom beams.

If you click Add Constraints button, it will pin top, leading, and trailing to the Superview, and bottom to the Bottom Layout Guide. If you want to pin bottom to the Superview also, press the drop down arrow next to the bottom value and choose View instead of Bottom Layout Guide. Then click Add Constraints.

A: Right next to the Align button is Pin button where you can set what you want.

A:
When you add a constraint via Add New Constraints you have a choise:

*

*By default Xcode uses Safe Area - Align Top To

*

*If you select a superview - Top Space To


text:
Q: HTTPS 301 while on CloudFlare w/ Flexible SSL (Apache) I am trying to have all variations of my root domain 301 (properly) to the https:// version while using CloudFlare w/ Flexible SSL enabled and hosted on an Apache webserver.
My goal is for the following versions to always 301 to https:// domain.tld version ...

*

*http:// domain.tld

*http:// www.domain.tld

*https:// www.domain.tld

Here is the current code I have...
Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [NC]
RewriteRule ^ https://domain.tld%{REQUEST_URI} [R=301,L]

Here is the documentation CloudFlare provides for those on "Flexible SSL"; can someone please assist me with this? It will be useful for almost every domain I have w/ CloudFlare enabled. Thanks!

A: Why aren't you just trying to use the Always Use Https:// option found in your CloudFlare PageRule settings?