Programs & Examples On #Observable

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

I found another solution to get the data. according to the documentation Please check documentation link

In service file add following.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class MoviesService {

  constructor(private db: AngularFireDatabase) {}
  getMovies() {
    this.db.list('/movies').valueChanges();
  }
}

In Component add following.

import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  movies$;

  constructor(private moviesDb: MoviesService) { 
   this.movies$ = moviesDb.getMovies();
 }

In your html file add following.

<li  *ngFor="let m of movies$ | async">{{ m.name }} </li>

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

In regard to the "You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable" error.

This could happen if you import { Observable } from 'rxjs' after (below) some module/function/whatever, which actually uses it.

Solution: move this import above the import of that module.

How to create an Observable from static data similar to http one in Angular?

This is how you can create a simple observable for static data.

let observable = Observable.create(observer => {
  setTimeout(() => {
    let users = [
      {username:"balwant.padwal",city:"pune"},
      {username:"test",city:"mumbai"}]

    observer.next(users); // This method same as resolve() method from Angular 1
    console.log("am done");
    observer.complete();//to show we are done with our processing
    // observer.error(new Error("error message"));
  }, 2000);

})

to subscribe to it is very easy

observable.subscribe((data)=>{
  console.log(data); // users array display
});

I hope this answer is helpful. We can use HTTP call instead static data.

Delegation: EventEmitter or Observable in Angular

You can use either:

  1. Behaviour Subject:

BehaviorSubject is a type of subject, a subject is a special type of observable which can act as observable and observer you can subscribe to messages like any other observable and upon subscription, it returns the last value of the subject emitted by the source observable:

Advantage: No Relationship such as parent-child relationship required to pass data between components.

NAV SERVICE

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class NavService {
  private navSubject$ = new BehaviorSubject<number>(0);

  constructor() {  }

  // Event New Item Clicked
  navItemClicked(navItem: number) {
    this.navSubject$.next(number);
  }

 // Allowing Observer component to subscribe emitted data only
  getNavItemClicked$() {
   return this.navSubject$.asObservable();
  }
}

NAVIGATION COMPONENT

@Component({
  selector: 'navbar-list',
  template:`
    <ul>
      <li><a (click)="navItemClicked(1)">Item-1 Clicked</a></li>
      <li><a (click)="navItemClicked(2)">Item-2 Clicked</a></li>
      <li><a (click)="navItemClicked(3)">Item-3 Clicked</a></li>
      <li><a (click)="navItemClicked(4)">Item-4 Clicked</a></li>
    </ul>
})
export class Navigation {
  constructor(private navService:NavService) {}
  navItemClicked(item: number) {
    this.navService.navItemClicked(item);
  }
}

OBSERVING COMPONENT

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  itemClickedSubcription:any

  constructor(private navService:NavService) {}
  ngOnInit() {

    this.itemClickedSubcription = this.navService
                                      .getNavItemClicked$
                                      .subscribe(
                                        item => this.selectedNavItem(item)
                                       );
  }
  selectedNavItem(item: number) {
    this.item = item;
  }

  ngOnDestroy() {
    this.itemClickedSubcription.unsubscribe();
  }
}

Second Approach is Event Delegation in upward direction child -> parent

  1. Using @Input and @Output decorators parent passing data to child component and child notifying parent component

e.g Answered given by @Ashish Sharma.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Here's an example

// in the service
getVehicles(){
    return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
}

// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
    this.vehicles = this._vehicleService.getVehicles();
}

// in template
<div *ngFor='let vehicle of vehicles | async'>
    {{vehicle.name}}
</div>

How can I create an observable with a delay

What you want is a timer:

// RxJS v6+
import { timer } from 'rxjs';

//emit [1, 2, 3] after 1 second.
const source = timer(1000).map(([1, 2, 3]);
//output: [1, 2, 3]
const subscribe = source.subscribe(val => console.log(val));

Creating and returning Observable from Angular 2 Service

In the service.ts file -

a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};

In the component where we are calling the get function of the service -

this.clientListService.getClientList().subscribe(res => this.clientList = res);

Angular/RxJs When should I unsubscribe from `Subscription`

Since seangwright's solution (Edit 3) appears to be very useful, I also found it a pain to pack this feature into base component, and hint other project teammates to remember to call super() on ngOnDestroy to activate this feature.

This answer provide a way to set free from super call, and make "componentDestroyed$" a core of base component.

class BaseClass {
    protected componentDestroyed$: Subject<void> = new Subject<void>();
    constructor() {

        /// wrap the ngOnDestroy to be an Observable. and set free from calling super() on ngOnDestroy.
        let _$ = this.ngOnDestroy;
        this.ngOnDestroy = () => {
            this.componentDestroyed$.next();
            this.componentDestroyed$.complete();
            _$();
        }
    }

    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

And then you can use this feature freely for example:

@Component({
    selector: 'my-thing',
    templateUrl: './my-thing.component.html'
})
export class MyThingComponent extends BaseClass implements OnInit, OnDestroy {
    constructor(
        private myThingService: MyThingService,
    ) { super(); }

    ngOnInit() {
        this.myThingService.getThings()
            .takeUntil(this.componentDestroyed$)
            .subscribe(things => console.log(things));
    }

    /// optional. not a requirement to implement OnDestroy
    ngOnDestroy() {
        console.log('everything works as intended with or without super call');
    }

}

When should we use Observer and Observable?

In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):

If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.

Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.

Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.

The last thing to close the puzzle is how will the Observable class know who is interested? So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o) internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.

It might be that in the interview they did not ask you explicitly about the java.util.Observer and java.util.Observable but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).

UPDATE

In response to your comment, the actual java.util.Observable class offers the following facilities:

  1. Maintaining a list of java.util.Observer instances. New instances interested in being notified can be added through addObserver(Observer o), and removed through deleteObserver(Observer o).

  2. Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged(). So you just call it when you changed something to the Observable and you want the rest of the Observers to eventually know about it.

  3. Notifying all observers that the specific Observable has changed state. This is done through notifyObservers(). This checks if the object has actually changed (i.e. a call to setChanged() was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer instances and calls the update(Observable o, Object arg) method for each of them. This tells the Observer which was the Observable object that changed (you could be observing more than one), and the extra Object arg to potentially carry some extra information (passed through notifyObservers().

Wait for Angular 2 to load/resolve model before rendering view/template

Try {{model?.person.name}} this should wait for model to not be undefined and then render.

Angular 2 refers to this ?. syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:

The Elvis Operator ( ?. ) and null property paths

The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

The current hero's name is {{currentHero?.firstName}}

Let’s elaborate on the problem and this particular solution.

What happens when the following data bound title property is null?

The title is {{ title }}

The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.

Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.

The null hero's name is {{nullHero.firstName}}

JavaScript throws a null reference error and so does Angular:

TypeError: Cannot read property 'firstName' of null in [null]

Worse, the entire view disappears.

We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.

On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.

While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.

Unfortunately, our app crashes when the currentHero is null.

We could code around that problem with NgIf

<!--No hero, div not displayed, no error --> <div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>

Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.

The null hero's name is {{nullHero && nullHero.firstName}}

These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.

The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.

<!-- No hero, no problem! --> The null hero's name is {{nullHero?.firstName}}

It works perfectly with long property paths too:

a?.b?.c?.d

Http post and get request in angular 6

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

Return an empty Observable

Try this

export class Collection{
public more (): Observable<Response> {
   if (this.hasMore()) {
     return this.fetch();
   }
   else{
     return this.returnEmpty(); 
   }            
  }
public returnEmpty(): any {
    let subscription = source.subscribe(
      function (x) {
       console.log('Next: %s', x);
    },
    function (err) {
       console.log('Error: %s', err);
    },
    function () {
       console.log('Completed');
    });
    }
  }
let source = Observable.empty();

How to make one Observable sequence wait for another to complete before emitting?

You can use result emitted from previous Observable thanks to mergeMap (or his alias flatMap) operator like this:

 const one = Observable.of('https://api.github.com/users');
 const two = (c) => ajax(c);//ajax from Rxjs/dom library

 one.mergeMap(two).subscribe(c => console.log(c))

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

Main differences between SOAP and RESTful web services in Java

REST is an architecture.
REST will give human-readable results.
REST is stateless.
REST services are easily cacheable.

SOAP is a protocol. It can run on top of JMS, FTP, and HTTP.

Lazy Method for Reading Big File in Python?

f = ... # file-like object, i.e. supporting read(size) function and 
        # returning empty string '' when there is nothing to read

def chunked(file, chunk_size):
    return iter(lambda: file.read(chunk_size), '')

for data in chunked(f, 65536):
    # process the data

UPDATE: The approach is best explained in https://stackoverflow.com/a/4566523/38592

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

PHP $_POST not working?

try doing var_dump($_GLOBALS).

A potential cause could be that there is a script running before yours which unsets the global variables. Such as:

unset($_REQUEST);

or even.

unset($GLOBALS);

This could be done via the auto_prepend_file option in the php.ini configuration.

Download large file in python with requests

Based on the Roman's most upvoted comment above, here is my implementation, Including "download as" and "retries" mechanism:

def download(url: str, file_path='', attempts=2):
    """Downloads a URL content into a file (with large file support by streaming)

    :param url: URL to download
    :param file_path: Local file name to contain the data downloaded
    :param attempts: Number of attempts
    :return: New file path. Empty string if the download failed
    """
    if not file_path:
        file_path = os.path.realpath(os.path.basename(url))
    logger.info(f'Downloading {url} content to {file_path}')
    url_sections = urlparse(url)
    if not url_sections.scheme:
        logger.debug('The given url is missing a scheme. Adding http scheme')
        url = f'http://{url}'
        logger.debug(f'New url: {url}')
    for attempt in range(1, attempts+1):
        try:
            if attempt > 1:
                time.sleep(10)  # 10 seconds wait time between downloads
            with requests.get(url, stream=True) as response:
                response.raise_for_status()
                with open(file_path, 'wb') as out_file:
                    for chunk in response.iter_content(chunk_size=1024*1024):  # 1MB chunks
                        out_file.write(chunk)
                logger.info('Download finished successfully')
                return file_path
        except Exception as ex:
            logger.error(f'Attempt #{attempt} failed with error: {ex}')
    return ''

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

How do I pass along variables with XMLHTTPRequest

The correct format for passing variables in a GET request is

?variable1=value1&variable2=value2&variable3=value3...
                 ^ ---notice &--- ^

But essentially, you have the right idea.

Find running median from a stream of integers

There are a number of different solutions for finding running median from streamed data, I will briefly talk about them at the very end of the answer.

The question is about the details of the a specific solution (max heap/min heap solution), and how heap based solution works is explained below:

For the first two elements add smaller one to the maxHeap on the left, and bigger one to the minHeap on the right. Then process stream data one by one,

Step 1: Add next item to one of the heaps

   if next item is smaller than maxHeap root add it to maxHeap,
   else add it to minHeap

Step 2: Balance the heaps (after this step heaps will be either balanced or
   one of them will contain 1 more item)

   if number of elements in one of the heaps is greater than the other by
   more than 1, remove the root element from the one containing more elements and
   add to the other one

Then at any given time you can calculate median like this:

   If the heaps contain equal amount of elements;
     median = (root of maxHeap + root of minHeap)/2
   Else
     median = root of the heap with more elements

Now I will talk about the problem in general as promised in the beginning of the answer. Finding running median from a stream of data is a tough problem, and finding an exact solution with memory constraints efficiently is probably impossible for the general case. On the other hand, if the data has some characteristics we can exploit, we can develop efficient specialized solutions. For example, if we know that the data is an integral type, then we can use counting sort, which can give you a constant memory constant time algorithm. Heap based solution is a more general solution because it can be used for other data types (doubles) as well. And finally, if the exact median is not required and an approximation is enough, you can just try to estimate a probability density function for the data and estimate median using that.

Get list of passed arguments in Windows batch script (.bat)

@echo off
:start

:: Insert your code here
echo.%%1 is now:%~1
:: End insert your code here

if "%~2" NEQ "" (
    shift
    goto :start
)

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

Android Studio - How to increase Allocated Heap Size

May help someone that get this problem:

I edit studio64.exe.vmoptions file, but failed to save.

So I opened this file with Notepad++ in Run as Administrator mode and then saved successfully.

Search for value in DataGridView in a column

Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[2].Value.ToString().Equals(searchValue))
            {
                row.Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Access Tomcat Manager App from different host

To access the tomcat manager from different machine you have to follow bellow steps:

1. Update conf/tomcat-users.xml file with user and some roles:

<role rolename="manager-gui"/>
 <role rolename="manager-script"/>
 <role rolename="manager-jmx"/>
 <role rolename="manager-status"/>
 <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>

Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".

Here tomcat user and password is : admin

2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):

Default configuration:

<Context antiResourceLocking="false" privileged="true" >
  
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
  
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>

Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .

2.a : Allow specefic IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />

Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address

2.b : Allow all IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />

Here using allow=".*" you are allowing all IP.

Thanks :)

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

npm install -g npm-install-peers

it will add all the missing peers and remove all the error

How to run multiple SQL commands in a single SQL connection?

using (var connection = new SqlConnection("Enter Your Connection String"))
    {
        connection.Open();
    
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "Enter the First Command Here";
            command.ExecuteNonQuery();
    
            command.CommandText = "Enter Second Comand Here";
            command.ExecuteNonQuery();

    //Similarly You can Add Multiple
        }
    }

Use mysql_fetch_array() with foreach() instead of while()

You can code like this:

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
foreach($rows as $row){ 
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
}

As you can see, it's still need a loop while to get data from mysql_fetch_array

How can I show/hide component with JSF?

You should use <h:panelGroup ...> tag with attribute rendered. If you set true to rendered, the content of <h:panelGroup ...> won't be shown. Your XHTML file should have something like this:

<h:panelGroup rendered="#{userBean.showPassword}">
    <h:outputText id="password" value="#{userBean.password}"/>
</h:panelGroup>

UserBean.java:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable{
    private boolean showPassword = false;
    private String password = "";

    public boolean isShowPassword(){
        return showPassword;
    }
    public void setPassword(password){
        this.password = password;
    }
    public String getPassword(){
        return this.password;
    }
}

Jquery DatePicker Set default date

<script  type="text/javascript">
    $(document).ready(function () {
        $("#txtDate").datepicker({ dateFormat: 'yy/mm/dd' }).datepicker("setDate", "0");
        $("#txtDate2").datepicker({ dateFormat: 'yy/mm/dd',  }).datepicker("setDate", new Date().getDay+15); });                       </script>   

PHP cURL not working - WAMP on Windows 7 64 bit

Go to http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/ and download the cURL version that corresponds to your PHP version under "Fixed curl extensions:".

So if you have PHP 5.3.13, download "php_curl-5.3.13-VC9-x64.zip". Try the "VC" version first. Then replace the php_curl.dll in ext folder. This worked for me.

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Easy way to dismiss keyboard?

@Nicholas Riley & @Kendall Helmstetter Geln & @cannyboy:

Absolutely brilliant!

Thank you.

Considering your advice and the advice of others in this thread, this is what I've done:

What it looks like when used:

[[self appDelegate] dismissKeyboard]; (note: I added appDelegate as an addition to NSObject so I can use anywhere on anything)

What it looks like under the hood:

- (void)dismissKeyboard 
{
    UITextField *tempTextField = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
    tempTextField.enabled = NO;
    [myRootViewController.view addSubview:tempTextField];
    [tempTextField becomeFirstResponder];
    [tempTextField resignFirstResponder];
    [tempTextField removeFromSuperview];
}

EDIT

Amendment to my answer to included tempTextField.enabled = NO;. Disabling the text field will prevent UIKeyboardWillShowNotification and UIKeyboardWillHideNotification keyboard notifications from being sent should you rely on these notifications throughout your app.

When are static variables initialized?

Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.

Google Authenticator available as a public service?

The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.

The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.

A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.

So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.

Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)

But, specifically, you don't need an offsite service to handle this.

Model Binding to a List MVC 4

A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.

public class ListModel<T>
{
    public List<T> Items { get; set; }

    public ListModel(List<T> list) {
        Items = list;
    }
}

and when you return the View you just need to simply do:

List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));

then define the list in the model:

@model ListModel<customClass>

and ready to go:

@foreach(var element in Model.Items) {
  //do as needed...
}

Why extend the Android Application class?

Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.

For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.

After this,you can get the username and password in any of the activities like this:

MyApplication mApplication = (MyApplication)getApplicationContext();
String username = mApplication.getUsername();
String password = mApplication.getPassword();

And finally, do remember to use the Application object as a singleton object:

 public class MyApplication extends Application {
    private static MyApplication singleton;

    public MyApplication getInstance(){
        return singleton;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }
}

For more information, please Click Application Class

Check if item is in an array / list

You have to use .values for arrays. for example say you have dataframe which has a column name ie, test['Name'], you can do

if name in test['Name'].values :
   print(name)

for a normal list you dont have to use .values

Spring: How to inject a value to static field?

First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.

Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

(works with @Autowired/@Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.

Plot a bar using matplotlib using a dictionary

For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))

plt.show()

Replacement for deprecated sizeWithFont: in iOS 7?

- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
    if ([self respondsToSelector:@selector(sizeWithAttributes:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
        return ([self sizeWithAttributes:attribs]);
    }
    return ([self sizeWithFont:fontToUse]);
}

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

Converting Array to List

Old way but still working!

 int[] values = {1,2,3,4};
 List<Integer> list = new ArrayList<>(values.length);

 for(int valor : values) {
     list.add(valor);
 }

get dictionary value by key

It's as simple as this:

String xmlfile = Data_Array["XML_File"];

Note that if the dictionary doesn't have a key that equals "XML_File", that code will throw an exception. If you want to check first, you can use TryGetValue like this:

string xmlfile;
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) {
   // the key isn't in the dictionary.
   return; // or whatever you want to do
}
// xmlfile is now equal to the value

Is PowerShell ready to replace my Cygwin shell on Windows?

The cmdlets in PowerShell are very nice and work reliably. Their object-orientedness appeals to me a lot since I'm a Java/C# developer, but it's not at all a complete set. Since it's object oriented, it's missed out on a lot of the text stream maturity of the POSIX tool set (awk and sed to name a few).

The best answer I've found to the dilemma of loving OO techniques and loving the maturity in the POSIX tools is to use both! One great aspect of PowerShell is that it does an excellent job piping objects to standard streams. PowerShell by default uses an object pipeline to transport its objects around. These aren't the standard streams (standard out, standard error, and standard in). When PowerShell needs to pass output to a standard process that doesn't have an object pipeline, it first converts the objects to a text stream. Since it does this so well, PowerShell makes an excellent place to host POSIX tools!

The best POSIX tool set is GnuWin32. It does take more than 5 seconds to install, but it's worth the trouble, and as far as I can tell, it doesn't modify your system (registry, c:\windows\* folders, etc.) except copying files to the directories you specify. This is extra nice because if you put the tools in a shared directory, many people can access them concurrently.

GnuWin32 Installation Instructions

Download and execute the exe (it's from the SourceForge site) pointing it to a suitable directory (I'll be using C:\bin). It will create a GetGnuWin32 directory there in which you will run download.bat, then install.bat (without parameters), after which, there will be a C:\bin\GetGnuWin32\gnuwin32\bin directory that is the most useful folder that has ever existed on a Windows machine. Add that directory to your path, and you're ready to go.

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

You need to change: AllowOverride None To: AllowOverride All

What does "|=" mean? (pipe equal operator)

|= reads the same way as +=.

notification.defaults |= Notification.DEFAULT_SOUND;

is the same as

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

where | is the bit-wise OR operator.

All operators are referenced here.

A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.

If you look at those constants, you'll see that they're in powers of two :

public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary

So you can use bit-wise OR to add flags

int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011

so

myFlags |= DEFAULT_LIGHTS;

simply means we add a flag.

And symmetrically, we test a flag is set using & :

boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;

Switch statement multiple cases in JavaScript

I can see there are lots of good answers here, but what happens if we need to check more than 10 cases? Here is my own approach:

 function isAccessible(varName){
     let accessDenied = ['Liam', 'Noah', 'William', 'James', 'Logan', 'Benjamin',
                        'Mason', 'Elijah', 'Oliver', 'Jacob', 'Daniel', 'Lucas'];
      switch (varName) {
         case (accessDenied.includes(varName) ? varName : null):
             return 'Access Denied!';
         default:
           return 'Access Allowed.';
       }
    }

    console.log(isAccessible('Liam'));

jQuery, checkboxes and .is(":checked")

I'm still experiencing this behavior with jQuery 1.7.2. A simple workaround is to defer the execution of the click handler with setTimeout and let the browser do its magic in the meantime:

$("#myCheckbox").click( function() {
    var that = this;
    setTimeout(function(){
        alert($(that).is(":checked"));
    });
});

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Find most frequent value in SQL column

Below query seems to work good for me in SQL Server database:

select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC

Result:

column          MOST_FREQUENT
item1           highest count
item2           second highest 
item3           third higest
..
..

How to get the first day of the current week and month?

I have created some methods for this:

public static String catchLastDayOfCurrentWeek(String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    return calendarToString(cal, pattern);
}

public static String catchLastDayOfCurrentWeek(String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    cal.add(Calendar.WEEK_OF_YEAR, 1);
    cal.add(Calendar.MILLISECOND, -1);

    return calendarToString(cal, pattern);
}

public static String catchTheFirstDayOfThemonth(Integer month, pattern padrao) {
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    return calendarToString(cal, pattern);
}

public static String catchTheLastDayOfThemonth(Integer month, String pattern) {
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(new Date());
    cal.set(cal.get(Calendar.YEAR), month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

    return calendarToString(cal, pattern);
}

public static String calendarToString(Calendar calendar, String pattern) {
    if (calendar == null) {
        return "";
    }
    SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
    return format.format(calendar.getTime());
}

You can see more here.

How do I use regular expressions in bash scripts?

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

Get loop counter/index using for…of syntax in JavaScript

Here's a function eachWithIndex that works with anything iterable.

You could also write a similar function eachWithKey that works with objets using for...in.

// example generator (returns an iterator that can only be iterated once)
function* eachFromTo(start, end) { for (let i = start; i <= end; i++) yield i }

// convers an iterable to an array (potential infinite loop)
function eachToArray(iterable) {
    const result = []
    for (const val of iterable) result.push(val)
    return result
}

// yields every value and index of an iterable (array, generator, ...)
function* eachWithIndex(iterable) {
    const shared = new Array(2)
    shared[1] = 0
    for (shared[0] of iterable) {
        yield shared
        shared[1]++
    }
}

console.log('iterate values and indexes from a generator')
for (const [val, i] of eachWithIndex(eachFromTo(10, 13))) console.log(val, i)

console.log('create an array')
const anArray = eachToArray(eachFromTo(10, 13))
console.log(anArray)

console.log('iterate values and indexes from an array')
for (const [val, i] of eachWithIndex(anArray)) console.log(val, i)

The good thing with generators is that they are lazy and can take another generator's result as an argument.

Variable name as a string in Javascript

This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:

_x000D_
_x000D_
   _x000D_
var myFirstName = "Danilo";_x000D_
var varName = Object.keys({myFirstName:0})[0];_x000D_
console.log(varName);
_x000D_
_x000D_
_x000D_

Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Python: What OS am I running on?

Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista'

...and I can’t believe no one’s posted one for Windows 10 yet:

>>> import os
>>> os.name
'nt'
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'10'

Is it a bad practice to use break in a for loop?

In your example you do not know the number of iterations for the for loop. Why not use while loop instead, which allows the number of iterations to be indeterminate at the beginning?

It is hence not necessary to use break statemement in general, as the loop can be better stated as a while loop.

Singular matrix issue with Numpy

As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0. But if you still want to get inverse matrix, you can use np.linalg.pinv, which leverages SVD to approximate initial matrix.

getting the index of a row in a pandas apply function

Either:

1. with row.name inside the apply(..., axis=1) call:

df = pandas.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'], index=['x','y'])

   a  b  c
x  1  2  3
y  4  5  6

df.apply(lambda row: row.name, axis=1)

x    x
y    y

2. with iterrows() (slower)

DataFrame.iterrows() allows you to iterate over rows, and access their index:

for idx, row in df.iterrows():
    ...

How can we stop a running java process through Windows cmd?

In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.

wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate

Else taskkill /im java.exe will work to kill all java processes

What is the official name for a credit card's 3 digit code?

It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).

Card Security Code

How can I change my Cygwin home folder after installation?

I happen to use cwRsync (Cygwin + Rsync for Windows) where cygwin comes bundled, and I couldn't find /etc/passwd.

And it kept saying

Could not create directory '/home/username/.ssh'.
...
Failed to add the host to the list of known hosts (/home/username/.ssh/known_hosts).

So I wrote a batch file which changed the HOME variable before running rsync. Something like:

set HOME=.
rsync /path1 user@host:/path2

And voila! The .ssh folder appeared in the current working dir, and rsync stopped annoying with rsa fingerprints.

It's a quick hotfix, but later you should change HOME to a more secure location.

How to access a dictionary element in a Django template?

You need to find (or define) a 'get' template tag, for example, here.

The tag definition:

@register.filter
def hash(h, key):
    return h[key]

And it’s used like:

{% for o in objects %}
  <li>{{ dictionary|hash:o.id }}</li>
{% endfor %}

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

Could not find folder 'tools' inside SDK

By default it looks for the SDK tools in "C:\Documents and Settings\user\android-sdks". Some times we install it at another location. So you just have to select the correct path and it will done.

How to have click event ONLY fire on parent DIV, not children?

You can use bubbling in your favor:

$('.foobar').on('click', function(e) {
    // do your thing.
}).on('click', 'div', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

Python: how to capture image from webcam on click using OpenCV

i'm not too experienced with open cv but if you want the code in the for loop to be called when a key is pressed, you can use a while loop and an raw_input and a condition to prevent the loop from executing forever

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I was having a similar issue with a customer and none of the posted resolutions did the trick. I granted the "Log on as a batch job" permission via the Local Security Policy and that finally made the Central Administration web page come up properly.

Improve INSERT-per-second performance of SQLite

The answer to your question is that the newer SQLite 3 has improved performance, use that.

This answer Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly? by SqlAlchemy Orm Author has 100k inserts in 0.5 sec, and I have seen similar results with python-sqlite and SqlAlchemy. Which leads me to believe that performance has improved with SQLite 3.

What does collation mean?

Collation defines how you sort and compare string values

For example, it defines how to deal with

  • accents (äàa etc)
  • case (Aa)
  • the language context:
    • In a French collation, cote < côte < coté < côté.
    • In the SQL Server Latin1 default , cote < coté < côte < côté
  • ASCII sorts (a binary collation)

How to use LogonUser properly to impersonate domain user from workgroup client

I was having the same problem. Don't know if you've solved this or not, but what I was really trying to do was access a network share with AD credentials. WNetAddConnection2() is what you need to use in that case.

Relative imports for the billionth time

__name__ changes depending on whether the code in question is run in the global namespace or as part of an imported module.

If the code is not running in the global space, __name__ will be the name of the module. If it is running in global namespace -- for example, if you type it into a console, or run the module as a script using python.exe yourscriptnamehere.py then __name__ becomes "__main__".

You'll see a lot of python code with if __name__ == '__main__' is used to test whether the code is being run from the global namespace – that allows you to have a module that doubles as a script.

Did you try to do these imports from the console?

Get Locale Short Date Format using javascript

How about:

// pass in a localeAbbv string to get the format for a specific locale,
// otherwise the browser's default localte will be used
function getLocaleShortDateFormat(localeAbbv?: string) {
    return new Intl.DateTimeFormat(Intl.DateTimeFormat(localeAbbv).resolvedOptions().locale)
        .format(new Date(2021, 0, 2))
        .replace(/0?1/, "MM").replace(/0?2/, "DD").replace(/(?:20)?21/, "YYYY");
}

This is just taking a known date (2 Jan 2021), formatting it using the current locale, and then replacing the known values (2021=year, 1=month, 2=day) with the appropriate date strings.

This uses standards-compliant method calls and I think should work in all modern(ish) browsers.

Actually I think it's better to use "-" instead of "/" for separating the components of the date when formatting dates for displaying to users. Couple of reasons for this: 1) it provides better UX in that it's easier to discern the components because "-" is not as tall as the numbers so the breaks between the date components stand out better, and 2) it's closer to the ISO 8601 format, which uses dashes between the date components. To do this, just add another .replace(/\//g, "-") to the chain.

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
    </div>
  </div>
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
    </div>
  </div>
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
    </div>
  </div>
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
    </div>
  </div>
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    </div>
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
    </div>
  </div>
</div>

How to redirect on another page and pass parameter in url from table?

Set the user name as data-username attribute to the button and also a class:

HTML

<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />

JS

$(document).on('click', '.btn', function() {

    var name = $(this).data('username');        
    if (name != undefined && name != null) {
        window.location = '/player_detail?username=' + name;
    }
});?

EDIT:

Also, you can simply check for undefined && null using:

$(document).on('click', '.btn', function() {

    var name = $(this).data('username');        
    if (name) {
        window.location = '/player_detail?username=' + name;
    }
});?

As, mentioned in this answer

if (name) {            
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA/Javascript.

Errno 13 Permission denied Python

If nothing worked for you, make sure the file is not open in another program. I was trying to import an xlsx file and Excel was blocking me from doing so.

How to find the Center Coordinate of Rectangle?

Center x = x + 1/2 of width

Center y = y + 1/2 of height 

If you know the width and height already then you only need one set of coordinates.

Pycharm/Python OpenCV and CV2 install error

I rather use Virtualenv to install such packages rather than the entire system, saves time and effort rather than building from source.

I use virtualenvwrapper

Windows user can download

pip install virtualenvwrapper-win

https://pypi.org/project/virtualenvwrapper-win/

Linux follow

pip install opencv-python

opencv-python

If processing a video is required

pip install opencv-contrib-python

opencv-contrib-python

If you do not need GUI in Opencv

pip install opencv-contrib-python-headless

opencv-contrib-python-headless

Function of Project > Clean in Eclipse

I also faced the same issue with Eclipse when I ran the clean build with Maven, but there is a simple solution for this issue. We just need to run Maven update and then build or direct run the application. I hope it will solve the problem.

WampServer orange icon

After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.

Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)

link: http://bugs.mysql.com/bug.php?id=72533

Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.

Regards SB

Get div to take up 100% body height, minus fixed-height header and footer

This still came up as the top Google result when I was trying to find an answer to this question. I didn't have to support older browsers in my project and I feel like I found a better, simpler solution in flex-box. The CSS snippet below is all that is necessary.

I have also shown how to make the main content scrollable if the screen height is too small.

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
header {_x000D_
  min-height: 60px;_x000D_
}_x000D_
main {_x000D_
  flex-grow: 1;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  min-height: 30px;_x000D_
}
_x000D_
<body style="margin: 0px; font-family: Helvetica; font-size: 18px;">_x000D_
  <header style="background-color: lightsteelblue; padding: 2px;">Hello</header>_x000D_
  <main style="overflow: auto; background-color: lightgrey; padding: 2px;">_x000D_
    <article style="height: 400px;">_x000D_
      Goodbye_x000D_
    </article>_x000D_
  </main>_x000D_
  <footer style="background-color: lightsteelblue; padding: 2px;">I don't know why you say, "Goodbye"; I say, "Hello."</footer>_x000D_
</body>
_x000D_
_x000D_
_x000D_

When is a CDATA section necessary within a script tag?

HTML

An HTML parser will treat everything between <script> and </script> as part of the script. Some implementations don't even need a correct closing tag; they stop script interpretation at "</", which is correct according to the specs.

Update In HTML5, and with current browsers, that is not the case anymore.

So, in HTML, this is not possible:

<script>
var x = '</script>';
alert(x)
</script>

A CDATA section has no effect at all. That's why you need to write

var x = '<' + '/script>'; // or
var x = '<\/script>';

or similar.

This also applies to XHTML files served as text/html. (Since IE does not support XML content types, this is mostly true.)

XML

In XML, different rules apply. Note that (non IE) browsers only use an XML parser if the XHMTL document is served with an XML content type.

To the XML parser, a script tag is no better than any other tag. Particularly, a script node may contain non-text child nodes, triggered by "<"; and a "&" sign denotes a character entity.

So, in XHTML, this is not possible:

<script>
if (a<b && c<d) {
    alert('Hooray');
}
</script>

To work around this, you can wrap the whole script in a CDATA section. This tells the parser: 'In this section, don't treat "<" and "&" as control characters.' To prevent the JavaScript engine from interpreting the "<![CDATA[" and "]]>" marks, you can wrap them in comments.

If your script does not contain any "<" or "&", you don't need a CDATA section anyway.

Dynamic WHERE clause in LINQ

alt text
(source: scottgu.com)

You need something like this? Use the Linq Dynamic Query Library (download includes examples).

Check out ScottGu's blog for more examples.

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

I ran into this issue when we changed to Visual Studio 2015. None of the above answers worked for us. In the end we got it working by adding the following config file to ALL sgen.exe executables on the machine

<?xml version ="1.0"?>
    <configuration>
        <startup useLegacyV2RuntimeActivationPolicy="true">
            <supportedRuntime version="v4.0" />
        </startup>    
</configuration>

Particularly in this location, even when we were targeting .NET 4.0:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

JFrame in full screen Java

Add:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH); 
frame.setUndecorated(true);
frame.setVisible(true);

Undefined symbols for architecture i386

well i found a solution to this problem for who want to work with xCode 4. All what you have to do is importing frameworks from the SimulatorSDK folder /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks

i don't know if it works when you try to test your app on a real iDevice, but i'm sure that it works on simulator.

ENJOY

Converting List<String> to String[] in Java

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

VB.NET Connection string (Web.Config, App.Config)

Not clear where My_ConnectionString is coming from in your example, but try this

System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString

like this

Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)

window.location.href doesn't redirect

From this answer,

window.location.href not working

you just need to add

return false;

at the bottom of your function

Copy entire contents of a directory to another using php

copy() only works with files.

Both the DOS copy and Unix cp commands will copy recursively - so the quickest solution is just to shell out and use these. e.g.

`cp -r $src $dest`;

Otherwise you'll need to use the opendir/readdir or scandir to read the contents of the directory, iterate through the results and if is_dir returns true for each one, recurse into it.

e.g.

function xcopy($src, $dest) {
    foreach (scandir($src) as $file) {
        if (!is_readable($src . '/' . $file)) continue;
        if (is_dir($src .'/' . $file) && ($file != '.') && ($file != '..') ) {
            mkdir($dest . '/' . $file);
            xcopy($src . '/' . $file, $dest . '/' . $file);
        } else {
            copy($src . '/' . $file, $dest . '/' . $file);
        }
    }
}

How to close TCP and UDP ports via windows command line

you can use program like tcpview from sysinternal. I guess it can help you a lot on both monitoring and killing unwanted connection.

Table with fixed header and fixed column on pure css

A co-worker and I have just released a new GitHub project that supplies an Angular directive that you can use to decorate your table with fixed headers: https://github.com/objectcomputing/FixedHeader

It relies on css and angular only, with a directive that adds some divs. There is no jQuery required.

This implementation isn't as fully-featured as some other implementations, but if your need is simply to add fixed tables, we think this might be a good option.

Number of rows affected by an UPDATE in PL/SQL

alternatively, SQL%ROWCOUNT you can use this within the procedure without any need to declare a variable

Is there a way to perform "if" in python's lambda

An easy way to perform an if in lambda is by using list comprehension.

You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

f = lambda x: print(x) if x==2 else print("exception")

Another example:

return 1 if M otherwise 0

f = lambda x: 1 if x=="M" else 0

Check if element is clickable in Selenium Java

There are certain things you have to take care:

  • WebDriverWait inconjunction with ExpectedConditions as elementToBeClickable() returns the WebElement once it is located and clickable i.e. visible and enabled.
  • In this process, WebDriverWait will ignore instances of NotFoundException that are encountered by default in the until condition.
  • Once the duration of the wait expires on the desired element not being located and clickable, will throw a timeout exception.
  • The different approach to address this issue are:
    • To invoke click() as soon as the element is returned, you can use:

      new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))).click();
      
    • To simply validate if the element is located and clickable, wrap up the WebDriverWait in a try-catch{} block as follows:

      try {
             new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
             System.out.println("Element is clickable");
           }
      catch(TimeoutException e) {
             System.out.println("Element isn't clickable");
          }
      
    • If WebDriverWait returns the located and clickable element but the element is still not clickable, you need to invoke executeScript() method as follows:

      WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))); 
      ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
      

Mvn install or Mvn package

It depends on what you're trying to achieve after changing the Java file. Until you want to test the maven process, you never need to do anything. Eclipse/MyEclipse will build what is necessary and put the output in the appropriate place within your project. You can also run or deploy it (if it's a web project, for example), without your needing to explicitly do anything with maven. In the end, to install your project in the maven repository, you will need to do a maven install. You may also have other maven goals that you wish to execute, which MyEclipse won't do automatically.

As I say, it depends on what you want to do.

In PANDAS, how to get the index of a known value?

I think this may help you , both index and columns of the values.

value you are looking for is not duplicated:

poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()

you can get its index and column

duplicated:

matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]: 
   f    h
q  1  1.0
g  1  NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]

you will get a list

How can I sort a List alphabetically?

//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) {

List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee)synchronizedListOne).name
.compareTo(((Employee)synchronizedListTwo).name);
}
}); 
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/

// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}

}
}
class Employee {
String name;
Employee (String name) {
this.name = name;

}
}

new Runnable() but no new thread?

Best and easy way is just pass argument and create instance and call thread method

Call thread using create a thread object and send a runnable class object with parameter or without parameter and start method of thread object.

In my condition I am sending parameter and I will use in run method.

new Thread(new FCMThreadController("2", null, "3", "1")).start();

OR

new Thread(new FCMThreadController()).start();

public class FCMThreadController implements Runnable {
private String type;
private List<UserDeviceModel> devices;
private String message;
private String id;


    public FCMThreadController(String type, List<UserDeviceModel> devices, String message, String id) {

        this.type = type;
        this.devices = devices;
        this.message = message;
        this.id = id;
    }



    public FCMThreadController( ) {

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }



}

jQuery AJAX submit form

jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button

Please follow steps

Step 1 - Form tag must have an ID field

<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>

Button which you are going to click

<button>Save</button>

Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.

$("#submitForm").submit(function(e) {
    e.preventDefault();
    var frm = $("#submitForm");
    var data = {};
    $.each(this, function(i, v){
        var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });
    $.ajax({
        contentType:"application/json; charset=utf-8",
        type:frm.attr("method"),
        url:frm.attr("action"),
        dataType:'json',
        data:JSON.stringify(data),
        success:function(data) {
            alert(data.message);
        }
    });
});

for live demo click on below link

How to submit a Form using jQuery AJAX?

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

How to convert timestamps to dates in Bash?

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'

Which terminal command to get just IP address and nothing else?

Use the following command:

/sbin/ifconfig $(netstat -nr | tail -1 | awk '{print $NF}') | awk -F: '/inet /{print $2}' | cut -f1 -d ' '

How to remove an iOS app from the App Store

I just changed availability date to a future date. After doing that, I received following message -

You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.

Which means that the app is removed and no longer available.

jQuery Mobile: Stick footer to bottom of page

The following lines work just fine...

var headerHeight = $( '#header' ).height();
var footerHeight = $( '#footer' ).height();
var footerTop = $( '#footer' ).offset().top;
var height = ( footerTop - ( headerHeight + footerHeight ) );
$( '#content' ).height( height );

How can I force users to access my page over HTTPS instead of HTTP?

If you use Apache or something like LiteSpeed, which supports .htaccess files, you can do the following. If you don't already have a .htaccess file, you should create a new .htaccess file in your root directory (usually where your index.php is located). Now add these lines as the first rewrite rules in your .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

You only need the instruction "RewriteEngine On" once in your .htaccess for all rewrite rules, so if you already have it, just copy the second and third line.

I hope this helps.

How to set a border for an HTML div tag

Try being explicit about all the border properties. For example:

border:1px solid black;

See Border shorthand property. Although the other bits are optional some browsers don't set the width or colour to a default you'd expect. In your case I'd bet that it's the width that's zero unless specified.

How can I search for a commit message on GitHub?

This works well from within Eclipse, until GitHub adds the feature:

Enter image description here

EGit/User Guide, Searching for commits

How can I get the max (or min) value in a vector?

Let,

 #include <vector>

 vector<int> v {1, 2, 3, -1, -2, -3};

If the vector is sorted in ascending or descending order then you can find it with complexity O(1).

For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].

If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].

If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.

int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++)  //start iterating from the second element
{
    if(v[i] < smallest_element)
    {
       smallest_element = v[i];
    }
    if(v[i] > largest_element)
    {
       largest_element = v[i];
    }
}

You can use iterator,

for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
    if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
    {
      smallest_element = *it;
    }
    if(*it > largest_element)
    {
      largest_element = *it;
    }
}

You can calculate it in input section (when you have to find smallest or largest element from a given vector)

int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
    cin>>value;
    if(i==0)
    {
        smallest_element= value; //smallest_element=v[0];
        largest_element= value; //also, largest_element = v[0]
    }

    if(value<smallest_element and i>0)
    {
        smallest_element = value;
    }

    if(value>largest_element and i>0)
    {
        largest_element = value;
    }
    v.push_back(value);
}

Also you can get smallest/largest element by built in functions

#include<algorithm>

int smallest_element = *min_element(v.begin(),v.end());

int largest_element  = *max_element(v.begin(),v.end());

You can get smallest/largest element of any range by using this functions. such as,

vector<int> v {1,2,3,-1,-2,-3};

cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements

cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements

cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)

cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)

I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.

<ng-container> vs <template>

A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.

UITableView - scroll to the top

using contentOffset is not the right way. this would be better as it is table view's natural way

tableView.scrollToRow(at: NSIndexPath.init(row: 0, section: 0) as IndexPath, at: .top, animated: true)

Extract hostname name from string

2020 answer

You don't need any extra dependencies for this! Depending on whether you need to optimize for performance or not, there are two good solutions:

1. Use URL.hostname for readability

In the Babel era, the cleanest and easiest solution is to use URL.hostname.

_x000D_
_x000D_
const getHostname = (url) => {
  // use URL constructor and return hostname
  return new URL(url).hostname;
}

// tests
console.log(getHostname("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostname("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
_x000D_
_x000D_

URL.hostname is part of the URL API, supported by all major browsers except IE (caniuse). Use a URL polyfill if you need to support legacy browsers.

Using this solution will also give you access to other URL properties and methods. This will be useful if you also want to extract the URL's pathname or query string params, for example.


2. Use RegEx for performance

URL.hostname is faster than using the anchor solution or parseUri. However it's still much slower than gilly3's regex:

_x000D_
_x000D_
const getHostnameFromRegex = (url) => {
  // run against regex
  const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
  // extract hostname (will be null if no match is found)
  return matches && matches[1];
}

// tests
console.log(getHostnameFromRegex("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostnameFromRegex("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
_x000D_
_x000D_

Test it yourself on this jsPerf


TL;DR

If you need to process a very large number of URLs (where performance would be a factor), use RegEx. Otherwise, use URL.hostname.

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

Black transparent overlay on image hover with only CSS?

You were close. This will work:

.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }

You needed to put the :hover on image, and make the .overlay cover the whole image by adding right:0; and bottom:0.

jsfiddle: http://jsfiddle.net/Zf5am/569/

Java 8 LocalDate Jackson format

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime createdDate;

How to remove first 10 characters from a string?

Substring has two Overloading methods:

public string Substring(int startIndex);//The substring starts at a specified character position and continues to the end of the string.

public string Substring(int startIndex, int length);//The substring starts at a specified character position and taking length no of character from the startIndex.

So for this scenario, you may use the first method like this below:

var str = "hello world!";
str = str.Substring(10);

Here the output is:

d!

If you may apply defensive coding by checking its length.

Oracle - Insert New Row with Auto Incremental ID

ELXAN@DB1> create table cedvel(id integer,ad varchar2(15));

Table created.

ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id);

Table altered.

ELXAN@DB1> create sequence test_seq start with 1 increment by 1;

Sequence created.

ELXAN@DB1> create or replace trigger ad_insert
before insert on cedvel
REFERENCING NEW AS NEW OLD AS OLD
for each row
begin
    select test_seq.nextval into :new.id from dual;
end;
/  2    3    4    5    6    7    8 

Trigger created.

ELXAN@DB1> insert into cedvel (ad) values ('nese');

1 row created.

How do you check if a selector matches something in jQuery?

Alternatively:

if( jQuery('#elem').get(0) ) {}

n-grams in python, four, five, six grams?

People have already answered pretty nicely for the scenario where you need bigrams or trigrams but if you need everygram for the sentence in that case you can use nltk.util.everygrams

>>> from nltk.util import everygrams

>>> message = "who let the dogs out"

>>> msg_split = message.split()

>>> list(everygrams(msg_split))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out'), ('who', 'let', 'the'), ('let', 'the', 'dogs'), ('the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs'), ('let', 'the', 'dogs', 'out'), ('who', 'let', 'the', 'dogs', 'out')]

Incase you have a limit like in case of trigrams where the max length should be 3 then you can use max_len param to specify it.

>>> list(everygrams(msg_split, max_len=2))
[('who',), ('let',), ('the',), ('dogs',), ('out',), ('who', 'let'), ('let', 'the'), ('the', 'dogs'), ('dogs', 'out')]

You can just modify the max_len param to achieve whatever gram i.e four gram, five gram, six or even hundred gram.

The previous mentioned solutions can be modified to implement the above mentioned solution but this solution is much straight forward than that.

For further reading click here

And when you just need a specific gram like bigram or trigram etc you can use the nltk.util.ngrams as mentioned in M.A.Hassan's answer.

Pushing an existing Git repository to SVN

Git -> SVN with complete commit history

I had a Git project and had to move it to SVN. This is how I made it, keeping the whole commit history. The only thing that gets lost is the original commit time since libSVN will set the local time when we do git svn dcommit.

Howto:

  1. Have a SVN repository where we want to import our stuff to and clone it with git-svn:

    git svn clone https://path.to/svn/repository repo.git-svn`
    
  2. Go there:

    cd repo.git-svn
    
  3. Add the remote of the Git repository (in this example I'm using C:/Projects/repo.git). You want to push to SVN and give it the name old-git:

    git remote add old-git file:///C/Projects/repo.git/
    
  4. Fetch the information from the master branch from the old-git repository to the current repository:

    git fetch old-git master
    
  5. Checkout the master branch of the old-git remote into a new branch called old in the current repository:

    git checkout -b old old-git/master`
    
  6. Rebase to put the HEAD on top of old-git/master. This will maintain all your commits. What this does basically is to take all of your work done in Git and put it on top of the work you are accessing from SVN.

    git rebase master
    
  7. Now go back to your master branch:

    git checkout master
    

    And you can see that you have a clean commit history. This is what you want to push to SVN.

  8. Push your work to SVN:

    git svn dcommit
    

That's all. It is very clean, no hacking, and everything works perfectly out of the box. Enjoy.

How to resolve merge conflicts in Git repository?

Bonus:

In speaking of pull/fetch/merge in the above answers, I would like to share an interesting and productive trick,

git pull --rebase

This above command is the most useful command in my git life which saved a lots of time.

Before pushing your newly committed change to remote server, try git pull --rebase rather git pull and manual merge and it will automatically sync latest remote server changes (with a fetch + merge) and will put your local latest commit at the top in git log. No need to worry about manual pull/merge.

In case of conflict, just use

git mergetool
git add conflict_file
git rebase --continue

Find details at: http://gitolite.com/git-pull--rebase

C# 30 Days From Todays Date

A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).

Fully documented and simple to use, I hope someone finds it useful!

public class TimeTrialManager
{
    private long expiryTime=0;
    private string softwareName = "";
    private string userPath="";
    private bool useSeconds = false;

    public TimeTrialManager(string softwareName) {
        this.softwareName = softwareName;
        // Create folder in Windows Application Data folder for persistence:
        userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
        if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
        userPath += "expiryinfo.txt";
    }

    // Use this method to check if the expiry has already been created. If
    // it has, you don't need to call the setExpiryDate() method ever again.
    public bool expiryHasBeenStored(){
        return File.Exists(userPath);
    }

    // Use this to set expiry as the number of days from the current time.
    // This should be called just once in the program's lifetime for that user.
    public void setExpiryDate(double days)  {
        DateTime time = DateTime.Now.AddDays(days);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString() );
        useSeconds = false;
    }

    // Like above, but set the number of seconds. This should be just used for testing
    // as no sensible time trial would allow the user seconds to test the trial out:
    public void setExpiryTime(double seconds)   {
        DateTime time = DateTime.Now.AddSeconds(seconds);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString());
        useSeconds = true;
    }

    // Check for this in a background timer or whenever else you wish to check if the time has run out
    public bool trialHasExpired()   {
        if(!File.Exists(userPath)) return false;
        if (expiryTime == 0)    expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
        if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
    }

    // This method is optional and isn't required to use the core functionality of the class
    // Perhaps use it to tell the user how long he has left to trial the software
    public string expiryAsHumanReadableString(bool remaining=false) {
        DateTime dt = new DateTime();
        dt = DateTime.FromFileTimeUtc(expiryTime);
        if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
        else {
            if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
            else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
        }
    }

    // This method is private to the class, so no need to worry about it
    private void storeExpiry(string value)  {
        try { File.WriteAllText(userPath, value); }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

}

Here is a typical usage of the above class. Couldn't be simpler!

TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
    ttm = new TimeTrialManager("TestTime");
    if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

JPanel Padding in Java

I will suppose your JPanel contains JTextField, for the sake of the demo.

Those components provides JTextComponent#setMargin() method which seems to be what you're looking for.

If you're looking for an empty border of any size around your text, well, use EmptyBorder

How to ignore whitespace in a regular expression subject string?

Addressing Steven's comment to Sam Dufel's answer

Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?

This should do the trick:

/c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/

See this page for all the different variations of 'cats' that this matches.

You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

How can I copy network files using Robocopy?

You should be able to use Windows "UNC" paths with robocopy. For example:

robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder

Robocopy has the ability to recover from certain types of network hiccups automatically.

What is the most efficient way to deep clone an object in JavaScript?

Checkout this benchmark: http://jsben.ch/#/bWfk9

In my previous tests where speed was a main concern I found

JSON.parse(JSON.stringify(obj))

to be the slowest way to deep clone an object (it is slower than jQuery.extend with deep flag set true by 10-20%).

jQuery.extend is pretty fast when the deep flag is set to false (shallow clone). It is a good option, because it includes some extra logic for type validation and doesn't copy over undefined properties, etc., but this will also slow you down a little.

If you know the structure of the objects you are trying to clone or can avoid deep nested arrays you can write a simple for (var i in obj) loop to clone your object while checking hasOwnProperty and it will be much much faster than jQuery.

Lastly if you are attempting to clone a known object structure in a hot loop you can get MUCH MUCH MORE PERFORMANCE by simply in-lining the clone procedure and manually constructing the object.

JavaScript trace engines suck at optimizing for..in loops and checking hasOwnProperty will slow you down as well. Manual clone when speed is an absolute must.

var clonedObject = {
  knownProp: obj.knownProp,
  ..
}

Beware using the JSON.parse(JSON.stringify(obj)) method on Date objects - JSON.stringify(new Date()) returns a string representation of the date in ISO format, which JSON.parse() doesn't convert back to a Date object. See this answer for more details.

Additionally, please note that, in Chrome 65 at least, native cloning is not the way to go. According to JSPerf, performing native cloning by creating a new function is nearly 800x slower than using JSON.stringify which is incredibly fast all the way across the board.

Update for ES6

If you are using Javascript ES6 try this native method for cloning or shallow copy.

Object.assign({}, obj);

JQuery Find #ID, RemoveClass and AddClass

jQuery('#testID2').find('.test2').replaceWith('.test3');

Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

You need to do this:

jQuery('#testID2').addClass('test3').removeClass('test2');

This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

How to connect Android app to MySQL database?

Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP

Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.

Toggle button using two image on different state

AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:

<ToggleButton 
    android:id="@+id/toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/check"   //check.xml
    android:background="@null"/>

check.xml:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
          android:state_checked="false"/>
    </selector>

Figuring out whether a number is a Double in Java

Try this:

if (items.elementAt(1) instanceof Double) {
   sum.add( i, items.elementAt(1));
}

How to check if current thread is not main thread

Allow me to preface this with: I acknowledged this post has the 'Android' tag, however, my search had nothing to do with 'Android' and this was my top result. To that end, for the non-Android SO Java users landing here, don't forget about:

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

After setting this, elsewhere in your code, you can easily check if you're about to execute on the main thread with:

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

A bit embarrassed I had searched before remembering this, but hopefully it will help someone else!

What does the Excel range.Rows property really do?

Range.Rows and Range.Columns return essentially the same Range except for the fact that the new Range has a flag which indicates that it represents Rows or Columns. This is necessary for some Excel properties such as Range.Count and Range.Hidden and for some methods such as Range.AutoFit():

  • Range.Rows.Count returns the number of rows in Range.
  • Range.Columns.Count returns the number of columns in Range.
  • Range.Rows.AutoFit() autofits the rows in Range.
  • Range.Columns.AutoFit() autofits the columns in Range.

You might find that Range.EntireRow and Range.EntireColumn are useful, although they still are not exactly what you are looking for. They return all possible columns for EntireRow and all possible rows for EntireColumn for the represented range.

I know this because SpreadsheetGear for .NET comes with .NET APIs which are very similar to Excel's APIs. The SpreadsheetGear API comes with several strongly typed overloads to the IRange indexer including the one you probably wish Excel had:

  • IRange this[int row1, int column1, int row2, int column2];

Disclaimer: I own SpreadsheetGear LLC

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Try this. It worked for me.

Go to RUN and type gpedit.msc then completely disable Onedrive. Have you noticed that the problem only existed after the last large download from Microsoft? It contained this package. I also removed it from the Start menu.

This appears to be the cause of the issue. Something to do with downloading temporary files, which of course an applet is.

Once done everything went back to normal.

Get method arguments using Spring AOP?

If you have to log all args or your method have one argument, you can simply use getArgs like described in previous answers.

If you have to log a specific arg, you can annoted it and then recover its value like this :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Data {
 String methodName() default "";
}

@Aspect
public class YourAspect {

 @Around("...")
 public Object around(ProceedingJoinPoint point) throws Throwable {
  Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
  Object[] args = point.getArgs();
  StringBuilder data = new StringBuilder();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    for (int argIndex = 0; argIndex < args.length; argIndex++) {
        for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
            if (!(paramAnnotation instanceof Data)) {
                continue;
            }
            Data dataAnnotation = (Data) paramAnnotation;
            if (dataAnnotation.methodName().length() > 0) {
                Object obj = args[argIndex];
                Method dataMethod = obj.getClass().getMethod(dataAnnotation.methodName());
                data.append(dataMethod.invoke(obj));
                continue;
            }
            data.append(args[argIndex]);
        }
    }
 }
}

Examples of use :

public void doSomething(String someValue, @Data String someData, String otherValue) {
    // Apsect will log value of someData param
}

public void doSomething(String someValue, @Data(methodName = "id") SomeObject someData, String otherValue) {
    // Apsect will log returned value of someData.id() method
}

Updating state on props change in React Form

The new hooks way of doing this is to use useEffect instead of componentWillReceiveProps the old way:

componentWillReceiveProps(nextProps) {
  // You don't have to do this check first, but it can help prevent an unneeded render
  if (nextProps.startTime !== this.state.startTime) {
    this.setState({ startTime: nextProps.startTime });
  }
}

becomes the following in a functional hooks driven component:

// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
// 
useEffect(() => {
  if (props.startTime !== startTime) {
    setStartTime(props.startTime);
  }
}, [props.startTime]);

we set the state using setState, using useEffect we check for changes to the specified prop, and take the action to update the state on change of the prop.

Inline Form nested within Horizontal Form in Bootstrap 3

This Bootply example seems like a much better option. Only thing is that the labels are a little too high so I added padding-top:5px to center them with my inputs.

<div class="container">
<h2>Bootstrap Mixed Form <p class="lead">with horizontal and inline fields</p></h2>
<form role="form" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-1" for="inputEmail1">Email</label>
        <div class="col-sm-5"><input type="email" class="form-control" id="inputEmail1" placeholder="Email"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1" for="inputPassword1">Password</label>
        <div class="col-sm-5"><input type="password" class="form-control" id="inputPassword1" placeholder="Password"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12" for="TextArea">Textarea</label>
        <div class="col-sm-6"><textarea class="form-control" id="TextArea"></textarea></div>
    </div>
    <div class="form-group">
        <div class="col-sm-3"><label>First name</label><input type="text" class="form-control" placeholder="First"></div>
        <div class="col-sm-3"><label>Last name</label><input type="text" class="form-control" placeholder="Last"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12">Phone number</label>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">area</div></div>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">local</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="1111"><div class="help">number</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="123"><div class="help">ext</div></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1">Options</label>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="Option 1"></div>
        <div class="col-sm-3"><input type="text" class="form-control" placeholder="Option 2"></div>
    </div>
    <div class="form-group">
        <div class="col-sm-6">
            <button type="submit" class="btn btn-info pull-right">Submit</button>
        </div>
    </div>
</form>
<hr>
</div>

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

@ symbol is a syntactic sugar python provides to utilize decorator,
to paraphrase the question, It's exactly about what does decorator do in Python?

Put it simple decorator allow you to modify a given function's definition without touch its innermost (it's closure).
It's the most case when you import wonderful package from third party. You can visualize it, you can use it, but you cannot touch its innermost and its heart.

Here is a quick example,
suppose I define a read_a_book function on Ipython

In [9]: def read_a_book():
   ...:     return "I am reading the book: "
   ...: 
In [10]: read_a_book()
Out[10]: 'I am reading the book: '

You see, I forgot to add a name to it.
How to solve such a problem? Of course, I could re-define the function as:

def read_a_book():
    return "I am reading the book: 'Python Cookbook'"

Nevertheless, what if I'm not allowed to manipulate the original function, or if there are thousands of such function to be handled.

Solve the problem by thinking different and define a new_function

def add_a_book(func):
    def wrapper():
        return func() + "Python Cookbook"
    return wrapper

Then employ it.

In [14]: read_a_book = add_a_book(read_a_book)
In [15]: read_a_book()
Out[15]: 'I am reading the book: Python Cookbook'

Tada, you see, I amended read_a_book without touching it inner closure. Nothing stops me equipped with decorator.

What's about @

@add_a_book
def read_a_book():
    return "I am reading the book: "
In [17]: read_a_book()
Out[17]: 'I am reading the book: Python Cookbook'

@add_a_book is a fancy and handy way to say read_a_book = add_a_book(read_a_book), it's a syntactic sugar, there's nothing more fancier about it.

Advantages of std::for_each over for loop

for_each allow us to implement Fork-Join pattern . Other than that it supports fluent-interface.

fork-join pattern

We can add implementation gpu::for_each to use cuda/gpu for heterogeneous-parallel computing by calling the lambda task in multiple workers.

gpu::for_each(users.begin(),users.end(),update_summary);
// all summary is complete now
// go access the user-summary here.

And gpu::for_each may wait for the workers work on all the lambda-tasks to finish before executing the next statements.

fluent-interface

It allow us to write human-readable code in concise manner.

accounts::erase(std::remove_if(accounts.begin(),accounts.end(),used_this_year));
std::for_each(accounts.begin(),accounts.end(),mark_dormant);

Subtracting 2 lists in Python

Try this:

list(array([1,2,3])-1)

How to access pandas groupby dataframe by key

You can use the get_group method:

In [21]: gb.get_group('foo')
Out[21]: 
     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

Note: This doesn't require creating an intermediary dictionary / copy of every subdataframe for every group, so will be much more memory-efficient than creating the naive dictionary with dict(iter(gb)). This is because it uses data-structures already available in the groupby object.


You can select different columns using the groupby slicing:

In [22]: gb[["A", "B"]].get_group("foo")
Out[22]:
     A         B
0  foo  1.624345
2  foo -0.528172
4  foo  0.865408

In [23]: gb["C"].get_group("foo")
Out[23]:
0     5
2    11
4    14
Name: C, dtype: int64

Angular bootstrap datepicker date format does not format ng-model value

After checking the above answers, I came up with this and it worked perfectly without having to add an extra attribute to your markup

angular.module('app').directive('datepickerPopup', function(dateFilter) {
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {
            ngModel.$parsers.push(function(viewValue) {
                return dateFilter(viewValue, 'yyyy-MM-dd');
            });
        }
    }
});

Object Dump JavaScript

console.log("my object: %o", myObj)

Otherwise you'll end up with a string representation sometimes displaying:

[object Object]

or some such.

Port 443 in use by "Unable to open process" with PID 4

Here it was the "Work Folders" feature having been added on a Server 2012 R2. By default it is listening for HTTPS client requests on port 443 via the "System" process. There is a Technet blog post explaining how to change that port number. Don't forget to add a corresponding firewall rule for your custom port and disable the existing one for port 443 though.

How to scroll HTML page to given anchor?

Most answers are unnecessarily complicated.

If you just want to jump to the target element, you don't need JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

If you want to scroll to the target animatedly, please refer to @Shahil's answer.

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Why am I getting the error "connection refused" in Python? (Sockets)

Assume s = socket.socket() The server can be bound by following methods: Method 1:

host = socket.gethostname()
s.bind((host, port))

Method 2:

host = socket.gethostbyname("localhost")  #Note the extra letters "by"
s.bind((host, port))

Method 3:

host = socket.gethostbyname("192.168.1.48")
s.bind((host, port))

If you do not exactly use same method on the client side, you will get the error: socket.error errno 111 connection refused.

So, you have to use on the client side exactly same method to get the host, as you do on the server. For example, in case of client, you will correspondingly use following methods:

Method 1:

host = socket.gethostname() 
s.connect((host, port))

Method 2:

host = socket.gethostbyname("localhost") # Get local machine name
s.connect((host, port))

Method 3:

host = socket.gethostbyname("192.168.1.48") # Get local machine name
s.connect((host, port))

Hope that resolves the problem.

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

How do I change the background color of a plot made with ggplot2

Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.

library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

mytheme = list(
    theme_classic()+
        theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
              legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
              axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)

ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()

custom ggplot theme

String to HtmlDocument

you could get a htmldocument by:

 System.Net.WebClient wc = new System.Net.WebClient();

 System.IO.Stream stream = wc.OpenRead(url);
 System.IO.StreamReader reader = new System.IO.StreamReader(stream);
 string s = reader.ReadToEnd();

 HtmlDocument doc = new HtmlDocument();
 doc.LoadHtml(s);

so you have getbiyid and getbyname ... but any further you'd better of with
HTML Agility Pack as suggested . f.e you can do: doc.DocumentNode.SelectNodes(xpathselector) or regex to parse the doc ..

btw: why not regex ? . its soo cool if you can use it right... but xpath is also very mighty ... so "choose your poison"

cu

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

How to use Fiddler to monitor WCF service

Fiddler listens to outbound requests rather than inbound requests so you're not going to be able to monitor all the requests coming in to your service by using Fiddler.

The best you're going to get with Fiddler is the ability to see all of the requests as they are generated by your Console App (assuming that the app generates web requests rather than using some other pipeline).

If you want a tool that is more powerful (but more difficult to use) that will allow you to monitor ALL incoming requests, you should check out WireShark.

Edit

I stand corrected. Thanks to Eric Law for posting the directions to configuring Fiddler to be a reverse proxy!

CSS Image size, how to fill, but not stretch?

If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property.

_x000D_
_x000D_
.container {_x000D_
  width: 150px;_x000D_
  height: 100px;_x000D_
  background-image: url("http://i.stack.imgur.com/2OrtT.jpg");_x000D_
  background-size: cover;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: 50% 50%;_x000D_
}
_x000D_
<div class="container"></div>?
_x000D_
_x000D_
_x000D_

While cover will give you a scaled up image, contain will give you a scaled down image. Both will preserve the pixel aspect ratio.

http://jsfiddle.net/uTHqs/ (using cover)

http://jsfiddle.net/HZ2FT/ (using contain)

This approach has the advantage of being friendly to Retina displays as per Thomas Fuchs' quick guide.

It's worth mentioning that browser support for both attributes excludes IE6-8.

How to listen to the window scroll event in a VueJS component?

document.addEventListener('scroll', function (event) {
    if ((<HTMLInputElement>event.target).id === 'latest-div') { // or any other filtering condition
  
    }
}, true /*Capture event*/);

You can use this to capture an event and and here "latest-div" is the id name so u can capture all scroller action here based on the id you can do the action as well inside here.

Jquery .on('scroll') not firing the event while scrolling

Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?

Then you can use:

$('#ulId').on('scroll',function(){ console.log('Event Fired'); })

obviously replacing ulId with whatever the actual id of the scrollable div is.

Then set css display: block; on the #ulId (or containing div) upon load?

Adding a Method to an Existing Object Instance

from types import MethodType

def method(self):
   print 'hi!'


setattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )

With this, you can use the self pointer

How create a new deep copy (clone) of a List<T>?

You need to create new Book objects then put those in a new List:

List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();

Update: Slightly simpler... List<T> has a method called ConvertAll that returns a new list:

List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));

Using NSPredicate to filter an NSArray based on NSDictionary keys

With Swift 3, when you want to filter an array of dictionaries with a predicate based on dictionary keys and values, you may choose one of the following patterns.


#1. Using NSPredicate init(format:arguments:) initializer

If you come from Objective-C, init(format:arguments:) offers a key-value coding style to evaluate your predicate.

Usage:

import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let predicate = NSPredicate(format: "key1 == %@", "value1")
//let predicate = NSPredicate(format: "self['key1'] == %@", "value1") // also works
let filteredArray = array.filter(predicate.evaluate)

print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]

#2. Using NSPredicate init(block:) initializer

As an alternative if you prefer strongly typed APIs over stringly typed APIs, you can use init(block:) initializer.

Usage:

import Foundation

let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]

let dictPredicate = NSPredicate(block: { (obj, _) in
    guard let dict = obj as? [String: String], let value = dict["key1"] else { return false }
    return value == "value1"
})

let filteredArray = array.filter(dictPredicate.evaluate)
print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]

How to break nested loops in JavaScript?

function myFunction(){
  for(var i = 0;i < n;i++){
    for(var m = 0;m < n;m++){
      if(/*break condition*/){
        goto out;
      }
    }
  }
out:
 //your out of the loop;
}

How to change default language for SQL Server?

Using SQL Server Management Studio

To configure the default language option

  1. In Object Explorer, right-click a server and select Properties.
  2. Click the Misc server settings node.
  3. In the Default language for users box, choose the language in which Microsoft SQL Server should display system messages. The default language is English.

Using Transact-SQL

To configure the default language option

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute.

This example shows how to use sp_configure to configure the default language option to French

USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

The 33 languages of SQL Server

| LANGID |        ALIAS        |
|--------|---------------------|
|    0   | English             |
|    1   | German              |
|    2   | French              |
|    3   | Japanese            |
|    4   | Danish              |
|    5   | Spanish             |
|    6   | Italian             |
|    7   | Dutch               |
|    8   | Norwegian           |
|    9   | Portuguese          |
|   10   | Finnish             |
|   11   | Swedish             |
|   12   | Czech               |
|   13   | Hungarian           |
|   14   | Polish              |
|   15   | Romanian            |
|   16   | Croatian            |
|   17   | Slovak              |
|   18   | Slovenian           |
|   19   | Greek               |
|   20   | Bulgarian           |
|   21   | Russian             |
|   22   | Turkish             |
|   23   | British English     |
|   24   | Estonian            |
|   25   | Latvian             |
|   26   | Lithuanian          |
|   27   | Brazilian           |
|   28   | Traditional Chinese |
|   29   | Korean              |
|   30   | Simplified Chinese  |
|   31   | Arabic              |
|   32   | Thai                |
|   33   | Bokmål              |

How to switch activity without animation in Android?

You can also just do this in all the activities that you dont want to transition from:

@Override
public void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

I like this approach because you do not have to mess with the style of your activity.

How to apply Hovering on html area tag?

for complete this script , the function for draw circle ,

    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }

Difference Between Select and SelectMany

Select is a simple one-to-one projection from source element to a result element. Select- Many is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence.

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

How to set a selected option of a dropdown list control using angular JS

I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.

You can use track by attribute in your ng-options.

Assume that you have:

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]

You can mention your ng-options as:

ng-options="v.name for v in variants track by v.id"

Hope this helps someone in future.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

How do malloc() and free() work?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

Update statement using with clause

You can always do something like this:

update  mytable t
set     SomeColumn = c.ComputedValue
from    (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id 

You can now also use with statement inside update

update  mytable t
set     SomeColumn = c.ComputedValue
from    (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
         select *, 42 as ComputedValue, abc.ComputedValue_new  from mytable n1
           inner join abc on n1.id=abc.id) c
where t.id = c.id 

module.exports vs exports in Node.js

Even though question has been answered and accepted long ago, i just want to share my 2 cents:

You can imagine that at the very beginning of your file there is something like (just for explanation):

var module = new Module(...);
var exports = module.exports;

enter image description here

So whatever you do just keep in mind that module.exports and NOT exports will be returned from your module when you're requiring that module from somewhere else.

So when you do something like:

exports.a = function() {
    console.log("a");
}
exports.b = function() {
    console.log("b");
}

You are adding 2 function a and b to the object on which module.exports points too, so the typeof the returning result will be an object : { a: [Function], b: [Function] }

Of course, this is the same result you will get if you are using module.exports in this example instead of exports.

This is the case where you want your module.exports to behave like a container of exported values. Whereas, if you only want to export a constructor function then there is something you should know about using module.exports or exports;(Remember again that module.exports will be returned when you require something, not export).

module.exports = function Something() {
    console.log('bla bla');
}

Now typeof returning result is 'function' and you can require it and immediately invoke like:
var x = require('./file1.js')(); because you overwrite the returning result to be a function.

However, using exports you can't use something like:

exports = function Something() {
    console.log('bla bla');
}
var x = require('./file1.js')(); //Error: require is not a function

Because with exports, the reference doesn't point anymore to the object where module.exports points, so there is not a relationship between exports and module.exports anymore. In this case module.exports still points to the empty object {} which will be returned.

Accepted answer from another topic should also help: Does Javascript pass by reference?

How to repair a serialized string which has been corrupted by an incorrect byte count length?

the official docs says it should return false and set E_NOTICE

but since you got error then the error reporting is set to be triggered by E_NOTICE

here is a fix to allow you detect false returned by unserialize

$old_err=error_reporting(); 
error_reporting($old_err & ~E_NOTICE);
$object = unserialize($serialized_data);
error_reporting($old_err);

you might want to consider use base64 encode/decode

$string=base64_encode(serialize($obj));
unserialize(base64_decode($string));

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How can you get the build/version number of your Android application?

Useful for build systems: there is a file generated with your APK file called output.json which contains an array of information for each generated APK file, including the versionName and versionCode.

For example,

[
    {
        "apkInfo": {
            "baseName": "x86-release",
            "enabled": true,
            "filterName": "x86",
            "fullName": "86Release",
            "outputFile": "x86-release-1.0.apk",
            "splits": [
                {
                    "filterType": "ABI",
                    "value": "x86"
                }
            ],
            "type": "FULL_SPLIT",
            "versionCode": 42,
            "versionName": "1.0"
        },
        "outputType": {
            "type": "APK"
        },
        "path": "app-x86-release-1.0.apk",
        "properties": {}
    }
]

How to avoid .pyc files?

In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory.

In python 2.6 and 3.0 however, there may be a setting in the sys module called "dont_write_bytecode" that can be set to suppress this. This can also be set by passing the "-B" option, or setting the environment variable "PYTHONDONTWRITEBYTECODE"

Rename multiple files in a folder, add a prefix (Windows)

I know it's an old question but I learned alot from the various answers but came up with my own solution as a function. This should dynamically add the parent folder as a prefix to all files that matches a certain pattern but only if it does not have that prefix already.

function Add-DirectoryPrefix($pattern) {
    # To debug, replace the Rename-Item with Select-Object
    Get-ChildItem -Path .\* -Filter $pattern -Recurse | 
        Where-Object {$_.Name -notlike ($_.Directory.Name + '*')} | 
        Rename-Item -NewName {$_.Directory.Name + '-' + $_.Name}
        # Select-Object -Property Directory,Name,@{Name = 'NewName'; Expression= {$_.Directory.Name + '-' + $_.Name}}
}

https://gist.github.com/kmpm/4f94e46e569ae0a4e688581231fa9e00

Specifying number of decimal places in Python

Use round() function.

round(2.607) = 3
round(2.607,2) = 2.61

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader

How to pass a value from Vue data to href?

You need to use v-bind: or its alias :. For example,

<a v-bind:href="'/job/'+ r.id">

or

<a :href="'/job/' + r.id">

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Ranges of floating point datatype in C?

A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:

(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) = 
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) = 
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38

How to concatenate text from multiple rows into a single text string in SQL server?

You need to create a variable that will hold your final result and select into it, like so.

Easiest Solution

DECLARE @char VARCHAR(MAX);

SELECT @char = COALESCE(@char + ', ' + [column], [column]) 
FROM [table];

PRINT @char;

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

Everything is dangerous if you don't know what you are doing

Even high-precision decimal types can't save the day:

declare @num1 numeric(38,22)
declare @num2 numeric(38,22)
set @num1 = .0000006
set @num2 = 1.0
select @num1 * @num2 * 1000000

1.000000 <- Should be 0.6000000


The money types are integers

The text representations of smallmoney and decimal(10,4) may look alike, but that doesn't make them interchangeable. Do you cringe when you see dates stored as varchar(10)? This is the same thing.

Behind the scenes, money/smallmoney are just a bigint/int The decimal point in the text representation of money is visual fluff, just like the dashes in a yyyy-mm-dd date. SQL doesn't actually store those internally.

Regarding decimal vs money, pick whatever is appropriate for your needs. The money types exist because storing accounting values as integer multiples of 1/10000th of unit is very common. Also, if you are dealing with actual money and calculations beyond simple addition and subtraction, you shouldn't be doing that at the database level! Do it at the application level with a library that supports Banker's Rounding (IEEE 754)

How do you use https / SSL on localhost?

If you have IIS Express (with Visual Studio):

To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.

See the steps and pictures at this code project.

IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.

From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.

enter image description here

Change MySQL root password in phpMyAdmin

Change It like this, It worked for me. Hope It helps. firs I did

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'changed';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

Then I Changed Like this...

$cfg['Servers'][$i]['verbose'] = 'mysql wampserver';
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root';
/* Server parameters */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;

How to upload files in asp.net core?

Fileservice.cs:

public class FileService : IFileService
{
    private readonly IWebHostEnvironment env;

    public FileService(IWebHostEnvironment env)
    {
        this.env = env;
    }

    public string Upload(IFormFile file)
    {
        var uploadDirecotroy = "uploads/";
        var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);

        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);

        var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploadPath, fileName);

        using (var strem = File.Create(filePath))
        {
            file.CopyTo(strem);
        }
        return fileName;
    }
}

IFileService:

namespace studentapps.Services
{
    public interface IFileService
    {
        string Upload(IFormFile file);
    }
}

StudentController:

[HttpGet]
public IActionResult Create()
{
    var student = new StudentCreateVM();
    student.Colleges = dbContext.Colleges.ToList();
    return View(student);
}

[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
    Student student = new Student()
    {
        DisplayImage = vm.DisplayImage.FileName,
        Name = vm.Name,
        Roll_no = vm.Roll_no,
        CollegeId = vm.SelectedCollegeId,
    };


    if (ModelState.IsValid)
    {
        var fileName = fileService.Upload(vm.DisplayImage);
        student.DisplayImage = fileName;
        getpath = fileName;

        dbContext.Add(student);
        dbContext.SaveChanges();
        TempData["message"] = "Successfully Added";
    }
    return RedirectToAction("Index");
}

How to set the title text color of UIButton?

set title color

btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)

Should Gemfile.lock be included in .gitignore?

No Gemfile.lock means:

  • new contributors cannot run tests because weird things fail, so they won't contribute or get failing PRs ... bad first experience.
  • you cannot go back to a x year old project and fix a bug without having to update/rewrite the project if you lost your local Gemfile.lock

-> Always check in Gemfile.lock, make travis delete it if you want to be extra thorough https://grosser.it/2015/08/14/check-in-your-gemfile-lock/

Convert binary to ASCII and vice versa

Are you looking for the code to do it or understanding the algorithm?

Does this do what you need? Specifically a2b_uu and b2a_uu? There are LOTS of other options in there in case those aren't what you want.

(NOTE: Not a Python guy but this seemed like an obvious answer)

Using GCC to produce readable assembly?

godbolt is a very useful tool, they list only has C++ compilers but you can use -x c flag in order to get it treat the code as C. It will then generate an assembly listing for your code side by side and you can use the Colourise option to generate colored bars to visually indicate which source code maps to the generated assembly. For example the following code:

#include <stdio.h>

void func()
{
  printf( "hello world\n" ) ;
}

using the following command line:

-x c -std=c99 -O3

and Colourise would generate the following:

enter image description here

Create view with primary key?

A little late to this party - but this also works well:

CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT 
CAST(CONCAT(CAST([ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO

In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.

Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :

UniqueId ID ROWNR Name 11 1 1 Amazon A 12 1 2 Amazon B 13 1 3 Amazon C 14 1 4 Amazon D 15 1 5 Amazon E

Table1:

[ID] [Name] 1 Amazon

Table2:

[ID] [Version] 1 A 1 B 1 C 1 D 1 E

CREATE VIEW [REF].[View_Systems]
AS    
SELECT 
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER()  OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]  
FROM  [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Function overloading in Python: Missing

You don't need function overloading, as you have the *args and **kwargs arguments.

The fact is that function overloading is based on the idea that passing different types you will execute different code. If you have a dynamically typed language like Python, you should not distinguish by type, but you should deal with interfaces and their compliance with the code you write.

For example, if you have code that can handle either an integer, or a list of integers, you can try iterating on it and if you are not able to, then you assume it's an integer and go forward. Of course it could be a float, but as far as the behavior is concerned, if a float and an int appear to be the same, then they can be interchanged.

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

SQL to add column and comment in table in single command

Add comments for two different columns of the EMPLOYEE table :

COMMENT ON EMPLOYEE
     (WORKDEPT IS 'see DEPARTMENT table for names',
     EDLEVEL IS 'highest grade level passed in school' )

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account 
SET (student_education_facility_id) = ( 
    SELECT teacher.education_facility_id
    FROM user_account teacher
    WHERE teacher.user_account_id = teacher_id
    AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE user_type = 'ROLE_STUDENT'

Above are the sample update query...

You can write sub query with update SQL statement, you don't need to give alias name for that table. give alias name to sub query table. I tried and it's working fine for me....

How do I specify different layouts for portrait and landscape orientations?

  1. Right click res folder,
  2. New -> Android Resource File
  3. in Available qualifiers, select Orientation,
  4. add to Chosen qualifier
  5. in Screen orientation, select Landscape
  6. Press OK

Using Android Studio 3.4.1, it no longer creates layout-land folder. It will create a folder and put two layout files together.

enter image description here

How to install XNA game studio on Visual Studio 2012?

On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases

In C# check that filename is *possibly* valid (not that it exists)

I've had luck using regular expressions as others have shown.

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

-Jay

Difference between webdriver.get() and webdriver.navigate()

driver.get(url) and navigate.to(url) both are used to go to particular web page. The key difference is that driver.get(url): It does not maintain the browser history and cookies and wait till page fully loaded. driver.navigate.to(url):It is also used to go to particular web page.it maintain browser history and cookies and does not wait till page fully loaded and have navigation between the pages back, forward and refresh.