Programs & Examples On #Outlet

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

It also might be that you haven't declared you Dependency Injected service, as a provider in the component that you injected it to. That was my case :)

How to Update a Component without refreshing full page - Angular

To update component

 @Injectable()
    export class LoginService{
    private isUserLoggedIn: boolean = false;

    public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
    this.isUserLoggedIn= flag;
    }


public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}

Login Component ts
            Login Component{
             constructor(public service: LoginService){}

public login(){
service.setLoggedInUser(true);
}
            }
Inside Header component

 Header Component ts
        HeaderComponent {
         constructor(public service: LoginService){}

         public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
        }

template of header component: Check for user sign in here

<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>

You can use many approach like show hide using ngIf

App Component ts
AppComponent {
 public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>

You can also use service

@Injectable()
export class AppService {
private showHeader: boolean = false;

public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}

public getHeader(): boolean {
return this.showHeader;
}
}

App Component.ts
    AppComponent {
     constructor(public service: AppService){}
    }

App Component.html
    <div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
    <app-header></app-header>
    </div>
    <router-outlet></router-outlet>
    <app-footer></app-footer>

How to set Angular 4 background image?

If you plan using background images a lot throughout your project you may find it useful to create a really simple custom pipe that will create the url for you.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'asUrl'
})
export class BackgroundUrlPipe implements PipeTransform {

  transform(value: string): string {
    return `url(./images/${value})`
  }

}

Then you can add background images without all the string concatenation.

<div [ngStyle]="{ background: trls.img | asUrl }"></div>

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

'router-outlet' is not a known element

In your app.module.ts file

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
{
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
},  
{
    path: 'dashboard',
    component: DashboardComponent
}
];

@NgModule({
imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    FormsModule               
],
declarations: [
    AppComponent,  
    DashboardComponent      
],
bootstrap: [AppComponent]
})
export class AppModule {

}

Add this code. Happy Coding.

Error: Cannot match any routes. URL Segment: - Angular 2

Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx"> The resulting contents are :

Component1.html

<nav>
    <a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
    <router-outlet></router-outlet>

Component2.html

 <a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ...       </a>
 <a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]">   In Two...Go to 4 ...</a>

 <router-outlet name="nameThree"></router-outlet>
 <router-outlet name="nameFour"></router-outlet>

The '/two' represents the parent component and ['three']and ['four'] represents the link to the respective children of component2 . Component3.html and Component4.html are the same as in the question.

router.module.ts

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [

        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree'
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        }
    ]
},];

Swift error : signal SIGABRT how to solve it

If you run into this in Xcode 10 you will have to clean before build. Or, switch to the legacy build system. File -> Workspace Settings... -> Build System: Legacy Build System.

Can't bind to 'routerLink' since it isn't a known property

When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.

Passing data into "router-outlet" child components

Service:

import {Injectable, EventEmitter} from "@angular/core";    

@Injectable()
export class DataService {
onGetData: EventEmitter = new EventEmitter();

getData() {
  this.http.post(...params).map(res => {
    this.onGetData.emit(res.json());
  })
}

Component:

import {Component} from '@angular/core';    
import {DataService} from "../services/data.service";       
    
@Component()
export class MyComponent {
  constructor(private DataService:DataService) {
    this.DataService.onGetData.subscribe(res => {
      (from service on .emit() )
    })
  }

  //To send data to all subscribers from current component
  sendData() {
    this.DataService.onGetData.emit(--NEW DATA--);
  }
}

Angular2 module has no exported member

In my module i am exporting classes this way:

export { SigninComponent } from './SigninComponent';
export { RegisterComponent } from './RegisterComponent';

This allow me to import multiple classes in file from same module:

import { SigninComponent, RegisterComponent} from "../auth.module";

PS: Of course @Fjut answer is correct, but same time it doesn't support multiple imports from same file. I would suggest to use both answers for your needs. But importing from module makes folder structure refactorings more easier.

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

As for me resetConfig only works

this.router.resetConfig(newRoutes);

Or concat with previous

this.router.resetConfig([...newRoutes, ...this.router.config]);

But keep in mind that the last must be always route with path **

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

How do I create a singleton service in Angular 2?

  1. If you want to make service singleton at application level you should define it in app.module.ts

    providers: [ MyApplicationService ] (you can define the same in child module as well to make it that module specific)

    • Do not add this service in provider which creates an instance for that component which breaks the singleton concept, just inject through constructor.
  2. If you want to define singleton service at component level create service, add that service in app.module.ts and add in providers array inside specific component as shown in below snipet.

    @Component({ selector: 'app-root', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'], providers : [TestMyService] })

  3. Angular 6 provide new way to add service at application level. Instead of adding a service class to the providers[] array in AppModule , you can set the following config in @Injectable() :

    @Injectable({providedIn: 'root'}) export class MyService { ... }

The "new syntax" does offer one advantage though: Services can be loaded lazily by Angular (behind the scenes) and redundant code can be removed automatically. This can lead to a better performance and loading speed - though this really only kicks in for bigger services and apps in general.

Angular: Cannot find a differ supporting object '[object Object]'

Missing square brackets around input property may cause this error. For example:

Component Foo {
    @Input()
    bars: BarType[];
}

Correct:

<app-foo [bars]="smth"></app-foo>

Incorrect (triggering error):

<app-foo bars="smth"></app-foo>

Angular window resize event

<div (window:resize)="onResize($event)"
onResize(event) {
  event.target.innerWidth;
}

or using the HostListener decorator:

@HostListener('window:resize', ['$event'])
onResize(event) {
  event.target.innerWidth;
}

Supported global targets are window, document, and body.

Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.

Angular2 multiple router-outlet in the same template

You can not use multiple router outlets in the same template with ngIf condition. But you can use it in the way shown below:

<div *ngIf="loading">
  <span>loading true</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>

<div *ngIf="!loading">
  <span>loading false</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
  </div>

  <ng-template #template>
    <router-outlet> </router-outlet>
  </ng-template>

Angular 2 router no base href set

With angular 4 you can fix this issue by updating app.module.ts file as follows:

Add import statement at the top as below:

import {APP_BASE_HREF} from '@angular/common';

And add below line inside @NgModule

providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]

Reff: https://angular.io/api/common/APP_BASE_HREF

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

import 'rxjs/add/operator/map';

will resolve your problem

I tested it in angular 5.2.0 and rxjs 5.5.2

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

My solution is simple. I am using [href] instead of [routerLink]. I have tried all solutions for [routerLink]. None of them works in my case.

Here is my solution:

<a [href]="getPlanUrl()" target="_blank">My Plan Name</a>

Then write the getPlanUrl function in the TS file.

How to make a UILabel clickable?

Swift 3 Update

yourLabel.isUserInteractionEnabled = true

How to detect tableView cell touched or clicked in swift

Problem was solved by myself using tutorial of weheartswift

enter image description here

Could not insert new outlet connection: Could not find any information for the class named

For me it worked when on the right tab > Localization, I checked English check box. Initially only Base was checked. After that I had no more problems. Hope this helps!

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

My problem was I was registering table view cell inside dispatch queue asynchronously. If you have registered table view source and delegate reference in storyboard then dispatch queue would delay the registration of cell as name suggests it will happen asynchronously and your table view is looking for the cells.

DispatchQueue.main.async {
    self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
    self.tableView.reloadData()
}

Either you shouldn't use dispatch queue for registration OR do this:

DispatchQueue.main.async {
    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
    self.tableView.reloadData()
}

UIButton action in table view cell

With Swift 5 this is what, worked for me!!

Step 1. Created IBOutlet for UIButton in My CustomCell.swift

class ListProductCell: UITableViewCell {
@IBOutlet weak var productMapButton: UIButton!
//todo
}

Step 2. Added action method in CellForRowAtIndex method and provided method implementation in the same view controller

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListProductCell") as! ListProductCell
cell.productMapButton.addTarget(self, action: #selector(ListViewController.onClickedMapButton(_:)), for: .touchUpInside)
return cell
    }

@objc func onClickedMapButton(_ sender: Any?) {

        print("Tapped")
    }

How to set image in circle in swift

import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.black.cgColor
    image.layer.cornerRadius = image.frame.height/2
    image.clipsToBounds = true
}

If you want it on an extension

import UIKit

extension UIImageView {

    func makeRounded() {

        self.layer.borderWidth = 1
        self.layer.masksToBounds = false
        self.layer.borderColor = UIColor.black.cgColor
        self.layer.cornerRadius = self.frame.height / 2
        self.clipsToBounds = true
    }
}

That is all you need....

Class has no initializers Swift

Not a specific answer to your question but I had got this error when I hadn't set an initial value for an enum while declaring it as a property. I assigned a initial value to the enum to resolve this error. Posting here as it might help someone.

How to set image for bar button with swift?

Only two Lines of code required for this

Swift 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

Adding a view controller as a subview in another view controller

A couple of observations:

  1. When you instantiate the second view controller, you are calling ViewControllerB(). If that view controller programmatically creates its view (which is unusual) that would be fine. But the presence of the IBOutlet suggests that this second view controller's scene was defined in Interface Builder, but by calling ViewControllerB(), you are not giving the storyboard a chance to instantiate that scene and hook up all the outlets. Thus the implicitly unwrapped UILabel is nil, resulting in your error message.

    Instead, you want to give your destination view controller a "storyboard id" in Interface Builder and then you can use instantiateViewController(withIdentifier:) to instantiate it (and hook up all of the IB outlets). In Swift 3:

    let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
    

    You can now access this controller's view.

  2. But if you really want to do addSubview (i.e. you're not transitioning to the next scene), then you are engaging in a practice called "view controller containment". You do not just want to simply addSubview. You want to do some additional container view controller calls, e.g.:

    let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
    addChild(controller)
    controller.view.frame = ...  // or, better, turn off `translatesAutoresizingMaskIntoConstraints` and then define constraints for this subview
    view.addSubview(controller.view)
    controller.didMove(toParent: self)
    

    For more information about why this addChild (previously called addChildViewController) and didMove(toParent:) (previously called didMove(toParentViewController:)) are necessary, see WWDC 2011 video #102 - Implementing UIViewController Containment. In short, you need to ensure that your view controller hierarchy stays in sync with your view hierarchy, and these calls to addChild and didMove(toParent:) ensure this is the case.

    Also see Creating Custom Container View Controllers in the View Controller Programming Guide.


By the way, the above illustrates how to do this programmatically. It is actually much easier if you use the "container view" in Interface Builder.

enter image description here

Then you don't have to worry about any of these containment-related calls, and Interface Builder will take care of it for you.

For Swift 2 implementation, see previous revision of this answer.

Programmatically set image to UIImageView with Xcode 6.1/Swift

You just need to drag and drop an ImageView, create the outlet action, link it, and provide an image (Xcode is going to look in your assets folder for the name you provided (here: "toronto"))

In yourProject/ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imgView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        imgView.image = UIImage(named: "toronto")
    }
}

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

Outlets cannot be connected to repeating content iOS

For collectionView :

solution:

From viewcontroller, kindly remove the IBoutlet of colllectionviewcell

. the issue mentions the invalid of your IBOutlet. so remove all subclass which has multi-outlet(invalids) and reconnect it.

The answer is already mentioned in another question for collectionviewcell

Command failed due to signal: Segmentation fault: 11

I had this line in my code

weakSelf?.notifications = weakSelf?.notifications ?? [] + weakSelf?.chatNotificationDataSource ?? []

this cause Segmentation fault. But then i changed it in this way:

weakSelf?.notifications = (weakSelf?.notifications ?? []) + (weakSelf?.chatNotificationDataSource ?? [])

and app started working.

Custom UITableViewCell from nib in Swift

Here's my approach using Swift 2 and Xcode 7.3. This example will use a single ViewController to load two .xib files -- one for a UITableView and one for the UITableCellView.

enter image description here

For this example you can drop a UITableView right into an empty TableNib.xib file. Inside, set the file's owner to your ViewController class and use an outlet to reference the tableView.

enter image description here

and

enter image description here

Now, in your view controller, you can delegate the tableView as you normally would, like so

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Table view delegate
        self.tableView.delegate = self
        self.tableView.dataSource = self

        ...

To create your Custom cell, again, drop a Table View Cell object into an empty TableCellNib.xib file. This time, in the cell .xib file you don't have to specify an "owner" but you do need to specify a Custom Class and an identifier like "TableCellId"

enter image description here enter image description here

Create your subclass with whatever outlets you need like so

class TableCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}

Finally... back in your View Controller, you can load and display the entire thing like so

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // First load table nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let tableNib = UINib(nibName: "TableNib", bundle: bundle)
    let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView

    // Then delegate the TableView
    self.tableView.delegate = self
    self.tableView.dataSource = self

    // Set resizable table bounds
    self.tableView.frame = self.view.bounds
    self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    // Register table cell class from nib
    let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)

    // Display table with custom cells
    self.view.addSubview(tableNibView)

}

The code shows how you can simply load and display a nib file (the table), and second how to register a nib for cell use.

Hope this helps!!!

Show Current Location and Update Location in MKMapView in Swift

MyLocation is a Swift iOS Demo.

You can use this demo for the following:

  1. Show the current location.

  2. Choose other location: in this case stop tracking the location.

  3. Add a push pin to a MKMapView(iOS) when touching.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In my case I wanted to add a method with a custom swift object as a type parameter, and the name I gave to the variable in the parameter was exactly the same as the custom object class name

The problems was something like this:

func moveBlob(**blob** : blob){
    ...code
}

The part in bold characters was causing the error of undeclared type

Xcode iOS 8 Keyboard types not supported

For me turning on and off the setting on

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

proved to fix the issue on simulators.

How to use pull to refresh in Swift?

I would like to mention a PRETTY COOL feature that has been included since iOS 10, which is:

For now, UIRefreshControl is directly supported in each of UICollectionView, UITableView and UIScrollView!

Each one of these views have refreshControl instance property, which means that there is no longer a need to add it as a subview in your scroll view, all you have to do is:

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)

    // this is the replacement of implementing: "collectionView.addSubview(refreshControl)"
    collectionView.refreshControl = refreshControl
}

func doSomething(refreshControl: UIRefreshControl) {
    print("Hello World!")

    // somewhere in your code you might need to call:
    refreshControl.endRefreshing()
}

Personally, I find it more natural to treat it as a property for scroll view more than add it as a subview, especially because the only appropriate view to be as a superview for a UIRefreshControl is a scrollview, i.e the functionality of using UIRefreshControl is only useful when working with a scroll view; That's why this approach should be more obvious to setup the refresh control view.

However, you still have the option of using the addSubview based on the iOS version:

if #available(iOS 10.0, *) {
  collectionView.refreshControl = refreshControl
} else {
  collectionView.addSubview(refreshControl)
}

How to Correctly handle Weak Self in Swift Blocks with Arguments

**EDITED for Swift 4.2:

As @Koen commented, swift 4.2 allows:

guard let self = self else {
   return // Could not get a strong reference for self :`(
}

// Now self is a strong reference
self.doSomething()

P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.

EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**

For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement

guard let `self` = self else {
   return
}
self.doSomething()

If you are wondering what the quote marks are around self is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.

Remove all constraints affecting a UIView

You can remove all constraints in a view by doing this:

self.removeConstraints(self.constraints)

EDIT: To remove the constraints of all subviews, use the following extension in Swift:

extension UIView {
    func clearConstraints() {
        for subview in self.subviews {
            subview.clearConstraints()
        }
        self.removeConstraints(self.constraints)
    }
}

Shall we always use [unowned self] inside closure in Swift

Update 11/2016

I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.

Original answer

The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.

The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.

swift weak vs unowned

Scenarios

You can have two possible scenarios:

  1. The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self] used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.

  2. The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate] you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.

Actual Usage

So, which will/should you actually use most of the times?

Quoting Joe Groff from twitter:

Unowned is faster and allows for immutability and nonoptionality.

If you don't need weak, don't use it.

You'll find more about unowned* inner workings here.

* Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.

Loading/Downloading image from URL on Swift

Swift 4.1 I have crated a function just pass image url, cache key after image is generated set it to completion block.

   class NetworkManager: NSObject {

  private var imageQueue = OperationQueue()
  private var imageCache = NSCache<AnyObject, AnyObject>()

  func downloadImageWithUrl(imageUrl: String, cacheKey: String, completionBlock: @escaping (_ image: UIImage?)-> Void) {

    let downloadedImage = imageCache.object(forKey: cacheKey as AnyObject)
    if let  _ = downloadedImage as? UIImage {
      completionBlock(downloadedImage as? UIImage)
    } else {
      let blockOperation = BlockOperation()
      blockOperation.addExecutionBlock({
        let url = URL(string: imageUrl)
        do {
          let data = try Data(contentsOf: url!)
          let newImage = UIImage(data: data)
          if newImage != nil {
            self.imageCache.setObject(newImage!, forKey: cacheKey as AnyObject)
            self.runOnMainThread {
              completionBlock(newImage)
            }
          } else {
            completionBlock(nil)
          }
        } catch {
          completionBlock(nil)
        }
      })
      self.imageQueue.addOperation(blockOperation)
      blockOperation.completionBlock = {
        print("Image downloaded \(cacheKey)")
      }
    }
  }
}
extension NetworkManager {
  fileprivate func runOnMainThread(block:@escaping ()->Void) {
    if Thread.isMainThread {
      block()
    } else {
      let mainQueue = OperationQueue.main
      mainQueue.addOperation({
        block()
      })
    }
  }
}

creating custom tableview cells in swift

Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).

Converting String to Int with Swift

@IBAction func calculateAclr(_ sender: Any) {
    if let addition = addition(arrayString: [txtBox1.text, txtBox2.text, txtBox3.text]) {
      print("Answer = \(addition)")
      lblAnswer.text = "\(addition)"
    }
}

func addition(arrayString: [Any?]) -> Int? {

    var answer:Int?
    for arrayElement in arrayString {
        if let stringValue = arrayElement, let intValue = Int(stringValue)  {
            answer = (answer ?? 0) + intValue
        }
    }

    return answer
}

How to check if a text field is empty or not in swift

Maybe i'm a little too late, but can't we check like this:

   @IBAction func Button(sender: AnyObject) {
       if textField1.text.utf16Count == 0 || textField2.text.utf16Count == 0 {

       }
    }

What is the Swift equivalent of isEqualToString in Objective-C?

Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.

For example:-

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.

Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!

Convert String to Float in Swift

extension String {    
    func floatValue() -> Float? {
        return Float(self)
    }
}

How to use auto-layout to move other views when a view is hidden?

Here's how I would re-align my uiviews to get your solution:

  1. Drag drop one UIImageView and place it to the left.
  2. Drag drop one UIView and place it to the right of UIImageView.
  3. Drag drop two UILabels inside that UIView whose leading and trailing constraints are zero.
  4. Set the leading constraint of UIView containing 2 labels to superview instead of UIImagView.
  5. IF UIImageView is hidden, set the leading constraint constant to 10 px to superview. ELSE, set the leading constraint constant to 10 px + UIImageView.width + 10 px.

I created a thumb rule of my own. Whenever you have to hide / show any uiview whose constraints might be affected, add all the affected / dependent subviews inside a uiview and update its leading / trailing / top / bottom constraint constant programmatically.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

What happened with me was the Type of class was not UIViewController for the script attached to my view controller. It was for a UITabController..... I had mistakenly quickly created the wrong type of class.... So make sure the class if the correct type.. Hope this helps someone. I was in a rush and made this mistake.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

This error is something else!

Here is how i Fixed it. I'm using xcode Version 6.1.1 and using swift. I got this error every time my app tried to perform a segue to jump to the next screen. Here what I did.

  1. Checked that the button was connected to the right action.(This wasn't the problem, but still good to check)
  2. Check that the button does not have any additional actions or outlets that you may have created by mistake. (This wasn't the problem, but still good to check)
  3. Check the logs and make sure that all the buttons in the NEXT SCREEN have the correct actions, and if there are any segues, make sure that they have a unique identifier. (This was the problem)
    • One of the segues did not have a unique identifier
    • One of the buttons had an action and two outlets that I created by mistake.

Delete any additional outlets and make sure that you the segues to the next screen have unique identifiers.

Cheers,

How do I animate constraint changes?

There is an article talk about this: http://weblog.invasivecode.com/post/42362079291/auto-layout-and-core-animation-auto-layout-was

In which, he coded like this:

- (void)handleTapFrom:(UIGestureRecognizer *)gesture {
    if (_isVisible) {
        _isVisible = NO;
        self.topConstraint.constant = -44.;    // 1
        [self.navbar setNeedsUpdateConstraints];  // 2
        [UIView animateWithDuration:.3 animations:^{
            [self.navbar layoutIfNeeded]; // 3
        }];
    } else {
        _isVisible = YES;
        self.topConstraint.constant = 0.;
        [self.navbar setNeedsUpdateConstraints];
        [UIView animateWithDuration:.3 animations:^{
            [self.navbar layoutIfNeeded];
        }];
    }
}

Hope it helps.

How to set the UITableView Section title programmatically (iPhone/iPad)?

Once you have connected your UITableView delegate and datasource to your controller, you could do something like this:

ObjC

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    NSString *sectionName;
    switch (section) {
        case 0:
            sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
            break;
        case 1:
            sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
            break;
        // ...
        default:
            sectionName = @"";
            break;
    }    
    return sectionName;
}

Swift

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    let sectionName: String
    switch section {
        case 0:
            sectionName = NSLocalizedString("mySectionName", comment: "mySectionName")
        case 1:
            sectionName = NSLocalizedString("myOtherSectionName", comment: "myOtherSectionName")
        // ...
        default:
            sectionName = ""
    }
    return sectionName
}

How do I show/hide a UIBarButtonItem?

self.dismissButton.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

Should IBOutlets be strong or weak under ARC?

One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:

https://developer.apple.com/videos/play/wwdc2015/407/

Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.

This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8

As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4

As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57

As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6

As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5

As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23

All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)

Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.

I hope this clarifies the subject a bit better!

Take care.

How to load local html file into UIWebView

[[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];

It may be late but if the file from pathForResource is nil you should add it in the Build Phases > Copy Bundle Resources.

enter image description here

Loaded nib but the 'view' outlet was not set

for me it happened, when

  • I have a ViewController class ( .mm/h ) associated with the Nib file,
  • UIView from this ViewController has to be loaded on the another view as a subview,

  • we will call something like this

    -(void)initCheckView{
    
       CheckView *pCheckViewCtrl = [CheckView instance];
    
       pCheckView = [pCheckViewCtrl view];
    
       [[self view]addSubview:pCheckView];
    
       [pCheckViewCtrl performCheck];        
    
    }
    

Where

+(CheckView *)instance{
    static CheckView *pCheckView = nil;
    static dispatch_once_t checkToken;

    dispatch_once(&checkToken, ^{
        pCheckView = [[CheckView alloc]initWithNibName:@"CheckView" bundle:nil];
        if ( pCheckView){
            [pCheckView initLocal];
            **[pCheckView loadView];**
        }
    });

    return pCheckView;

}

Here loadView was missing,,, adding this line resolved my problem.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

The cause of my trouble, was that I duplicated a storyboard file (outside of Xcode if I recall correctly), then all view controllers in the duplicated file had same object-ID as in the original file. The remedy is to copy-pasted the view controllers, and they will then get a new object-ID. You can see the object-ID in the Identity Inspector.

How to store custom objects in NSUserDefaults

If anybody is looking for a swift version:

1) Create a custom class for your data

class customData: NSObject, NSCoding {
let name : String
let url : String
let desc : String

init(tuple : (String,String,String)){
    self.name = tuple.0
    self.url = tuple.1
    self.desc = tuple.2
}
func getName() -> String {
    return name
}
func getURL() -> String{
    return url
}
func getDescription() -> String {
    return desc
}
func getTuple() -> (String,String,String) {
    return (self.name,self.url,self.desc)
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as! String
    self.url = aDecoder.decodeObjectForKey("url") as! String
    self.desc = aDecoder.decodeObjectForKey("desc") as! String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.name, forKey: "name")
    aCoder.encodeObject(self.url, forKey: "url")
    aCoder.encodeObject(self.desc, forKey: "desc")
} 
}

2) To save data use following function:

func saveData()
    {
        let data  = NSKeyedArchiver.archivedDataWithRootObject(custom)
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(data, forKey:"customArray" )
    }

3) To retrieve:

if let data = NSUserDefaults.standardUserDefaults().objectForKey("customArray") as? NSData
        {
             custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [customData]
        }

Note: Here I am saving and retrieving an array of the custom class objects.

iPhone: Setting Navigation Bar Title

For all your Swift-ers out there, this worked perfectly for me. It's notably one of the shorter ways to accomplish setting the title, as well:

override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "presentLineItem" {
    print("Setting Title")
    var vc = segue.destinationViewController as! LineItemsTableViewController
    vc.navigationItem.title = "Line Item"
  }
}

IBOutlet and IBAction

IBOutlet

  • It is a property.
  • When the nib(IB) file is loaded, it becomes part of encapsulated data which connects to an instance variable.
  • Each connection is unarchived and reestablished.

IBAction

  • Attribute indicates that the method is an action that you can connect to from your storyboard in Interface Builder.

@ - Dynamic pattern IB - Interface Builder

How to load a UIView using a nib file created with Interface Builder

To programmatically load a view from a nib/xib in Swift 4:

// Load a view from a Nib given a placeholder view subclass
//      Placeholder is an instance of the view to load.  Placeholder is discarded.
//      If no name is provided, the Nib name is the same as the subclass type name
//
public func loadViewFromNib<T>(placeholder placeholderView: T, name givenNibName: String? = nil) -> T {

    let nib = loadNib(givenNibName, placeholder: placeholderView)
    return instantiateView(fromNib: nib, placeholder: placeholderView)
}

// Step 1: Returns a Nib
//
public func loadNib<T>(_ givenNibName: String? = nil, placeholder placeholderView: T) -> UINib {
    //1. Load and unarchive nib file
    let nibName = givenNibName ?? String(describing: type(of: placeholderView))

    let nib = UINib(nibName: nibName, bundle: Bundle.main)
    return nib
}

// Step 2: Instantiate a view given a nib
//
public func instantiateView<T>(fromNib nib: UINib, placeholder placeholderView: T) -> T {
    //1. Get top level objects
    let topLevelObjects = nib.instantiate(withOwner: placeholderView, options: nil)

    //2. Have at least one top level object
    guard let firstObject = topLevelObjects.first else {
        fatalError("\(#function): no top level objects in nib")
    }

    //3. Return instantiated view, placeholderView is not used
    let instantiatedView = firstObject as! T
    return instantiatedView
}

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

PHP - the Sierpinski gasket a.k.a the Triforce

OK, it's 15 lines of code but the result is awesome! That's the kind of stuff that made me freak out when I was a child. This is from the PHP manual:

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);
 
$corners[0] = array('x' => 100, 'y' =>  10);
$corners[1] = array('x' =>   0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0); 

for ($i = 0; $i < 100000; $i++) {
  imagesetpixel($gd, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}
 
header('Content-Type: image/png');
imagepng($gd);

sierpinski gasket

How can I change the image displayed in a UIImageView programmatically?

If you want to set image to UIImageView programmatically then Dont Forget to add UIImageView as SubView to the main View.

And also dont forgot to set ImageView Frame.

here is the code

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];

myImage.image = [UIImage imageNamed:@"myImage.png"];

[self.view addSubview:myImage];

How do you load custom UITableViewCells from Xib files?

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cellReuseIdentifier = "collabCell"
            var cell:collabCell! = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? collabCell
            if cell == nil {
                tableView.register(UINib(nibName: "collabCell", bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
                cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! collabCell!
            }


            return cell

}

Conda command not found

MacOSX: cd /Users/USER_NAME/anaconda3/bin && ./activate

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

How to ssh connect through python Paramiko with ppk public key

Ok @Adam and @Kimvais were right, paramiko cannot parse .ppk files.

So the way to go (thanks to @JimB too) is to convert .ppk file to openssh private key format; this can be achieved using Puttygen as described here.

Then it's very simple getting connected with it:

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')

stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()

Create listview in fragment android

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here

MetadataException when using Entity Framework Entity Connection

I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.

Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.

To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.

Why are iframes considered dangerous and a security risk?

"Dangerous" and "Security risk" are not the first things that spring to mind when people mention iframes … but they can be used in clickjacking attacks.

Better way of getting time in milliseconds in javascript?

As far that I know you only can get time with Date.

Date.now is the solution but is not available everywhere : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now.

var currentTime = +new Date();

This gives you the current time in milliseconds.

For your jumps. If you compute interpolations correctly according to the delta frame time and you don't have some rounding number error, I bet for the garbage collector (GC).

If there is a lot of created temporary object in your loop, garbage collection has to lock the thread to make some cleanup and memory re-organization.

With Chrome you can see how much time the GC is spending in the Timeline panel.

EDIT: Since my answer, Date.now() should be considered as the best option as it is supported everywhere and on IE >= 9.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

I needed the following bindings to get mine to work:

        <binding name="SI_PurchaseRequisition_ISBindingSSL">
          <security mode="Transport">
            <transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
          </security>
        </binding>

Android: keep Service running when app is killed

inside onstart command put START_STICKY... This service won't kill unless it is doing too much task and kernel wants to kill it for it...

@Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
        }

Get a list of distinct values in List

Distinct the Note class by Author

var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());

foreach(var item in DistinctItems)
{
    //Add to other List
}

Direct casting vs 'as' operator?

I would like to attract attention to the following specifics of the as operator:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

unsigned int vs. size_t

size_t is the size of a pointer.

So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits. and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).

There are other models but these are the ones that g++ use (at least by default)

How can I make PHP display the error instead of giving me 500 Internal Server Error

Be careful to check if

display_errors

or

error_reporting

is active (not a comment) somewhere else in the ini file.

My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my

display_errors = on;

So remember the last one counts!

Get current time in seconds since the Epoch on Linux, Bash

With most Awk implementations:

awk 'BEGIN {srand(); print srand()}'

Reading specific XML elements from XML file

Alternatively, you can use XPath query via XPathSelectElements method:

var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");

C# Linq Group By on multiple columns

Given a list:

var list = new List<Child>()
{
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
    new Child()
        {School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
    new Child()
        {School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};

The query would look like:

var newList = list
    .GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
    .Select(y => new ConsolidatedChild()
        {
            FavoriteColor = y.Key.FavoriteColor,
            Friend = y.Key.Friend,
            School = y.Key.School,
            Children = y.ToList()
        }
    );

Test code:

foreach(var item in newList)
{
    Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
    foreach(var child in item.Children)
    {
        Console.WriteLine("\t Name: {0}", child.Name);
    }
}

Result:

School: School1 FavouriteColor: blue Friend: Bob
    Name: John
    Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
    Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
    Name: Bob

Assign variable value inside if-statement

Yes, you can assign the value of variable inside if.

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===.

It will be better if you do something like this:

int v;
if((v = someMethod()) != 0) 
   return true;

Substitute a comma with a line break in a cell

To replace commas with newline characters use this formula (assuming that the text to be altered is in cell A1):

=SUBSTITUTE(A1,",",CHAR(10))

You may have to then alter the row height to see all of the values in the cell

I've left a comment about the other part of your question


Edit: here's a screenshot of this working - I had to turn on "Wrap Text" in the "Format Cells" dialog.

enter image description here

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

The documentation for this at the MySQL site is woefully out of date and riddled with foot-guns (such as interactive_timeout). Issuing FLUSH TABLES WITH READ LOCK as part of your export of the master generally only makes sense when coordinated with a storage/filesystem snapshot such as LVM or zfs.

If you are going to use mysqldump, you should rely instead on the --master-data option to guard against human error and release the locks on the master as quickly as possible.

Assume the master is 192.168.100.50 and the slave is 192.168.100.51, each server has a distinct server-id configured, the master has binary logging on and the slave has read-only=1 in my.cnf

To stage the slave to be able to start replication just after importing the dump, issue a CHANGE MASTER command but omit the log file name and position:

slaveserver> CHANGE MASTER TO MASTER_HOST='192.168.100.50', MASTER_USER='replica', MASTER_PASSWORD='asdmk3qwdq1';

Issue the GRANT on the master for the slave to use:

masterserver> GRANT REPLICATION SLAVE ON *.* TO 'replica'@'192.168.100.51' IDENTIFIED BY 'asdmk3qwdq1';

Export the master (in screen) using compression and automatically capturing the correct binary log coordinates:

mysqldump --master-data --all-databases --flush-privileges | gzip -1 > replication.sql.gz

Copy the replication.sql.gz file to the slave and then import it with zcat to the instance of MySQL running on the slave:

zcat replication.sql.gz | mysql

Start replication by issuing the command to the slave:

slaveserver> START SLAVE;

Optionally update the /root/.my.cnf on the slave to store the same root password as the master.

If you are on 5.1+, it is best to first set the master's binlog_format to MIXED or ROW. Beware that row logged events are slow for tables which lack a primary key. This is usually better than the alternative (and default) configuration of binlog_format=statement (on master), since it is less likely to produce the wrong data on the slave.

If you must (but probably shouldn't) filter replication, do so with slave options replicate-wild-do-table=dbname.% or replicate-wild-ignore-table=badDB.% and use only binlog_format=row

This process will hold a global lock on the master for the duration of the mysqldump command but will not otherwise impact the master.

If you are tempted to use mysqldump --master-data --all-databases --single-transaction (because you only using InnoDB tables), you are perhaps better served using MySQL Enterprise Backup or the open source implementation called xtrabackup (courtesy of Percona)

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

check your application.properties

changing

spring.datasource.driverClassName=com.mysql.jdbc.Driver

to

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

worked for me. Full config:

spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=
spring.datasource.password=   
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

Google Maps API - Get Coordinates of address

Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps

https://nominatim.openstreetmap.org/search?q=Mumbai&format=json

Here is the API documentation for reference.

Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.

How to setup virtual environment for Python in VS Code?

For Mac users, note this bug: when you click "Enter interpreter path", you have two options: (1) manually enter the path; (2) select the venv file from Finder.

It only works if I manually enter the path. Selecting with Finder yields some strange path like Library/Developer/CommandTools/... which I understand.

DateTime format to SQL format using C#

if you want to store current date in table so you can use

GETDATE();

or pass this function as a parameter

eg. 'update tblname set curdate=GETDATE() where colname=123'

Unable to run Java GUI programs with Ubuntu

Ubuntu has the option to install a headless Java -- this means without graphics libraries. This wasn't always the case, but I encountered this while trying to run a Java text editor on 10.10 the other day. Run the following command to install a JDK that has these libraries:

sudo apt-get install openjdk-6-jdk

EDIT: Actually, looking at my config, you might need the JRE. If that's the case, run:

sudo apt-get install openjdk-6-jre

Case insensitive 'in'

username = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
    ...

Alternatively:

if username.upper() in map(str.upper, USERNAMES):
    ...

Or, yes, you can make a custom method.

100% height minus header?

As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.

The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

In Python script, how do I set PYTHONPATH?

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

git remote add with other SSH port

For those of you editing the ./.git/config

[remote "external"]                                                                                                                                                                                                                                                            
  url = ssh://[email protected]:11720/aaa/bbb/ccc                                                                                                                                                                                                               
  fetch = +refs/heads/*:refs/remotes/external/* 

How to change port number for apache in WAMP

In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf and change the port:

[apache]
apachePortUsed = "8080"

Then exit and relaunch wamp.

What is the correct way to read a serial port using .NET framework?

I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.

private string buffer { get; set; }
private SerialPort _port { get; set; }

public Port() 
{
    _port = new SerialPort();
    _port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
    buffer = string.Empty;
}

private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{    
    buffer += _port.ReadExisting();

    //test for termination character in buffer
    if (buffer.Contains("\r\n"))
    {
        //run code on data received from serial port
    }
}

How do you discover model attributes in Rails?

some_instance.attributes

Source: blog

How to apply slide animation between two activities in Android?

Slide up/down with alpha animation with a few note

enter image description here

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    >
    <translate
        android:fromYDelta="100%p"
        android:toYDelta="0"/>
    <alpha
        android:fromAlpha="0.5"
        android:toAlpha="1"/>
</set>

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    >
    <translate
        android:fromYDelta="0"
        android:toYDelta="100%p"/>
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0.5"/>
</set>

no_animation.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    android:fromYDelta="0"
    android:toYDelta="0"/>

First Activity

startActivity(new Intent(this, SecondActivity.class));
overridePendingTransition(R.anim.slide_up,  R.anim.no_animation); // remember to put it after startActivity, if you put it to above, animation will not working
// document say if we don't want animation we can put 0. However, if we put 0 instead of R.anim.no_animation, the exist activity will become black when animate

Second Activity

finish();
overridePendingTransition(R.anim.no_animation, R.anim.slide_down);

Done

MORE
I try to make the slide animation like iOS animation when present a View Model (like this https://www.youtube.com/watch?v=deZobvh2064) but failed.

Looking at iOS present animation you will see: The animation from bottom with alpha (about 50%) then it go very fast then slower, the animation time is about > 500ms (I use trim video tools for count the animation time https://www.kapwing.com/trim-video so it can not exactly 100%)

Then I try to apply to android.
To make alpha I use <alpha> and success.
To make animation start faster than slower I use android:interpolator="a decelerate interpolator" but it almost failed.

There are 3 default decelerate interpolator in Android
@android:interpolator/decelerate_quad -> factor = 1
@android:interpolator/decelerate_cubic -> factor = 1.5
@android:interpolator/decelerate_quint _> factor = 2.5
(higher factor <=> animation start more faster from start and more slower at end)
Here is a good tutorial http://cogitolearning.co.uk/2013/10/android-animations-tutorial-5-more-on-interpolators/ for understand it

I tried 3 above I can not achieve like iOS, the animation can not start faster like iOS. Then I create a custom decelerateInterpolator wiht factor = 3 like

<?xml version="1.0" encoding="utf-8"?>
<decelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:factor="3" />

and I increase the duration time from 500 -> 750. It working well (very similar to iOS). However, it only working well in some device, in some device the animation is quite slow. Later on, I know that animation may different on different device (eg: some device will faster and some device will slower) so I can not make it the animation similar in all Android device. Therefore I don't use interpolator. I don't know if my testing is exactly 100% or not but I hope this experience help

Inserting the same value multiple times when formatting a string

You can use the dictionary type of formatting:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

perform an action on checkbox checked or unchecked event on html form

The currently accepted answer doesn't always work.

(To read about the problem and circumstances, read this: Defined function is "Not defined".)

So, you have 3 options:

1 (it has above-mentioned drawback)

<input type="checkbox" onchange="doAlert(this)">

<script>
function doAlert(checkboxElem) {
    if (checkboxElem.checked) {
        alert ('hi');
    } else {
        alert ('bye');
    }
}
</script>

2 and 3

<input type="checkbox" id="foo">

<script>
function doAlert() {
    var input = document.querySelector('#foo');

    // input.addEventListener('change', function() { ... });
    // or
    // input.onchange = function() { ... };
    input.addEventListener('change', function() {
        if (input.checked) {
            alert ('hi');
        } else {
            alert ('bye');
        }
    });
}

doAlert();
</script>

Press Enter to move to next control

In a KeyPress event, if the user pressed Enter, call

SendKeys.Send("{TAB}")

Nicest way to implement automatically selecting the text on receiving focus is to create a subclass of TextBox in your project with the following override:

Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
    SelectionStart = 0
    SelectionLength = Text.Length
    MyBase.OnGotFocus(e)
End Sub

Then use this custom TextBox in place of the WinForms standard TextBox on all your Forms.

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

How to get all selected values of a multiple select box?

Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:

selected = Array.prototype.filter.apply(
  select.options, [
    function(o) {
      return o.selected;
    }
  ]
);

It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.

Another approach would be using selectors:

selected = Array.prototype.map.apply(
    select.querySelectorAll('option[selected="selected"]'),
    [function (o) { return o.value; }]
);

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

Reloading .env variables without restarting server (Laravel 5, shared hosting)

I know this is old, but for local dev, this is what got things back to a production .env file:

rm bootstrap/cache/config.php

then

php artisan config:cache
php artisan config:clear
php artisan cache:clear

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

same thing JUST happened to me with NUGET.

the following tag helped

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly>

Also if this is happening on the server, I had to make sure I was running the application pool on a more "privileged account" to the file system, but I don think that's your issue here

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

eslint: error Parsing error: The keyword 'const' is reserved

I used .eslintrc.js and I have added following code.

module.exports = {
    "parserOptions": {
        "ecmaVersion": 6
    }
};

Download multiple files as a zip-file using php

You are ready to do with php zip lib, and can use zend zip lib too,

<?PHP
// create object
$zip = new ZipArchive();   

// open archive 
if ($zip->open('app-0.09.zip') !== TRUE) {
    die ("Could not open archive");
}

// get number of files in archive
$numFiles = $zip->numFiles;

// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
    $file = $zip->statIndex($x);
    printf("%s (%d bytes)", $file['name'], $file['size']);
    print "
";    
}

// close archive
$zip->close();
?>

http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/

and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php

How/when to generate Gradle wrapper files?

If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:

task wrapper(type: Wrapper) {
    gradleVersion = '2.13'
    distributionUrl = distributionUrl.replace("bin", "all")
}

CURL and HTTPS, "Cannot resolve host"

Just a note which may be helpful- I was having this trouble with Apache on my laptop (which connects by wifi AFTER startup), and restarting the server (after connect) fixed the issue. I guess in my case this may be to do with apache starting offline and perhaps there noting that DNS lookups fail?

Laravel: Auth::user()->id trying to get a property of a non-object

For Laravel 6.X you can do the following:

$user = Auth::guard(<GUARD_NAME>)->user();
$user_id = $user->id;
$full_name = $user->full_name;

Custom ImageView with drop shadow

Here the Implementation of Paul Burkes answer:

public class ShadowImageView extends ImageView {

    public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ShadowImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ShadowImageView(Context context) {
        super(context);
    }

    private Paint createShadow() {
        Paint mShadow = new Paint();

        float radius = 10.0f;
        float xOffset = 0.0f;
        float yOffset = 2.0f;

        // color=black
        int color = 0xFF000000;
        mShadow.setShadowLayer(radius, xOffset, yOffset, color);


        return mShadow;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint mShadow = createShadow();
        Drawable d = getDrawable();
        if (d != null){
            setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
        } else {
            super.onDraw(canvas);
        }

    };

}

TODO: execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow); only if API Level is > 10

Insert default value when parameter is null

Try an if statement ...

if @value is null 
    insert into t (value) values (default)
else
    insert into t (value) values (@value)

how to align text vertically center in android

just use like this to make anything to center

 android:layout_gravity="center"
 android:gravity="center"

updated :

android:layout_gravity="center|right"
android:gravity="center|right"

Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView

<LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"  >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center" 
            android:gravity="center|right"
            android:text="hello" 
            android:textSize="20dp" />
    </LinearLayout>

How can I get screen resolution in java?

Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.

  GraphicsDevice devices[];

  devices = GraphicsEnvironment.
     getLocalGraphicsEnvironment().
     getScreenDevices();

  return Stream.
     of(devices).
     map(GraphicsDevice::getDefaultConfiguration).
     map(GraphicsConfiguration::getBounds).
     mapToInt(bounds -> bounds.x + bounds.width).
     max().
     orElse(0);

Here are links to the JavaDoc.

GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()

Semi-transparent color layer over background-image?

Why so complicated? Your solution was almost right except it's a way easier to make the pattern transparent and the background color solid. PNG can contain transparencies. So use photoshop to make the pattern transparent by setting the layer to 70% and resaving your image. Then you only need one selector. Works cross browser.

CSS:

.background {
   background: url('../img/bg/diagonalnoise.png');/* transparent png image*/
   background-color: rgb(248, 247, 216);
}

HTML:

<div class="background">
   ...
</div> 

This are the basic. A usage example follows where I switched from background to background-image but both properties works the same.

_x000D_
_x000D_
body { margin: 0; }_x000D_
div {_x000D_
   height: 110px !important;_x000D_
   padding: 1em;_x000D_
   text-transform: uppercase;_x000D_
   font-family: Arial, Helvetica, sans-serif;_x000D_
   font-weight: 600;_x000D_
   color: white;_x000D_
   text-shadow: 0 0 2px #333;_x000D_
}_x000D_
.background {_x000D_
   background-image: url('https://www.transparenttextures.com/patterns/arabesque.png');/* transparent png image */_x000D_
   }_x000D_
.col-one {_x000D_
  background-color: rgb(255, 255, 0);_x000D_
}_x000D_
.col-two {_x000D_
  background-color: rgb(0, 255, 255);_x000D_
}_x000D_
.col-three {_x000D_
  background-color: rgb(0, 255, 0);_x000D_
}
_x000D_
<div class="background col-one">_x000D_
 1. Background_x000D_
</div> _x000D_
<div class="background col-two">_x000D_
 2. Background_x000D_
</div> _x000D_
<div class="background col-three">_x000D_
 3. Background_x000D_
</div> 
_x000D_
_x000D_
_x000D_

PLEASE WAIT A MINUTE! IT TAKES SOME TIME TO LOAD THE EXTERNAL PATTERNS.

This website seems to be rather slow...

How to pass in password to pg_dump?

Create a .pgpass file in the home directory of the account that pg_dump will run as.

The format is:

hostname:port:database:username:password

Then, set the file's mode to 0600. Otherwise, it will be ignored.

chmod 600 ~/.pgpass

See the Postgresql documentation libpq-pgpass for more details.

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

How to update an object in a List<> in C#

Can also try.

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();

Can't use SURF, SIFT in OpenCV

As per June 2020, I suppose this version (pip install -U opencv-contrib-python==3.4.2.16) is still working. so install it and enjoy.

Case Statement Equivalent in R

case_when(), which was added to dplyr in May 2016, solves this problem in a manner similar to memisc::cases().

For example:

library(dplyr)
mtcars %>% 
  mutate(category = case_when(
    .$cyl == 4 & .$disp < median(.$disp) ~ "4 cylinders, small displacement",
    .$cyl == 8 & .$disp > median(.$disp) ~ "8 cylinders, large displacement",
    TRUE ~ "other"
  )
)

As of dplyr 0.7.0,

mtcars %>% 
  mutate(category = case_when(
    cyl == 4 & disp < median(disp) ~ "4 cylinders, small displacement",
    cyl == 8 & disp > median(disp) ~ "8 cylinders, large displacement",
    TRUE ~ "other"
  )
)

Connect to network drive with user name and password

var fileName = "Mylogs.log";
var local = Path.Combine(@"C:\TempLogs", fileName);
var remote = Path.Combine(@"\\servername\c$\Windows\Temp\", fileName);

WebClient request = new WebClient();
request.Credentials = new NetworkCredential(@"username", "password");

if (File.Exists(local))
{
    File.Delete(local);

    File.Copy(remote, local, true);
}
else
{
    File.Copy(remote, local, true);
}

conversion from infix to prefix

(a–b)/c*(d + e – f / g)

remember scanning the expression from leftmost to right most start on parenthesized terms follow the WHICH COMES FIRST rule... *, /, % are on the same level and higher than + and -.... so (a-b) = -bc prefix (a-b) = bc- for postfix another parenthesized term: (d + e - f / g) = do move the / first then plus '+' comes first before minus sigh '-' (remember they are on the same level..) (d + e - f / g) move / first (d + e - (/fg)) = prefix (d + e - (fg/)) = postfix followed by + then - ((+de) - (/fg)) = prefix ((de+) - (fg/)) = postfix

(-(+de)(/fg)) = prefix so the new expression is now -+de/fg (1) ((de+)(fg/)-) = postfix so the new expression is now de+fg/- (2)

(a–b)/c* hence

  1. (a-b)/c*(d + e – f / g) = -bc prefix [-ab]/c*[-+de/fg] ---> taken from (1) / c * do not move yet so '/' comes first before '*' because they on the same level, move '/' to the rightmost : /[-ab]c * [-+de/fg] then move '*' to the rightmost

    • / [-ab]c[-+de/fg] = remove the grouping symbols = */-abc-+de/fg --> Prefix
  2. (a-b)/c*(d + e – f / g) = bc- for postfix [ab-]/c*[de+fg/-]---> taken from (2) so '/' comes first before '' because they on the same level, move '/' to the leftmost: [ab-]c[de+fg/-]/ then move '' to the leftmost [ab-] c [de+fg/-]/ = remove the grouping symbols= a b - c d e + f g / - / * --> Postfix

How to read an external local JSON file in JavaScript?

One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181

python -m SimpleHTTPServer 8181

Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.

Switch: Multiple values in one case?

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }

How do I do a simple 'Find and Replace" in MsSQL?

The following query replace each and every a character with a b character.

UPDATE 
    YourTable
SET 
    Column1 = REPLACE(Column1,'a','b')
WHERE 
    Column1 LIKE '%a%'

This will not work on SQL server 2003.

Check/Uncheck a checkbox on datagridview

The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code

private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];

    if (chk.Value == chk.TrueValue)
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
    }
    else
    {
        gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
    }

}

What Content-Type value should I send for my XML sitemap?

Other answers here address the general question of what the proper Content-Type for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml and application/xml are permissible. However, none address whether there are any rules specific to sitemaps.

Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site: searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type should be used for serving sitemaps.

In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type of any other XML document - i.e. that it may be either text/xml or application/xml.

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

Download and install an ipa from self hosted url on iOS

It won't be possible if you like to directly download and install the app from your website. There is a different way for enterprise to deploy and install app over the air. Your URL should point to a web service that hosts a manifest plist file in predefined format required by Apple. This service should return the url of manifest file which can then be used as below:

NSString *urlString = // url string where your manifest.plist is deployed on your server.
NSURL *installationURL = [NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[[UIApplication sharedApplication] openURL];

Hope this answers your question.

How do I write a bash script to restart a process if it dies?

I'm not sure how portable it is across operating systems, but you might check if your system contains the 'run-one' command, i.e. "man run-one". Specifically, this set of commands includes 'run-one-constantly', which seems to be exactly what is needed.

From man page:

run-one-constantly COMMAND [ARGS]

Note: obviously this could be called from within your script, but also it removes the need for having a script at all.

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

Bootstrap row class contains margin-left and margin-right which creates problems

You can use row-fluid instead of row, then you won't have this problem. (for previous versions of bootstrap)

I am not sure of recent versions 3, any way :

The issue is that the first column should not have half a gutter on the left, and the last should not have half a gutter on the right. Rather than use some sort of .first or .last class on those columns as some grid systems do, they instead set the .row class to have negative margins that match the padding of the columns. This "pulls" the gutters off of the first and last columns, while at the same time making it wider.

For more information on this Why does the bootstrap .row has a default margin-left of -30px?

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

How to convert a byte array to Stream

I am using as what John Rasch said:

Stream streamContent = taxformUpload.FileContent;

phpmailer - The following SMTP Error: Data not accepted

In my case the problem was with the content of mail. When I changed content to simpler content without HTML, it worked. But after updating the phpmailer everything solved.

OSError: [WinError 193] %1 is not a valid Win32 application

I too faced same issue and following steps in resolution of this.

  1. I removed unnecessary python path from system except anaconda path.
  2. C:\Users<user-Name>\AppData\Roaming<python> = remove any unnecessary python files /folder. these files may interfere with current execution.

Regards Vj

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Formatting a number with leading zeros in PHP

Given that the value is in $value:

  • To echo it:

    printf("%08d", $value);

  • To get it:

    $formatted_value = sprintf("%08d", $value);

That should do the trick

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

How Do I Convert an Integer to a String in Excel VBA?

The shortest way without declaring the variable is with Type Hints :

s$ =  123   ' s = "123"
i% = "123"  ' i =  123

This will not compile with Option Explicit. The types will not be Variant but String and Integer

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Once you set the app.config file, visual studio will generate a copy in the bin folder named App.exe.config. Copy this to the application directory during deployment. Sounds obvious but surprisingly a lot of people miss this step. WinForms developers are not used to config files :).

How to create a numeric vector of zero length in R

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument which defaults to 0

Therefore

numeric()
logical()
character()
integer()
double()
raw()
complex() 
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')

All return 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')

When tracing out variables in the console, How to create a new line?

The worst thing of using just

console.log({'some stuff': 2} + '\n' + 'something')

is that all stuff are converted to the string and if you need object to show you may see next:

[object Object]

Thus my variant is the next code:

console.log({'some stuff': 2},'\n' + 'something');

How to align a div to the top of its parent but keeping its inline-block behaviour?

Or you could just add some content to the div and use inline-table

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

How can I create database tables from XSD files?

XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.

XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

equals vs Arrays.equals in Java

Sigh. Back in the 70s I was the "system programmer" (sysadmin) for an IBM 370 system, and my employer was a member of the IBM users group SHARE. It would sometimes happen thatsomebody submitted an APAR (bug report) on some unexpected behavior of some CMS command, and IBM would respond NOTABUG: the command does what it was designed to do (and what the documentation says).

SHARE came up with a counter to this: BAD -- Broken As Designed. I think this might apply to this implementation of equals for arrays.

There's nothing wrong with the implementation of Object.equals. Object has no data members, so there is nothing to compare. Two "Object"s are equal if and only if they are, in fact, the same Object (internally, the same address and length).

But that logic doesn't apply to arrays. Arrays have data, and you expect comparison (via equals) to compare the data. Ideally, the way Arrays.deepEquals does, but at least the way Arrays.equals does (shallow comparison of the elements).

So the problem is that array (as a built-in object) does not override Object.equals. String (as a named class) does override Object.equals and give the result you expect.

Other answers given are correct: [...].equals([....]) simply compares the pointers and not the contents. Maybe someday somebody will correct this. Or maybe not: how many existing programs would break if [...].equals actually compared the elements? Not many, I suspect, but more than zero.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

How to find topmost view controller on iOS

I am thinking that perhaps one thing is being overlooked here. Perhaps it is better to pass the parent viewController into the function that is using the viewController. If you are fishing around in the view hierarchy to find the top view controller that it is probably violating separation of the Model layer and UI layer and is a code smell. Just pointing this out, I did the same, then realized it was much simpler just to pass it in to function, by having the model operation return to the UI layer where I have a reference to the view controller.

%Like% Query in spring JpaRepository

The spring data JPA query needs the "%" chars as well as a space char following like in your query, as in

@Query("Select c from Registration c where c.place like %:place%").

Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.

You may want to get rid of the @Queryannotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line

List<Registration> findByPlaceContaining(String place);

is sufficient.

How to sum the values of one column of a dataframe in spark/scala

Not sure this was around when this question was asked but:

df.describe().show("columnName")

gives mean, count, stdtev stats on a column. I think it returns on all columns if you just do .show()

How to get Tensorflow tensor dimensions (shape) as int values?

2.0 Compatible Answer: In Tensorflow 2.x (2.1), you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:

Method 1 (using tf.shape):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape)   # [2,3]

Method 2 (using tf.get_shape()):

import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape)   # [2,3]

Redirect parent window from an iframe action

Redirect iframe in parent window by iframe in the same parent:

window.parent.document.getElementById("content").src = "content.aspx?id=12";

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

event.preventDefault() vs. return false

You can hang a lot of functions on the onClick event for one element. How can you be sure the false one will be the last one to fire? preventDefault on the other hand will definitely prevent only the default behavior of the element.

inline conditionals in angular.js

EDIT: 2Toad's answer below is what you're looking for! Upvote that thing

If you're using Angular <= 1.1.4 then this answer will do:

One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:

Here's a filter that will do an "immediate if" (aka iif):

app.filter('iif', function () {
   return function(input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
   };
});

and can be used like this:

{{foo == "bar" | iif : "it's true" : "no, it's not"}}

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

SQL DROP TABLE foreign key constraint

Here's another way to do delete all the constraints followed by the tables themselves, using a concatenation trick involving FOR XML PATH('') which allows merging multiple input rows into a single output row. Should work on anything SQL 2005 & later.

I've left the EXECUTE commands commented out for safety.

DECLARE @SQL NVARCHAR(max)
;WITH fkeys AS (
    SELECT quotename(s.name) + '.' + quotename(o.name) tablename, quotename(fk.name) constraintname 
    FROM sys.foreign_keys fk
    JOIN sys.objects o ON fk.parent_object_id = o.object_id
    JOIN sys.schemas s ON o.schema_id = s.schema_id
)
SELECT @SQL = STUFF((SELECT '; ALTER TABLE ' + tablename + ' DROP CONSTRAINT ' + constraintname
FROM fkeys
FOR XML PATH('')),1,2,'')

-- EXECUTE(@sql)

SELECT @SQL = STUFF((SELECT '; DROP TABLE ' + quotename(TABLE_SCHEMA) + '.' + quotename(TABLE_NAME) 
FROM INFORMATION_SCHEMA.TABLES 
FOR XML PATH('')),1,2,'')

-- EXECUTE(@sql)

PHP XML how to output nice format

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$dom = new DOMDocument();                               //create a document
$dom->preserveWhiteSpace = false;                       //disable whitespace preservation
$dom->formatOutput = true;                              //pretty print output
$documentElement = $dom->createElement("Entry");        //create a node
$dom->appendChild ($documentElement);                   //append it 
$message = new DOMDocument();                           //create another document
$message->loadXML($messageXMLtext);                     //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node);                   //append the new node to the document Element
$dom->saveXML($dom->documentElement);                   //print the original document

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

How to know Hive and Hadoop versions from command prompt?

If you are using hortonworks distro then using CLI you can get the version with the command:

hive --version

Example output

How can I get form data with JavaScript/jQuery?

use .serializeArray() to get the data in array format and then convert it into an object:

function getFormObj(formId) {
    var formObj = {};
    var inputs = $('#'+formId).serializeArray();
    $.each(inputs, function (i, input) {
        formObj[input.name] = input.value;
    });
    return formObj;
}

PDF Editing in PHP?

I really had high hopes for dompdf (it is a cool idea) but the positioning issue are a major factor in my using fpdf. Though it is tedious as every element has to be set; it is powerful as all get out.

I lay an image underneath my workspace in the document to put my layout on top of to fit. Its always been sufficient even for columns (requires a tiny bit of php string calculation, but nothing too terribly heady).

Good luck.

How do ports work with IPv6?

The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.

Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793

how to make a div to wrap two float divs inside?

It's a common problem when you have two floats inside a block. The best way of fixing it is using clear:both after the second div.

<div style="display: block; clear: both;"></div>

It should force the container to be the correct height.

How to filter object array based on attributes?

Or you can simply use $.each (which also works for objects, not only arrays) and build a new array like so:

var json = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...     
        {
            "home_id": "3-will-be-matched",
            "price": "925",
            "sqft": "1000",
            "num_of_beds": "2",
            "num_of_baths": "2.5",
        },
    ]
}

var homes = [];
$.each(json.homes, function(){
    if (this.price <= 1000
        && this.sqft >= 500
        && this.num_of_beds >= 2
        && this.num_of_baths >= 2.5
    ) {
        homes.push(this);
    }
});

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Have you tried Visual Assist X ? Sort of lights up the VS editor.

Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  ...
  watch: {
    leaveType () {
      this.whateverMethod(this.leaveType)
    }
  },
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)
     }
  }

Cannot get to $rootScope

I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run, config, service, factory, etc..), which are more professional.In this function you don't even have to inject that by yourself like

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];

you can use it, as you know.

How to check if a string starts with "_" in PHP?

$variable[0] != "_"

How does it work?

In PHP you can get particular character of a string with array index notation. $variable[0] is the first character of a string (if $variable is a string).

C error: Expected expression before int

{ } -->

defines scope, so if(a==1) { int b = 10; } says, you are defining int b, for {}- this scope. For

if(a==1)
  int b =10;

there is no scope. And you will not be able to use b anywhere.

How to stop a thread created by implementing runnable interface?

If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.

Set an empty DateTime variable

You may want to use a nullable datetime. Datetime? someDate = null;

You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.

How to split data into 3 sets (train, validation and test)?

Here is a Python function that splits a Pandas dataframe into train, validation, and test dataframes with stratified sampling. It performs this split by calling scikit-learn's function train_test_split() twice.

import pandas as pd
from sklearn.model_selection import train_test_split

def split_stratified_into_train_val_test(df_input, stratify_colname='y',
                                         frac_train=0.6, frac_val=0.15, frac_test=0.25,
                                         random_state=None):
    '''
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    '''

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError('fractions %f, %f, %f do not add up to 1.0' % \
                         (frac_train, frac_val, frac_test))

    if stratify_colname not in df_input.columns:
        raise ValueError('%s is not a column in the dataframe' % (stratify_colname))

    X = df_input # Contains all columns.
    y = df_input[[stratify_colname]] # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(X,
                                                          y,
                                                          stratify=y,
                                                          test_size=(1.0 - frac_train),
                                                          random_state=random_state)

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(df_temp,
                                                      y_temp,
                                                      stratify=y_temp,
                                                      test_size=relative_frac_test,
                                                      random_state=random_state)

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test

Below is a complete working example.

Consider a dataset that has a label upon which you want to perform the stratification. This label has its own distribution in the original dataset, say 75% foo, 15% bar and 10% baz. Now let's split the dataset into train, validation, and test into subsets using a 60/20/20 ratio, where each split retains the same distribution of the labels. See the illustration below:

enter image description here

Here is the example dataset:

df = pd.DataFrame( { 'A': list(range(0, 100)),
                     'B': list(range(100, 0, -1)),
                     'label': ['foo'] * 75 + ['bar'] * 15 + ['baz'] * 10 } )

df.head()
#    A    B label
# 0  0  100   foo
# 1  1   99   foo
# 2  2   98   foo
# 3  3   97   foo
# 4  4   96   foo

df.shape
# (100, 3)

df.label.value_counts()
# foo    75
# bar    15
# baz    10
# Name: label, dtype: int64

Now, let's call the split_stratified_into_train_val_test() function from above to get train, validation, and test dataframes following a 60/20/20 ratio.

df_train, df_val, df_test = \
    split_stratified_into_train_val_test(df, stratify_colname='label', frac_train=0.60, frac_val=0.20, frac_test=0.20)

The three dataframes df_train, df_val, and df_test contain all the original rows but their sizes will follow the above ratio.

df_train.shape
#(60, 3)

df_val.shape
#(20, 3)

df_test.shape
#(20, 3)

Further, each of the three splits will have the same distribution of the label, namely 75% foo, 15% bar and 10% baz.

df_train.label.value_counts()
# foo    45
# bar     9
# baz     6
# Name: label, dtype: int64

df_val.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

df_test.label.value_counts()
# foo    15
# bar     3
# baz     2
# Name: label, dtype: int64

How to add favicon.ico in ASP.NET site

_x000D_
_x000D_
    <link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />
_x000D_
_x000D_
_x000D_

This worked for me. If anyone is troubleshooting while reading this - I found issues when my favicon.ico was not nested in the root folder. I had mine in the Resources folder and was struggling at that point.

How do I select an element that has a certain class?

h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

Your want to note it like this:

.myClass h2

Which selects all children of myClass which have the tagname h2

How to add text to an existing div with jquery

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

_x000D_
_x000D_
$(function () {_x000D_
  $('#Add').on('click', function () {_x000D_
    $('<p>Text</p>').appendTo('#Content');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
    <button id="Add">Add Text</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

Cast a Double Variable to Decimal

Convert.ToDecimal(the double you are trying to convert);

echo that outputs to stderr

Another option that I recently stumbled on is this:

    {
        echo "First error line"
        echo "Second error line"
        echo "Third error line"
    } >&2

This uses only Bash built-ins while making multi-line error output less error prone (since you don't have to remember to add &>2 to every line).

How do I assert equality on two classes without an equals method?

You can override the equals method of the class like:

@Override
public int hashCode() {
    int hash = 0;
    hash += (app != null ? app.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    HubRule other = (HubRule) object;

    if (this.app.equals(other.app)) {
        boolean operatorHubList = false;

        if (other.operator != null ? this.operator != null ? this.operator
                .equals(other.operator) : false : true) {
            operatorHubList = true;
        }

        if (operatorHubList) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Well, if you want to compare two object from a class you must implement in some way the equals and the hash code method

Java stack overflow error - how to increase the stack size in Eclipse?

i also have the same problem while parsing schema definition files(XSD) using XSOM library,

i was able to increase Stack memory upto 208Mb then it showed heap_out_of_memory_error for which i was able to increase only upto 320mb.

the final configuration was -Xmx320m -Xss208m but then again it ran for some time and failed.

My function prints recursively the entire tree of the schema definition,amazingly the output file crossed 820Mb for a definition file of 4 Mb(Aixm library) which in turn uses 50 Mb of schema definition library(ISO gml).

with that I am convinced I have to avoid Recursion and then start iteration and some other way of representing the output, but I am having little trouble converting all that recursion to iteration.

How to find the socket connection state in C?

You could call getsockopt just like the following:

int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len);

To test if the socket is up:

if (retval != 0) {
    /* there was a problem getting the error code */
    fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));
    return;
}

if (error != 0) {
    /* socket has a non zero error status */
    fprintf(stderr, "socket error: %s\n", strerror(error));
}

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

How Many Seconds Between Two Dates?

Just subtract:

var a = new Date();
alert("Wait a few seconds, then click OK");

var b = new Date();
var difference = (b - a) / 1000;

alert("You waited: " + difference + " seconds");

how to convert object to string in java

maybe you benefit from converting it to JSON string

String jsonString = new com.google.gson.Gson().toJson(myObject);

in my case, I wanted to add an object to the response headers but you cant add objects to the headers,

so to solve this I convert my object to JSON string and in the client side I will return that string to JSON again

What is the best (and safest) way to merge a Git branch into master?

How I would do this

git checkout master
git pull origin master
git merge test
git push origin master

If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that test is only for you? So no reason to publish it.

git always tries to respect yours and others changes, and so will --rebase. I don't think I can explain it appropriately, so have a look at the Git book - Rebasing or git-ready: Intro into rebasing for a little description. It's a quite cool feature

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Vue.js getting an element within a component

you can access the children of a vuejs component with this.$children. if you want to use the query selector on the current component instance then this.$el.querySelector(...)

just doing a simple console.log(this) will show you all the properties of a vue component instance.

additionally if you know the element you want to access in your component, you can add the v-el:uniquename directive to it and access it via this.$els.uniquename

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

Change http to https of the marked error or all the URL ending with *.xsd extension.

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

I solved this with one code line, as follow: In file index.php, at your template root, after this code line:

defined( '_JEXEC' ) or die( 'Restricted access' );

paste this line: ini_set ('display_errors', 'Off');

Don't worry, be happy...

posted by Jenio.

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

Illegal Escape Character "\"

Use "\\" to escape the \ character.

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

How to vertically align text in input type="text"?

The <textarea> element automatically aligns text at the top of a textbox, if you don't want to use CSS to force it.

Could not create work tree dir 'example.com'.: Permission denied

I was facing same issue then I read first few lines of this question and I realised that I was trying to run command at the root directory of my bash profile instead of CD/my work project folder. I switched back to my work folder and able to clone the project successfully

Login to Microsoft SQL Server Error: 18456

Another worked solution for me. serever->security->logins->new logins->General->create your user name as login name,Click sql server authentication add passwords

uncheck the password verification three checkboxes . This will work.

Remeber to change the server properties ->Security from Server authentication to SQL Server and Windows Authentication mode

Writing Python lists to columns in csv

You can use izip to combine your lists, and then iterate them

for val in itertools.izip(l1,l2,l3,l4,l5):
    writer.writerow(val)

How to forcefully set IE's Compatibility Mode off from the server-side?

Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Maybe this url can help you: Activating Browser Modes with Doctype

Edit: Today we were able to override the compatibility view with: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

Twitter Bootstrap Multilevel Dropdown Menu

I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:

.dropdown-menu li {
    position: relative;
}

I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).

Here is the full less/css change (replace the above with this):

.dropdown-menu li {
    position: relative;

    [class^="icon-"] {
        float: right;
    }

    &:hover {
        // Switch to white icons on hover
        [class^="icon-"] {
            background-image: url("../img/glyphicons-halflings-white.png");
        }
    }
}

Why have header files and .cpp files?

Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.

This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.

It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.

Why use getters and setters/accessors?

If you want a readonly variable but don't want the client to have to change the way they access it, try this templated class:

template<typename MemberOfWhichClass, typename primative>                                       
class ReadOnly {
    friend MemberOfWhichClass;
public:
    template<typename number> inline bool   operator==(const number& y) const { return x == y; } 
    template<typename number> inline number operator+ (const number& y) const { return x + y; } 
    template<typename number> inline number operator- (const number& y) const { return x - y; } 
    template<typename number> inline number operator* (const number& y) const { return x * y; }  
    template<typename number> inline number operator/ (const number& y) const { return x / y; } 
    template<typename number> inline number operator<<(const number& y) const { return x << y; }
    template<typename number> inline number operator^(const number& y) const  { return x^y; }
    template<typename number> inline number operator~() const                 { return ~x; }
    template<typename number> inline operator number() const                  { return x; }
protected:
    template<typename number> inline number operator= (const number& y) { return x = y; }       
    template<typename number> inline number operator+=(const number& y) { return x += y; }      
    template<typename number> inline number operator-=(const number& y) { return x -= y; }      
    template<typename number> inline number operator*=(const number& y) { return x *= y; }      
    template<typename number> inline number operator/=(const number& y) { return x /= y; }      
    primative x;                                                                                
};      

Example Use:

class Foo {
public:
    ReadOnly<Foo, int> cantChangeMe;
};

Remember you'll need to add bitwise and unary operators as well! This is just to get you started

What is callback in Android?

Here is a nice tutorial, which describes callbacks and the use-case well.

The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".

Here's a example:

class A implements ICallback {
     MyObject o;
     B b = new B(this, someParameter);

     @Override
     public void callback(MyObject o){
           this.o = o;
     }
}

class B {
     ICallback ic;
     B(ICallback ic, someParameter){
         this.ic = ic;
     }

    new Thread(new Runnable(){
         public void run(){
             // some calculation
             ic.callback(myObject)
         }
    }).start(); 
}

interface ICallback{
    public void callback(MyObject o);
}

Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.

In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.

mysqli::query(): Couldn't fetch mysqli

Reason of the error is wrong initialization of the mysqli object. True construction would be like this:

$DBConnect = new mysqli("localhost","root","","Ladle");

Easy way to export multiple data.frame to multiple Excel worksheets

I had this exact problem and I solved it this way:

library(openxlsx) # loads library and doesn't require Java installed

your_df_list <- c("df1", "df2", ..., "dfn")

for(name in your_df_list){
  write.xlsx(x = get(name), 
             file = "your_spreadsheet_name.xlsx", 
             sheetName = name)
}

That way you won't have to create a very long list manually if you have tons of dataframes to write to Excel.

Can you use @Autowired with static fields?

In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

Combining "LIKE" and "IN" for SQL Server

Effectively, the IN statement creates a series of OR statements... so

SELECT * FROM table WHERE column IN (1, 2, 3)

Is effectively

SELECT * FROM table WHERE column = 1 OR column = 2 OR column = 3

And sadly, that is the route you'll have to take with your LIKE statements

SELECT * FROM table
WHERE column LIKE 'Text%' OR column LIKE 'Hello%' OR column LIKE 'That%'

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment

How to export all collections in MongoDB?

You can do it using the mongodump command

Step 1 : Open command prompt

Step 2 : go to bin folder of your mongoDB installation (C:\Program Files\MongoDB\Server\4.0\bin)

Step 3 : then execute the following command

mongodump -d your_db_name -o destination_path

your_db_name = test

destination_path = C:\Users\HP\Desktop

Exported files will be created in destination_path\your_db_name folder (in this example C:\Users\HP\Desktop\test)

References : o7planning

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

How to display an alert box from C# in ASP.NET?

If you don't have a Page.Redirect(), use this

Response.Write("<script>alert('Inserted successfully!')</script>"); //works great

But if you do have Page.Redirect(), use this

Response.Write("<script>alert('Inserted..');window.location = 'newpage.aspx';</script>"); //works great

works for me.

Hope this helps.

Android view layout_width - how to change programmatically?

try using

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

navigate to C:\wamp64\alias\phpmyadmin.conf and change from:

php_admin_value upload_max_filesize 128M
php_admin_value post_max_size 128M

to

php_admin_value upload_max_filesize 2048M
php_admin_value post_max_size 2048M

or more :)

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

Filtering Table rows using Jquery

tr:not(:contains(.... work for me

function busca(busca){
    $("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
    $("#listagem tr:contains('"+busca+"')").css("display", "");
}

YouTube URL in Video Tag

The most straight forward answer to this question is: You can't.

Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/> element.

There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.

Using BETWEEN in CASE SQL statement

You do not specify why you think it is wrong but I can se two dangers:

BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.

Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.

How to get ER model of database from server with Workbench

  1. Migrate your DB "simply make sure the tables and columns exist".
  2. Recommended to delete all your data (this freezes MySQL Workbench on my MAC everytime due to "software out of memory..")

  1. Open MySQL Workbench
  2. click + to make MySQL connection
  3. enter credentials and connect
  4. go to database tab
  5. click reverse engineer
  6. follow the wizard Next > Next ….
  7. DONE :)
  8. now you can click the arrange tab then choose auto-layout (keep clicking it until you are satisfied with the result)

Bold words in a string of strings.xml in Android

You can do it from string

 <resources xmlns:tools="http://schemas.android.com/tools">

 <string name="total_review"><b>Total Review: </b> </string>

 </resources>

and can access it from the java code like

proDuctReviewNumber.setText(getResources().getString(R.string.total_review)+productDetailsSuccess.getProductTotalReview());

What is secret key for JWT based authentication and how to generate it?

What is the secret key

The secret key is combined with the header and the payload to create a unique hash. You are only able to verify this hash if you have the secret key.

How to generate the key

You can choose a good, long password. Or you can generate it from a site like this.

Example (but don't use this one now):

8Zz5tw0Ionm3XPZZfN0NOml3z9FMfmpgXwovR9fp6ryDIoGRM8EPHAB6iHsc0fb

Any free WPF themes?

We use the Assergs Application Framework themes:

http://www.codeplex.com/appfx

They have a nice office look and feel to it :)

Find nearest latitude/longitude with an SQL query

Mysql query for search coordinates with distance limit and where condition

SELECT , ( 3959 acos( cos( radians('28.5850154') ) cos( radians(lat) ) cos( radians( lng ) - radians('77.07207489999999') ) + sin( radians('28.5850154') ) * sin( radians( lat ) ) ) ) AS distance FROM `Wo_Products` WHERE `active` = '1' HAVING distance < 5

Mongoose delete array element in document and save

The checked answer does work but officially in MongooseJS latest, you should use pull.

doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed

https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull

I was just looking that up too.

See Daniel's answer for the correct answer. Much better.

jQuery Ajax POST example with PHP

If you want to send data using jQuery Ajax then there is no need of form tag and submit button

Example:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>

<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />

How do you exit from a void function in C++?

void foo() {
  /* do some stuff */
  if (!condition) {
    return;
  }
}

You can just use the return keyword just like you would in any other function.

Show DialogFragment with animation growing from a point

Have you looked at Android Developers Training on Zooming a View? Might be a good starting point.

You probably want to create a custom class extending DialogFragment to get this working.

Also, take a look at Jake Whartons NineOldAndroids for Honeycomb Animation API compatibility all the way back to API Level 1.

How can I redirect a php page to another php page?

Send a Location header to redirect. Keep in mind this only works before any other output is sent.

header('Location: index.php'); // redirect to index.php

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

Get program path in VB.NET?

For that you can use the Application object.

Startup path, just the folder, use Application.StartupPath()

Dim appPath As String = Application.StartupPath()

Full .exe path, including the program.exe name on the end:, use Application.ExecutablePath()

Dim exePath As String = Application.ExecutablePath()

Pass a String from one Activity to another Activity in Android

private final String easyPuzzle ="630208010200050089109060030"+
                             "008006050000187000060500900"+
                             "09007010681002000502003097";
Bundle ePzl= new Bundle();
ePzl.putString("key", easyPuzzle);

Intent i = new Intent(MainActivity.this,AnotherActivity.class);
i.putExtras(ePzl);
startActivity(i);

Now go to AnotherActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_activity);

    Bundle p = getIntent().getExtras();
    String yourPreviousPzl =p.getString("key");

}

now "yourPreviousPzl" is your desired string.

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

Adding a directory to the PATH environment variable in Windows

On Windows 10, I was able to search for set path environment variable and got these instructions:

  1. From the desktop, right-click the very bottom-left corner of the screen to get the Power User Task Menu.
  2. From the Power User Task Menu, click System.
  3. In the Settings window, scroll down to the Related settings section and click the System info link.
  4. In the System window, click the Advanced system settings link in the left navigation panel.
  5. In the System Properties window, click the Advanced tab, then click the Environment Variables button near the bottom of that tab.
  6. In the Environment Variables window (pictured below), highlight the Path variable in the System variables section and click the Edit button. Add or modify the path lines with the paths you want the computer to access. Each different directory is separated with a semicolon, as shown below:

C:\Program Files;C:\Winnt;C:\Winnt\System32

The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.

Draw a line in a div

Its working for me

_x000D_
_x000D_
 .line{_x000D_
width: 112px;_x000D_
height: 47px;_x000D_
border-bottom: 1px solid black;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="line"></div>
_x000D_
_x000D_
_x000D_

Switch/toggle div (jQuery)

Use this:

<script type="text/javascript" language="javascript">
    $("#toggle").click(function() { $("#login-form, #recover-password").toggle(); });
</script>

Your HTML should look like:

<a id="toggle" href="javascript:void(0);">forgot password?</a>
<div id="login-form"></div>
<div id="recover-password" style="display:none;"></div>

Hey, all right! One line! I <3 jQuery.

How to generate List<String> from SQL query?

Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);

            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);

            }
        }

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

How to convert enum names to string in c

An simpler alternative to Hokyo's "Non-Sequential enums" answer, based on using designators to instantiate the string array:

#define NAMES C(RED, 10)C(GREEN, 20)C(BLUE, 30)
#define C(k, v) k = v,
enum color { NAMES };
#undef C

#define C(k, v) [v] = #k,    
const char * const color_name[] = { NAMES };

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

Excel SUMIF between dates

I found another way to work around this issue that I thought I would share.

In my case I had a years worth of daily columns (i.e. Jan-1, Jan-2... Dec-31), and I had to extract totals for each month. I went about it this way: Sum the entire year, Subtract out the totals for the dates prior and the dates after. It looks like this for February's totals:

=SUM($P3:$NP3)-(SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3)+SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3))

Where $P$2:$NP$2 contained my date values and $P3:$NP3 was the first row of data I am totaling. So SUM($P3:$NP3) is my entire year's total and I subtract (the sum of two sumifs):

SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3), which totals all the months after February and SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3), which totals all the months before February.

How to validate an email address in PHP

If you want to check if provided domain from email address is valid, use something like:

/*
* Check for valid MX record for given email domain
*/
if(!function_exists('check_email_domain')){
    function check_email_domain($email) {
        //Get host name from email and check if it is valid
        $email_host = explode("@", $email);     
        //Add a dot to the end of the host name to make a fully qualified domain name and get last array element because an escaped @ is allowed in the local part (RFC 5322)
        $host = end($email_host) . "."; 
        //Convert to ascii (http://us.php.net/manual/en/function.idn-to-ascii.php)
        return checkdnsrr(idn_to_ascii($host), "MX"); //(bool)       
    }
}

This is handy way to filter a lot of invalid email addresses, along with standart email validation, because valid email format does not mean valid email.

Note that idn_to_ascii() (or his sister function idn_to_utf8()) function may not be available in your PHP installation, it requires extensions PECL intl >= 1.0.2 and PECL idn >= 0.1.

Also keep in mind that IPv4 or IPv6 as domain part in email (for example user@[IPv6:2001:db8::1]) cannot be validated, only named hosts can.

See more here.

jQuery get textarea text

You should have a div that just contains the console messages, that is, previous commands and their output. And underneath put an input or textarea that just holds the command you are typing.

-------------------------------
| consle output ...           |
| more output                 |
| prevous commands and data   |
-------------------------------
> This is an input box.

That way you just send the value of the input box to the server for processing, and append the result to the console messages div.

How do I access nested HashMaps in Java?

I prefer creating a custom map that extends HashMap. Then just override get() to add extra logic so that if the map doesnt contain your key. It will a create a new instance of the nested map, add it, then return it.

public class KMap<K, V> extends HashMap<K, V> {

    public KMap() {
        super();
    }

    @Override
    public V get(Object key) {
        if (this.containsKey(key)) {
            return super.get(key);
        } else {
            Map<K, V> value = new KMap<K, V>();
            super.put((K)key, (V)value);
            return (V)value;
        }
    }
}

Now you can use it like so:

Map<Integer, Map<Integer, Map<String, Object>>> nestedMap = new KMap<Integer, Map<Integer, Map<String, Object>>>();

Map<String, Object> map = (Map<String, Object>) nestedMap.get(1).get(2);
Object obj= new Object();
map.put(someKey, obj);

Clear form fields with jQuery

$(".reset").click(function() {
    $(this).closest('form').find("input[type=text], textarea").val("");
});

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

The best practice is selecting the most appropriate one.

.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.

The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.

Reference : Here

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.

Reference : Here

Check the source code (Reference Source .NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

Examples

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

how to add lines to existing file using python

Open the file for 'append' rather than 'write'.

with open('file.txt', 'a') as file:
    file.write('input')

Java : Convert formatted xml file to one line string

//filename is filepath string
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();

while((line=br.readLine())!= null){
    sb.append(line.trim());
}

using StringBuilder is more efficient then concat http://kaioa.com/node/59

Can I force a UITableView to hide the separator between empty cells?

If you use iOS 7 SDK, this is very simple.

Just add this line in your viewDidLoad method:

self.yourTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

How to send password using sftp batch file

PSFTP -b path/file_name.sftp user@IP_server -hostkey 1e:52:b1... -pw password

the file content is:

lcd "path_file for send"

cd path_destination

mput file_name_to_send

quit

to have the hostkey run:

psftp  user@IP_SERVER

Comparing results with today's date?

Not sure what your asking!

However

SELECT  GETDATE()

Will get you the current date and time

SELECT  DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

Will get you just the date with time set to 00:00:00