Programs & Examples On #Newforms

Create a tag in a GitHub repository

For creating git tag you can simply run git tag <tagname> command by replacing with the actual name of the tag. Here is a complete tutorial on the basics of managing git tags: https://www.drupixels.com/blog/git-tags-create-push-remote-checkout-and-much-more

Bootstrap center heading

Just use "justify-content-center" in the row's class attribute.

<div class="container">
  <div class="row justify-content-center">
    <h1>This is a header</h1>
  </div>
</div>

Showing all session data at once?

For print session data you do not need to use print_r() function every time .

If you use it then it will be non-readable format.Data will be looks very dirty.

But if you use my function all you have to do is to use p()-Funtion and pass data into it. //create new file into application/cms_helper.php and load helper cms into //autoload or on controller

/*Copy Code for p function from here and paste into cms_helper.php in application/helpers folder */

   //@parram $data-array,$d-if true then die by default it is false
   //@author Your name

    function p($data,$d = false){

          echo "<pre>"; 
             print_r($data);
          echo "</pre>"; 

        if($d == TRUE){
             die();
          } 
      }

Just remember to load cms_helper into your project or controller using $this->load->helper('cms'); use bellow code into your controller or model it will works just GREAT.

 p($this->session->all_userdata()); // it will apply pre to your sesison data and other array as  well

Python - Extracting and Saving Video Frames

Following script will extract frames every half a second of all videos in folder. (Works on python 3.7)

import cv2
import os
listing = os.listdir(r'D:/Images/AllVideos')
count=1
for vid in listing:
    vid = r"D:/Images/AllVideos/"+vid
    vidcap = cv2.VideoCapture(vid)
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        if hasFrames:
            cv2.imwrite("D:/Images/Frames/image"+str(count)+".jpg", image) # Save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5 # Change this number to 1 for each 1 second
    
    success = getFrame(sec)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)

Fit cell width to content

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

I'd say you can, although it doesn't validate and Firefox will re-arrange the code (so what you see in 'View generated source' when using Web Developer may well surprise). I'm no expert, but putting

<form action="someexecpage.php" method="post">

just ahead of the

<tr>

and then using

</tr></form>

at the end of the row certainly gives the functionality (tested in Firefox, Chrome and IE7-9). Working for me, even if the number of validation errors it produced was a new personal best/worst! No problems seen as a consequence, and I have a fairly heavily styled table. I guess you may have a dynamically produced table, as I do, which is why parsing the table rows is a bit non-obvious for us mortals. So basically, open the form at the beginning of the row and close it just after the end of the row.

JavaScript chop/slice/trim off last character in string

For a number like your example, I would recommend doing this over substring:

_x000D_
_x000D_
console.log(parseFloat('12345.00').toFixed(1));
_x000D_
_x000D_
_x000D_

Do note that this will actually round the number, though, which I would imagine is desired but maybe not:

_x000D_
_x000D_
console.log(parseFloat('12345.46').toFixed(1));
_x000D_
_x000D_
_x000D_

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

How to set alignment center in TextBox in ASP.NET?

To center align text

input[type='text'] { text-align:center;}

To center align the textbox in the container that it sits in, apply text-align:center to the container.

How to change Hash values?

This will do it:

my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }

As opposed to inject the advantage is that you are in no need to return the hash again inside the block.

Line continue character in C#

C# will allow you to have a string split over multiple lines, the term is called verbatim literal:

string myString = @"this is a
                    test
                   to see how long my string
                   can be



                    and it can be quite long";

If you are looking for the alternative to & _ from VB, use the + to join your lines.

Counter in foreach loop in C#

Or even more simple if you don't want to use a lot of linq and for some reason don't want to use a for loop.

int i = 0;
foreach(var x in arr)
{
   //Do some stuff
   i++;
}

Eclipse, regular expression search and replace

At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be

replace: ((TypeName)$0)

Difference between Iterator and Listiterator?

The differences are listed in the Javadoc for ListIterator

You can

  • iterate backwards
  • obtain the iterator at any point.
  • add a new value at any point.
  • set a new value at that point.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

AsyncTask<CognitoCachingCredentialsProvider, Integer, Void> task = new 
AsyncTask<CognitoCachingCredentialsProvider, Integer, Void>() {

@Override
protected Void doInBackground(CognitoCachingCredentialsProvider... params) {
    AWSSessionCredentials creds = credentialsProvider.getCredentials();
    String id = credentialsProvider.getCachedIdentityId();
    credentialsProvider.refresh();
    Log.d("wooohoo", String.format("id=%s, token=%s", id, creds.getSessionToken()));
    return null;
    }
};

task.execute(credentialsProvider);

Check Answer Key 2018

SQL string value spanning multiple lines in query

SQL Server allows the following (be careful to use single quotes instead of double)

UPDATE User
SET UserId = 12345
   , Name = 'J Doe'
   , Location = 'USA'
   , Bio='my bio
spans 
multiple
lines!'
WHERE UserId = 12345

Splitting a list into N parts of approximately equal length

See more_itertools.divide:

n = 2

[list(x) for x in mit.divide(n, range(5, 11))]
# [[5, 6, 7], [8, 9, 10]]

[list(x) for x in mit.divide(n, range(5, 12))]
# [[5, 6, 7, 8], [9, 10, 11]]

Install via > pip install more_itertools.

Swift programmatically navigate to another view controller/scene

The above code works well but if you want to navigate from an NSObject class, where you can not use self.present:

let storyBoard = UIStoryboard(name:"Main", bundle: nil)
if let conVC = storyBoard.instantiateViewController(withIdentifier: "SoundViewController") as? SoundViewController,
    let navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
    
    navController.pushViewController(conVC, animated: true)
}

what do <form action="#"> and <form method="post" action="#"> do?

Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))

An action of # indicates that the form stays on the same page, simply suffixing the url with a #. Similar use occurs in anchors. <a href=#">Link</a> for example, will stay on the same page.

Thus, the form is submitted to the same page, which then processes the data etc.

Replace a character at a specific index in a string?

As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.

There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).

public static void main(String[] args) {
    String text = "This is a test";
    try {
        //String.value is the array of char (char[])
        //that contains the text of the String
        Field valueField = String.class.getDeclaredField("value");
        //String.value is a private variable so it must be set as accessible 
        //to read and/or to modify its value
        valueField.setAccessible(true);
        //now we get the array the String instance is actually using
        char[] value = (char[])valueField.get(text);
        //The 13rd character is the "s" of the word "Test"
        value[12]='x';
        //We display the string which should be "This is a text"
        System.out.println(text);
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

C# Collection was modified; enumeration operation may not execute

I suspect the error is caused by this:

foreach (KeyValuePair<int, int> kvp in rankings)

rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.

But you're modifying the dictionary inside your loop:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

which isn't allowed...so you get the exception.

You could simply do this

foreach (KeyValuePair<int, int> kvp in rankings.ToArray())

Redirecting from HTTP to HTTPS with PHP

Redirecting from HTTP to HTTPS with PHP on IIS

I was having trouble getting redirection to HTTPS to work on a Windows server which runs version 6 of MS Internet Information Services (IIS). I’m more used to working with Apache on a Linux host so I turned to the Internet for help and this was the highest ranking Stack Overflow question when I searched for “php redirect http to https”. However, the selected answer didn’t work for me.

After some trial and error, I discovered that with IIS, $_SERVER['HTTPS'] is set to off for non-TLS connections. I thought the following code should help any other IIS users who come to this question via search engine.

<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
    $redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header("Location: $redirect_url");
    exit();
}
?>

Edit: From another Stack Overflow answer, a simpler solution is to check if($_SERVER["HTTPS"] != "on").

Selecting last element in JavaScript array

Use the slice() method:

my_array.slice(-1)[0]

No provider for HttpClient

I had similar problem. For me the fix was to import HttpModule before HttpClient Module:

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
.
.
.
imports: [
  BrowserModule,
  HttpModule,
  HttpClientModule
],

Creating and returning Observable from Angular 2 Service

UPDATE: 9/24/16 Angular 2.0 Stable

This question gets a lot of traffic still, so, I wanted to update it. With the insanity of changes from Alpha, Beta, and 7 RC candidates, I stopped updating my SO answers until they went stable.

This is the perfect case for using Subjects and ReplaySubjects

I personally prefer to use ReplaySubject(1) as it allows the last stored value to be passed when new subscribers attach even when late:

let project = new ReplaySubject(1);

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject
    project.next(result));

    //add delayed subscription AFTER loaded
    setTimeout(()=> project.subscribe(result => console.log('Delayed Stream:', result)), 3000);
});

//Output
//Subscription Streaming: 1234
//*After load and delay*
//Delayed Stream: 1234

So even if I attach late or need to load later I can always get the latest call and not worry about missing the callback.

This also lets you use the same stream to push down onto:

project.next(5678);
//output
//Subscription Streaming: 5678

But what if you are 100% sure, that you only need to do the call once? Leaving open subjects and observables isn't good but there's always that "What If?"

That's where AsyncSubject comes in.

let project = new AsyncSubject();

//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result),
                  err => console.log(err),
                  () => console.log('Completed'));

http.get('path/to/whatever/projects/1234').subscribe(result => {
    //push onto subject and complete
    project.next(result));
    project.complete();

    //add a subscription even though completed
    setTimeout(() => project.subscribe(project => console.log('Delayed Sub:', project)), 2000);
});

//Output
//Subscription Streaming: 1234
//Completed
//*After delay and completed*
//Delayed Sub: 1234

Awesome! Even though we closed the subject it still replied with the last thing it loaded.

Another thing is how we subscribed to that http call and handled the response. Map is great to process the response.

public call = http.get(whatever).map(res => res.json())

But what if we needed to nest those calls? Yes you could use subjects with a special function:

getThing() {
    resultSubject = new ReplaySubject(1);

    http.get('path').subscribe(result1 => {
        http.get('other/path/' + result1).get.subscribe(response2 => {
            http.get('another/' + response2).subscribe(res3 => resultSubject.next(res3))
        })
    })
    return resultSubject;
}
var myThing = getThing();

But that's a lot and means you need a function to do it. Enter FlatMap:

var myThing = http.get('path').flatMap(result1 => 
                    http.get('other/' + result1).flatMap(response2 => 
                        http.get('another/' + response2)));

Sweet, the var is an observable that gets the data from the final http call.

OK thats great but I want an angular2 service!

I got you:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ReplaySubject } from 'rxjs';

@Injectable()
export class ProjectService {

  public activeProject:ReplaySubject<any> = new ReplaySubject(1);

  constructor(private http: Http) {}

  //load the project
  public load(projectId) {
    console.log('Loading Project:' + projectId, Date.now());
    this.http.get('/projects/' + projectId).subscribe(res => this.activeProject.next(res));
    return this.activeProject;
  }

 }

 //component

@Component({
    selector: 'nav',
    template: `<div>{{project?.name}}<a (click)="load('1234')">Load 1234</a></div>`
})
 export class navComponent implements OnInit {
    public project:any;

    constructor(private projectService:ProjectService) {}

    ngOnInit() {
        this.projectService.activeProject.subscribe(active => this.project = active);
    }

    public load(projectId:string) {
        this.projectService.load(projectId);
    }

 }

I'm a big fan of observers and observables so I hope this update helps!

Original Answer

I think this is a use case of using a Observable Subject or in Angular2 the EventEmitter.

In your service you create a EventEmitter that allows you to push values onto it. In Alpha 45 you have to convert it with toRx(), but I know they were working to get rid of that, so in Alpha 46 you may be able to simply return the EvenEmitter.

class EventService {
  _emitter: EventEmitter = new EventEmitter();
  rxEmitter: any;
  constructor() {
    this.rxEmitter = this._emitter.toRx();
  }
  doSomething(data){
    this.rxEmitter.next(data);
  }
}

This way has the single EventEmitter that your different service functions can now push onto.

If you wanted to return an observable directly from a call you could do something like this:

myHttpCall(path) {
    return Observable.create(observer => {
        http.get(path).map(res => res.json()).subscribe((result) => {
            //do something with result. 
            var newResultArray = mySpecialArrayFunction(result);
            observer.next(newResultArray);
            //call complete if you want to close this stream (like a promise)
            observer.complete();
        });
    });
}

That would allow you do this in the component: peopleService.myHttpCall('path').subscribe(people => this.people = people);

And mess with the results from the call in your service.

I like creating the EventEmitter stream on its own in case I need to get access to it from other components, but I could see both ways working...

Here's a plunker that shows a basic service with an event emitter: Plunkr

How do I get the "id" after INSERT into MySQL database with Python?

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.

How do you list all triggers in a MySQL database?

I hope following code will give you more information.

select * from information_schema.triggers where 
information_schema.triggers.trigger_schema like '%your_db_name%'

This will give you total 22 Columns in MySQL version: 5.5.27 and Above

TRIGGER_CATALOG 
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA 
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED 
SQL_MODE
DEFINER 
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION

How to remove item from list in C#?

You don't specify what kind of list, but the generic List can use either the RemoveAt(index) method, or the Remove(obj) method:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

How to connect to a secure website using SSL in Java with a pkcs12 file?

I cannot comment because of the 50pts threshhold, but I don't think that the answer provided in https://stackoverflow.com/a/537344/1341220 is correct. What you are actually describing is how you insert server certificates into the systems default truststore:

$JAVA_HOME/jre/lib/security/cacerts, password: changeit)

This works, indeed, but it means that you did not really specify a trust store local to your project, but rather accepted the certificate universially in your system.

You actually never use your own truststore that you defined here:

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

syntax error: unexpected token <

This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.

To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.

Does SVG support embedding of bitmap images?

Yes, you can reference any image from the image element. And you can use data URIs to make the SVG self-contained. An example:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

    ...
    <image
        width="100" height="100"
        xlink:href="data:image/png;base64,IMAGE_DATA"
        />
    ...
</svg>

The svg element attribute xmlns:xlink declares xlink as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href means.

The IMAGE_DATA is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.

Here's a full example from the SVG testsuite.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

If you want to use Angular with an unsupported TypeScript version, add this to your tsconfig.json to ignore the warning:

  "angularCompilerOptions": {
    "disableTypeScriptVersionCheck": true,
  },

Wamp Server not goes to green color

You should also make sure that the ports WAMP uses aren't already in use.

That can be done by typing the following command into the command prompt:

netstat –o

Getting values from JSON using Python

There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:

j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon

Remove directory from remote repository after adding them to .gitignore

The rules in your .gitignore file only apply to untracked files. Since the files under that directory were already committed in your repository, you have to unstage them, create a commit, and push that to GitHub:

git rm -r --cached some-directory
git commit -m 'Remove the now ignored directory "some-directory"'
git push origin master

You can't delete the file from your history without rewriting the history of your repository - you shouldn't do this if anyone else is working with your repository, or you're using it from multiple computers. If you still want to do that, you can use git filter-branch to rewrite the history - there is a helpful guide to that here.

Additionally, note the output from git rm -r --cached some-directory will be something like:

rm 'some-directory/product/cache/1/small_image/130x130/small_image.jpg'
rm 'some-directory/product/cache/1/small_image/135x/small_image.jpg'
rm 'some-directory/.htaccess'
rm 'some-directory/logo.jpg'

The rm is feedback from git about the repository; the files are still in the working directory.

mongodb count num of distinct values per field/key

I use this query:

var collection = "countries"; var field = "country"; 
db[collection].distinct(field).forEach(function(value){print(field + ", " + value + ": " + db.hosts.count({[field]: value}))})

Output:

countries, England: 3536
countries, France: 238
countries, Australia: 1044
countries, Spain: 16

This query first distinct all the values, and then count for each one of them the number of occurrences.

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

What's the right way to create a date in Java?

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import java.net.URI; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say google.com
        d.browse(new URI("http://google.com"));

        }
    }
}

The transaction log for the database is full

The following will truncate the log.

USE [yourdbname] 
GO

-- TRUNCATE TRANSACTION LOG --
DBCC SHRINKFILE(yourdbname_log, 1)
BACKUP LOG yourdbname WITH TRUNCATE_ONLY
DBCC SHRINKFILE(yourdbname_log, 1)
GO

-- CHECK DATABASE HEALTH --
ALTER FUNCTION [dbo].[checker]() RETURNS int AS BEGIN  RETURN 0 END
GO

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

values_of_objArray = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

private ValueId : number = 0 // this will be used for multi access like 
                             // update, deleting the obj with id.
private selectedObj : any;

private selectedValueObj(id: any) {
  this.ValueId = (id.srcElement || id.target).value;
  for (let i = 0; i < this.values_of_objArray.length; i++) {
    if (this.values_of_objArray[i].id == this.ValueId) {
      this.selectedObj = this.values_of_objArray[i];
    }
  }
}

Now play with this.selectedObj which has the selected obj from the view.

HTML:

<select name="values_of_obj" class="form-control" [(ngModel)]="ValueId"  
        (change)="selectedValueObj($event)" required>

  <option *ngFor="let Value of values_of_objArray"
          [value]="Value.id">{{Value.name}}</option>    
</select>

Adding calculated column(s) to a dataframe in pandas

The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,

def lower_wick_vec(o, l, c):
    min_oc = numpy.where(o > c, c, o)
    return min_oc - l

where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:

def lower_wick_df(df):
    min_oc = df[['Open', 'Close']].min(axis=1)
    return min_oc - l

The other three will work on columns or vectors just as they are. Then you can finish off with

def is_hammer(df):
    lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"]) 
    cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
    return cl & lw

Bit operators can perform set logic on boolean vectors, & for and, | for or etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.

For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.

How to set up a Web API controller for multipart/form-data

This is what solved my problem
Add the following line to WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

I was facing a similar issue and below line fixed the issue for me.

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </dependency>

Edit: I realized that I was using spring boot and the version of the dependency was getting pulled from spring-boot-starter-parent.

Convert Mongoose docs to json

You may also try mongoosejs's lean() :

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}

*ngIf else if in template

You can also use this old trick for converting complex if/then/else blocks into a slightly cleaner switch statement:

<div [ngSwitch]="true">
    <button (click)="foo=(++foo%3)+1">Switch!</button>

    <div *ngSwitchCase="foo === 1">one</div>
    <div *ngSwitchCase="foo === 2">two</div>
    <div *ngSwitchCase="foo === 3">three</div>
</div>

"while :" vs. "while true"

from manual:

: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

As this returns always zero therefore is is similar to be used as true

Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?

Where can I find a list of escape characters required for my JSON ajax return type?

From the spec:

All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus [backslash] (U+005C), and the control characters U+0000 to U+001F

Just because e.g. Bell (U+0007) doesn't have a single-character escape code does not mean that you don't need to escape it. Use the Unicode escape sequence \u0007.

json.net has key method?

Just use x["error_msg"]. If the property doesn't exist, it returns null.

Xcode "Build and Archive" from command line

Go to the folder where's your project root and:

xcodebuild -project projectname -activetarget -activeconfiguration archive

Is there "\n" equivalent in VBscript?

As David and Remou pointed out, vbCrLf if you want a carriage-return-linefeed combination. Otherwise, Chr(13) and Chr(10) (although some VB-derivatives have vbCr and vbLf; VBScript may well have those, worth checking before using Chr).

ERROR 1049 (42000): Unknown database 'mydatabasename'

You can also create a database named 'mydatabasename' and then try restoring it again.

Create a new database using MySQL CLI:

mysql -u[username] -p[password]
CREATE DATABASE mydatabasename;

Then try to restore your database:

mysql -u[username] -p[password] mydatabase<mydatabase.sql;

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

It might be possible that you have not installed the code in your system. So, please install it first. the command is here -

sudo snap install --classic code

Details are available is here

Backup/Restore a dockerized PostgreSQL database

Another approach (based on docker-postgresql-workflow)

Local running database (not in docker, but same approach would work) to export:

pg_dump -F c -h localhost mydb -U postgres export.dmp

Container database to import:

docker run -d -v /local/path/to/postgres:/var/lib/postgresql/data postgres #ex runs container as `CONTAINERNAME` #find via `docker ps`
docker run -it --link CONTAINERNAME:postgres  --volume $PWD/:/tmp/  postgres  bash -c 'exec pg_restore -h postgres -U postgres -d mydb -F c /tmp/sonar.dmp'

Set Page Title using PHP

Move the data retrieval at the top of the script, and after that use:

<title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>

How does String.Index work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

startIndex and endIndex

  • startIndex is the index of the first character
  • endIndex is the index after the last character.

Example

// character
str[str.startIndex] // H
str[str.endIndex]   // error: after last character

// range
let range = str.startIndex..<str.endIndex
str[range]  // "Hello, playground"

With Swift 4's one-sided ranges, the range can be simplified to one of the following forms.

let range = str.startIndex...
let range = ..<str.endIndex

I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code.

after

As in: index(after: String.Index)

  • after refers to the index of the character directly after the given index.

Examples

// character
let index = str.index(after: str.startIndex)
str[index]  // "e"

// range
let range = str.index(after: str.startIndex)..<str.endIndex
str[range]  // "ello, playground"

before

As in: index(before: String.Index)

  • before refers to the index of the character directly before the given index.

Examples

// character
let index = str.index(before: str.endIndex)
str[index]  // d

// range
let range = str.startIndex..<str.index(before: str.endIndex)
str[range]  // Hello, playgroun

offsetBy

As in: index(String.Index, offsetBy: String.IndexDistance)

  • The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int.

Examples

// character
let index = str.index(str.startIndex, offsetBy: 7)
str[index]  // p

// range
let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end
str[range]  // play

limitedBy

As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

  • The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds.

Example

// character
if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) {
    str[index]  // p
}

If the offset had been 77 instead of 7, then the if statement would have been skipped.

Why is String.Index needed?

It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters.

It is possibly to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.

How to calculate age (in years) based on Date of Birth and getDate()

DECLARE @yourBirthDate DATETIME = '1987-05-25'
SELECT YEAR(DATEADD(DAY, DATEDIFF(DAY, @yourBirthDate, GETDATE()), CAST('0001-01-01' AS DATETIME2))) - 1

How do I exclude Weekend days in a SQL Server query?

Calculate Leave working days in a table column as a default value--updated

If you are using SQL here is the query which can help you: http://gallery.technet.microsoft.com/Calculate...

Starting Docker as Daemon on Ubuntu

I know this questions has been answered, however the reason this is happening to you, was probably because you did not add your username to the docker group.

Here are the steps to do it:

Add the docker group if it doesn't already exist:

sudo groupadd docker

Add the connected user ${USER} to the docker group. Change the user name to match your preferred user:

sudo gpasswd -a ${USER} docker

Restart the Docker daemon:

sudo service docker restart

If you are on Ubuntu 14.04-15.10* use docker.io instead:

sudo service docker.io restart

(If you are on Ubuntu 16.04 the service is named "docker" simply)

Either do a newgrp docker or log out/in to activate the changes to groups.

Readably print out a python dict() sorted by key

An easy way to print the sorted contents of the dictionary, in Python 3:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
...   print("{} : {}".format(key, value))
... 
a : 3
b : 2
c : 1

The expression dict_example.items() returns tuples, which can then be sorted by sorted():

>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

Below is an example to pretty print the sorted contents of a Python dictionary's values.

for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))

Converting string from snake_case to CamelCase in Ruby

I feel a little uneasy to add more answers here. Decided to go for the most readable and minimal pure ruby approach, disregarding the nice benchmark from @ulysse-bn. While :class mode is a copy of @user3869936, the :method mode I don't see in any other answer here.

  def snake_to_camel_case(str, mode: :class)
    case mode
    when :class
      str.split('_').map(&:capitalize).join
    when :method
      str.split('_').inject { |m, p| m + p.capitalize }
    else
      raise "unknown mode #{mode.inspect}"
    end
  end

Result is:

[28] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :class)
=> "AsdDsaFds"
[29] pry(main)> snake_to_camel_case("asd_dsa_fds", mode: :method)
=> "asdDsaFds"

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

How are iloc and loc different?

Label vs. Location

The main distinction between the two methods is:

  • loc gets rows (and/or columns) with particular labels.

  • iloc gets rows (and/or columns) at integer locations.

To demonstrate, consider a series s of characters with a non-monotonic integer index:

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 
49    a
48    b
47    c
0     d
1     e
2     f

>>> s.loc[0]    # value at index label 0
'd'

>>> s.iloc[0]   # value at index location 0
'a'

>>> s.loc[0:1]  # rows at index labels between 0 and 1 (inclusive)
0    d
1    e

>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49    a

Here are some of the differences/similarities between s.loc and s.iloc when passed various objects:

<object> description s.loc[<object>] s.iloc[<object>]
0 single item Value at index label 0 (the string 'd') Value at index location 0 (the string 'a')
0:1 slice Two rows (labels 0 and 1) One row (first row at location 0)
1:47 slice with out-of-bounds end Zero rows (empty Series) Five rows (location 1 onwards)
1:47:-1 slice with negative step Four rows (labels 1 back to 47) Zero rows (empty Series)
[2, 0] integer list Two rows with given labels Two rows with given locations
s > 'e' Bool series (indicating which values have the property) One row (containing 'f') NotImplementedError
(s>'e').values Bool array One row (containing 'f') Same as loc
999 int object not in index KeyError IndexError (out of bounds)
-1 int object not in index KeyError Returns last value in s
lambda x: x.index[3] callable applied to series (here returning 3rd item in index) s.loc[s.index[3]] s.iloc[s.index[3]]

loc's label-querying capabilities extend well-beyond integer indexes and it's worth highlighting a couple of additional examples.

Here's a Series where the index contains string objects:

>>> s2 = pd.Series(s.index, index=s.values)
>>> s2
a    49
b    48
c    47
d     0
e     1
f     2

Since loc is label-based, it can fetch the first value in the Series using s2.loc['a']. It can also slice with non-integer objects:

>>> s2.loc['c':'e']  # all rows lying between 'c' and 'e' (inclusive)
c    47
d     0
e     1

For DateTime indexes, we don't need to pass the exact date/time to fetch by label. For example:

>>> s3 = pd.Series(list('abcde'), pd.date_range('now', periods=5, freq='M')) 
>>> s3
2021-01-31 16:41:31.879768    a
2021-02-28 16:41:31.879768    b
2021-03-31 16:41:31.879768    c
2021-04-30 16:41:31.879768    d
2021-05-31 16:41:31.879768    e

Then to fetch the row(s) for March/April 2021 we only need:

>>> s3.loc['2021-03':'2021-04']
2021-03-31 17:04:30.742316    c
2021-04-30 17:04:30.742316    d

Rows and Columns

loc and iloc work the same way with DataFrames as they do with Series. It's useful to note that both methods can address columns and rows together.

When given a tuple, the first element is used to index the rows and, if it exists, the second element is used to index the columns.

Consider the DataFrame defined below:

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

Then for example:

>>> df.loc['c': , :'z']  # rows 'c' and onwards AND columns up to 'z'
    x   y   z
c  10  11  12
d  15  16  17
e  20  21  22

>>> df.iloc[:, 3]        # all rows, but only the column at index location 3
a     3
b     8
c    13
d    18
e    23

Sometimes we want to mix label and positional indexing methods for the rows and columns, somehow combining the capabilities of loc and iloc.

For example, consider the following DataFrame. How best to slice the rows up to and including 'c' and take the first four columns?

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

We can achieve this result using iloc and the help of another method:

>>> df.iloc[:df.index.get_loc('c') + 1, :4]
    x   y   z   8
a   0   1   2   3
b   5   6   7   8
c  10  11  12  13

get_loc() is an index method meaning "get the position of the label in this index". Note that since slicing with iloc is exclusive of its endpoint, we must add 1 to this value if we want row 'c' as well.

Where to download Microsoft Visual c++ 2003 redistributable

After a bit of googling, it seems that there never was a separate redistributable for Visual C++ 2003 (7.1). At least that is what a post on the microsoft forum says.

You may however be able to extract the runtime DLLs from the VC 7.1 DST timezone update.

VBScript - How to make program wait until process has finished?

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create "notepad.exe", null, null, intProcessID
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
    ("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'")
Do Until i = 1
    Set objLatestProcess = colMonitoredProcesses.NextEvent
    If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
        i = 1
    End If
Loop
Wscript.Echo "Notepad has been terminated."

Fetching data from MySQL database to html dropdown list

What you are asking is pretty straight forward

  1. execute query against your db to get resultset or use API to get the resultset

  2. loop through the resultset or simply the result using php

  3. In each iteration simply format the output as an element

the following refernce should help

HTML option tag

Getting Datafrom MySQL database

hope this helps :)

Difference between javacore, thread dump and heap dump in Websphere

Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.

Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.

Android Studio AVD - Emulator: Process finished with exit code 1

This works to me:

click in Sdk manager in SDK Tools and: enter image description here

Unistal and install the Android Emulator: enter image description here

Hope to help!

PostgreSQL query to list all table names?

select 
 relname as table 
from 
 pg_stat_user_tables 
where schemaname = 'public'

select 
  tablename as table 
from 
  pg_tables  
where schemaname = 'public'

Logging levels - Logback - rule-of-thumb to assign log levels

This may also tangentially help, to understand if a logging request (from the code) at a certain level will result in it actually being logged given the effective logging level that a deployment is configured with. Decide what effective level you want to configure you deployment with from the other Answers here, and then refer to this to see if a particular logging request from your code will actually be logged then...

For examples:

  • "Will a logging code line that logs at WARN actually get logged on my deployment configured with ERROR?" The table says, NO.
  • "Will a logging code line that logs at WARN actually get logged on my deployment configured with DEBUG?" The table says, YES.

from logback documentation:

In a more graphic way, here is how the selection rule works. In the following table, the vertical header shows the level of the logging request, designated by p, while the horizontal header shows effective level of the logger, designated by q. The intersection of the rows (level request) and columns (effective level) is the boolean resulting from the basic selection rule. enter image description here

So a code line that requests logging will only actually get logged if the effective logging level of its deployment is less than or equal to that code line's requested level of severity.

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

Naming threads and thread-pools of ExecutorService

There's an open RFE for this with Oracle. From the comments from the Oracle employee it seems they don't understand the issue and won't fix. It's one of these things that is dead simple to support in the JDK (without breaking backwards compatibility) so it is kind of a shame that the RFE gets misunderstood.

As pointed out you need to implement your own ThreadFactory. If you don't want to pull in Guava or Apache Commons just for this purpose I provide here a ThreadFactory implementation that you can use. It is exactly similar to what you get from the JDK except for the ability to set the thread name prefix to something else than "pool".

package org.demo.concurrency;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadFactory with the ability to set the thread name prefix. 
 * This class is exactly similar to 
 * {@link java.util.concurrent.Executors#defaultThreadFactory()}
 * from JDK8, except for the thread naming feature.
 *
 * <p>
 * The factory creates threads that have names on the form
 * <i>prefix-N-thread-M</i>, where <i>prefix</i>
 * is a string provided in the constructor, <i>N</i> is the sequence number of
 * this factory, and <i>M</i> is the sequence number of the thread created 
 * by this factory.
 */
public class ThreadFactoryWithNamePrefix implements ThreadFactory {

    // Note:  The source code for this class was based entirely on 
    // Executors.DefaultThreadFactory class from the JDK8 source.
    // The only change made is the ability to configure the thread
    // name prefix.


    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * Creates a new ThreadFactory where threads are created with a name prefix
     * of <code>prefix</code>.
     *
     * @param prefix Thread name prefix. Never use a value of "pool" as in that
     *      case you might as well have used
     *      {@link java.util.concurrent.Executors#defaultThreadFactory()}.
     */
    public ThreadFactoryWithNamePrefix(String prefix) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup()
                : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-"
                + poolNumber.getAndIncrement()
                + "-thread-";
    }


    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

When you want to use it you simply take advantage of the fact that all Executors methods allow you to provide your own ThreadFactory.

This

    Executors.newSingleThreadExecutor();

will give an ExecutorService where threads are named pool-N-thread-M but by using

    Executors.newSingleThreadExecutor(new ThreadFactoryWithNamePrefix("primecalc"));

you'll get an ExecutorService where threads are named primecalc-N-thread-M. Voila!

Preventing multiple clicks on button

I found this solution that is simple and worked for me:

<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>

This solution was found in: Original solution

Apache POI error loading XSSFWorkbook class

Please note that 4.0 is not sufficient since ListValuedMap, was introduced in version 4.1.

You need to use this maven repository link for version 4.1. Replicated below for convenience

 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
 <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.1</version>
</dependency>

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

How can I check the current status of the GPS receiver?

If you just need to know if there's a fix, then check for the last known location provided by the GPS receiver and check the .getTime() value to know how old is that. If it's recent enough (like... a few seconds) you have a fix.

   LocationManager lm = (LocationManager)context.getSystemService(LOCATION_SERVICE); 
   Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

   // Get the time of the last fix
   long lastFixTimeMillis = loc.getTime(); 

... and finally compare that to current date time (In UTC!). If it's recent enough you have a fix.

I do that in my app and so far so good.

Where can I find the Java SDK in Linux after installing it?

Another best way to find Java folder path is to use alternatives command in Fedora Linux (I know its for Ubuntu but I hit this post from google just by its headline). Just want to share incase people like me looking for answers for fedora flavour.

To display all information regarding java

alternatives --display java

How to force a line break on a Javascript concatenated string?

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

_x000D_
_x000D_
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to calculate number of days between two given dates?

Without using datetime object in python.

# A date has day 'd', month 'm' and year 'y' 
class Date:
    def __init__(self, d, m, y):
            self.d = d
            self.m = m
            self.y = y

# To store number of days in all months from 
# January to Dec. 
monthDays = [31, 28, 31, 30, 31, 30,
                                            31, 31, 30, 31, 30, 31 ]

# This function counts number of leap years 
# before the given date 
def countLeapYears(d):

    years = d.y

    # Check if the current year needs to be considered 
    # for the count of leap years or not 
    if (d.m <= 2) :
            years-= 1

    # An year is a leap year if it is a multiple of 4, 
    # multiple of 400 and not a multiple of 100. 
    return int(years / 4 - years / 100 + years / 400 )


# This function returns number of days between two 
# given dates 
def getDifference(dt1, dt2) :

    # COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' 

    # initialize count using years and day 
    n1 = dt1.y * 365 + dt1.d

    # Add days for months in given date 
    for i in range(0, dt1.m - 1) :
            n1 += monthDays[i]

    # Since every leap year is of 366 days, 
    # Add a day for every leap year 
    n1 += countLeapYears(dt1)

    # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' 

    n2 = dt2.y * 365 + dt2.d
    for i in range(0, dt2.m - 1) :
            n2 += monthDays[i]
    n2 += countLeapYears(dt2)

    # return difference between two counts 
    return (n2 - n1)


# Driver program 
dt1 = Date(31, 12, 2018 )
dt2 = Date(1, 1, 2019 )

print(getDifference(dt1, dt2), "days")

Better way to find index of item in ArrayList?

ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index

int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
    Log.e(TAG, "Object not found in List");
} else {
    Log.i(TAG, "" + position);
}

Output: List Index : 7

If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.

Done

In SQL Server, how to create while loop in select

INSERT INTO Table2 SELECT DISTINCT ID,Data = STUFF((SELECT ', ' + AA.Data FROM Table1 AS AA WHERE AA.ID = BB.ID FOR XML PATH(''), TYPE).value('.','nvarchar(max)'), 1, 2, '') FROM Table1 AS BB 
GROUP BY ID,Data
ORDER BY ID;

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

The existing answers already cover the "how", but I just wanted to elaborate on the "what" and "why" for others who might be wondering.

What a compiler (gcc) does: The term "compile" is a bit of an overloaded term because it is used at a high-level to mean "convert source code to a program", but more technically means to "convert source code to object code". A compiler like gcc actually performs two related, but arguably distinct functions to turn your source code into a program: compiling (as in the latter definition of turning source to object code) and linking (the process of combining the necessary object code files together into one complete executable).

The original error that you saw is technically a "linking error", and is thrown by "ld", the linker. Unlike (strict) compile-time errors, there is no reference to source code lines, as the linker is already in object space.

By default, when gcc is given source code as input, it attempts to compile each and then link them all together. As noted in the other responses, it's possible to use flags to instruct gcc to just compile first, then use the object files later to link in a separate step. This two-step process may seem unnecessary (and probably is for very small programs) but it is very important when managing a very large program, where compiling the entire project each time you make a small change would waste a considerable amount of time.

Determine if an element has a CSS class with jQuery

 $('.segment-name').click(function () {
    if($(this).hasClass('segment-a')){
        //class exist
    }
});

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

Should I use window.navigate or document.location in JavaScript?

I'd go with window.location = "http://...";. I've been coding cross-browser JavaScript for a few years, and I've never experienced problems using this approach.

window.navigate and window.location.href seems a bit odd to me.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

IPython Notebook save location

To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.

set "var=%cd%"
cd var
ipython notebook

Redirect website after certain amount of time

If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.

Here is a very basic approach using setTimeout()

_x000D_
_x000D_
<html>_x000D_
    <body>_x000D_
    <p>You will be redirected in 3 seconds</p>_x000D_
    <script>_x000D_
        var timer = setTimeout(function() {_x000D_
            window.location='http://example.com'_x000D_
        }, 3000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is function overloading and overriding in php?

I would like to point out over here that Overloading in PHP has a completely different meaning as compared to other programming languages. A lot of people have said that overloading isnt supported in PHP and by the conventional definition of overloading, yes that functionality isnt explicitly available.

However, the correct definition of overloading in PHP is completely different.

In PHP overloading refers to dynamically creating properties and methods using magic methods like __set() and __get(). These overloading methods are invoked when interacting with methods or properties that are not accessible or not declared.

Here is a link from the PHP manual : http://www.php.net/manual/en/language.oop5.overloading.php

Is it possible to clone html element objects in JavaScript / JQuery?

It's actually very easy in jQuery:

$("#ddl_1").clone().attr("id",newId).appendTo("body");

Change .appendTo() of course...

dropping a global temporary table

-- First Truncate temporary table
SQL> TRUNCATE TABLE test_temp1;

-- Then Drop temporary table
SQL> DROP TABLE test_temp1;

How to cast the size_t to double or int C++

Static cast:

static_cast<int>(data);

How to find if a native DLL file is compiled as x64 or x86?

I rewrote c++ solution in first answer in powershell script. Script can determine this types of .exe and .dll files:

#Description       C# compiler switch             PE type       machine corflags
#MSIL              /platform:anycpu (default)     PE32  x86     ILONLY
#MSIL 32 bit pref  /platform:anycpu32bitpreferred PE32  x86     ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed       /platform:x86                  PE32  x86     ILONLY | 32BITREQUIRED
#x86 mixed         n/a                            PE32  x86     32BITREQUIRED
#x64 managed       /platform:x64                  PE32+ x64     ILONLY
#x64 mixed         n/a                            PE32+ x64  
#ARM managed       /platform:arm                  PE32  ARM     ILONLY
#ARM mixed         n/a                            PE32  ARM  

this solution has some advantages over corflags.exe and loading assembly via Assembly.Load in C# - you will never get BadImageFormatException or message about invalid header.

function GetActualAddressFromRVA($st, $sec, $numOfSec, $dwRVA)
{
    [System.UInt32] $dwRet = 0;
    for($j = 0; $j -lt $numOfSec; $j++)   
    {   
        $nextSectionOffset = $sec + 40*$j;
        $VirtualSizeOffset = 8;
        $VirtualAddressOffset = 12;
        $SizeOfRawDataOffset = 16;
        $PointerToRawDataOffset = 20;

    $Null = @(
        $curr_offset = $st.BaseStream.Seek($nextSectionOffset + $VirtualSizeOffset, [System.IO.SeekOrigin]::Begin);        
        [System.UInt32] $VirtualSize = $b.ReadUInt32();
        [System.UInt32] $VirtualAddress = $b.ReadUInt32();
        [System.UInt32] $SizeOfRawData = $b.ReadUInt32();
        [System.UInt32] $PointerToRawData = $b.ReadUInt32();        

        if ($dwRVA -ge $VirtualAddress -and $dwRVA -lt ($VirtualAddress + $VirtualSize)) {
            $delta = $VirtualAddress - $PointerToRawData;
            $dwRet = $dwRVA - $delta;
            return $dwRet;
        }
        );
    }
    return $dwRet;
}

function Get-Bitness2([System.String]$path, $showLog = $false)
{
    $Obj = @{};
    $Obj.Result = '';
    $Obj.Error = $false;

    $Obj.Log = @(Split-Path -Path $path -Leaf -Resolve);

    $b = new-object System.IO.BinaryReader([System.IO.File]::Open($path,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read, [System.IO.FileShare]::Read));
    $curr_offset = $b.BaseStream.Seek(0x3c, [System.IO.SeekOrigin]::Begin)
    [System.Int32] $peOffset = $b.ReadInt32();
    $Obj.Log += 'peOffset ' + "{0:X0}" -f $peOffset;

    $curr_offset = $b.BaseStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin);
    [System.UInt32] $peHead = $b.ReadUInt32();

    if ($peHead -ne 0x00004550) {
        $Obj.Error = $true;
        $Obj.Result = 'Bad Image Format';
        $Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
    };

    if ($Obj.Error)
    {
        $b.Close();
        Write-Host ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    [System.UInt16] $machineType = $b.ReadUInt16();
    $Obj.Log += 'machineType ' + "{0:X0}" -f $machineType;

    [System.UInt16] $numOfSections = $b.ReadUInt16();
    $Obj.Log += 'numOfSections ' + "{0:X0}" -f $numOfSections;
    if (($machineType -eq 0x8664) -or ($machineType -eq 0x200)) { $Obj.Log += 'machineType: x64'; }
    elseif ($machineType -eq 0x14c)                             { $Obj.Log += 'machineType: x86'; }
    elseif ($machineType -eq 0x1c0)                             { $Obj.Log += 'machineType: ARM'; }
    else{
        $Obj.Error = $true;
        $Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
    };

    if ($Obj.Error) {
        $b.Close();
        Write-Output ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    $curr_offset = $b.BaseStream.Seek($peOffset+20, [System.IO.SeekOrigin]::Begin);
    [System.UInt16] $sizeOfPeHeader = $b.ReadUInt16();

    $coffOffset = $peOffset + 24;#PE header size is 24 bytes
    $Obj.Log += 'coffOffset ' + "{0:X0}" -f $coffOffset;

    $curr_offset = $b.BaseStream.Seek($coffOffset, [System.IO.SeekOrigin]::Begin);#+24 byte magic number
    [System.UInt16] $pe32 = $b.ReadUInt16();         
    $clr20headerOffset = 0;
    $flag32bit = $false;
    $Obj.Log += 'pe32 magic number: ' + "{0:X0}" -f $pe32;
    $Obj.Log += 'size of optional header ' + ("{0:D0}" -f $sizeOfPeHeader) + " bytes";

    #COMIMAGE_FLAGS_ILONLY               =0x00000001,
    #COMIMAGE_FLAGS_32BITREQUIRED        =0x00000002,
    #COMIMAGE_FLAGS_IL_LIBRARY           =0x00000004,
    #COMIMAGE_FLAGS_STRONGNAMESIGNED     =0x00000008,
    #COMIMAGE_FLAGS_NATIVE_ENTRYPOINT    =0x00000010,
    #COMIMAGE_FLAGS_TRACKDEBUGDATA       =0x00010000,
    #COMIMAGE_FLAGS_32BITPREFERRED       =0x00020000,

    $COMIMAGE_FLAGS_ILONLY        = 0x00000001;
    $COMIMAGE_FLAGS_32BITREQUIRED = 0x00000002;
    $COMIMAGE_FLAGS_32BITPREFERRED = 0x00020000;

    $offset = 96;
    if ($pe32 -eq 0x20b) {
        $offset = 112;#size of COFF header is bigger for pe32+
    }     

    $clr20dirHeaderOffset = $coffOffset + $offset + 14*8;#clr directory header offset + start of section number 15 (each section is 8 byte long);
    $Obj.Log += 'clr20dirHeaderOffset ' + "{0:X0}" -f $clr20dirHeaderOffset;
    $curr_offset = $b.BaseStream.Seek($clr20dirHeaderOffset, [System.IO.SeekOrigin]::Begin);
    [System.UInt32] $clr20VirtualAddress = $b.ReadUInt32();
    [System.UInt32] $clr20Size = $b.ReadUInt32();
    $Obj.Log += 'clr20VirtualAddress ' + "{0:X0}" -f $clr20VirtualAddress;
    $Obj.Log += 'clr20SectionSize ' + ("{0:D0}" -f $clr20Size) + " bytes";

    if ($clr20Size -eq 0) {
        if ($machineType -eq 0x1c0) { $Obj.Result = 'ARM native'; }
        elseif ($pe32 -eq 0x10b)    { $Obj.Result = '32-bit native'; }
        elseif($pe32 -eq 0x20b)     { $Obj.Result = '64-bit native'; }

       $b.Close();   
       if ($Obj.Result -eq '') { 
            $Obj.Error = $true;
            $Obj.Log += 'Unknown type of file';
       }
       else { 
            if ($showLog) { Write-Output ($Obj.Log | Format-List | Out-String); };
            return $Obj.Result;
       }
    };

    if ($Obj.Error) {
        $b.Close();
        Write-Host ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    [System.UInt32]$sectionsOffset = $coffOffset + $sizeOfPeHeader;
    $Obj.Log += 'sectionsOffset ' + "{0:X0}" -f $sectionsOffset;
    $realOffset = GetActualAddressFromRVA $b $sectionsOffset $numOfSections $clr20VirtualAddress;
    $Obj.Log += 'real IMAGE_COR20_HEADER offset ' + "{0:X0}" -f $realOffset;
    if ($realOffset -eq 0) {
        $Obj.Error = $true;
        $Obj.Log += 'cannot find COR20 header - exit with error';
        $b.Close();
        return $false;
    };

    if ($Obj.Error) {
        $b.Close();
        Write-Host ($Obj.Log | Format-List | Out-String);
        return $false;
    };

    $curr_offset = $b.BaseStream.Seek($realOffset + 4, [System.IO.SeekOrigin]::Begin);
    [System.UInt16] $majorVer = $b.ReadUInt16();
    [System.UInt16] $minorVer = $b.ReadUInt16();
    $Obj.Log += 'IMAGE_COR20_HEADER version ' + ("{0:D0}" -f $majorVer) + "." + ("{0:D0}" -f $minorVer);

    $flagsOffset = 16;#+16 bytes - flags field
    $curr_offset = $b.BaseStream.Seek($realOffset + $flagsOffset, [System.IO.SeekOrigin]::Begin);
    [System.UInt32] $flag32bit = $b.ReadUInt32();
    $Obj.Log += 'CorFlags: ' + ("{0:X0}" -f $flag32bit);

#Description       C# compiler switch             PE type       machine corflags
#MSIL              /platform:anycpu (default)     PE32  x86     ILONLY
#MSIL 32 bit pref  /platform:anycpu32bitpreferred PE32  x86     ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed       /platform:x86                  PE32  x86     ILONLY | 32BITREQUIRED
#x86 mixed         n/a                            PE32  x86     32BITREQUIRED
#x64 managed       /platform:x64                  PE32+ x64     ILONLY
#x64 mixed         n/a                            PE32+ x64  
#ARM managed       /platform:arm                  PE32  ARM     ILONLY
#ARM mixed         n/a                            PE32  ARM  

    $isILOnly = ($flag32bit -band $COMIMAGE_FLAGS_ILONLY) -eq $COMIMAGE_FLAGS_ILONLY;
    $Obj.Log += 'ILONLY: ' + $isILOnly;
    if ($machineType -eq 0x1c0) {#if ARM
        if ($isILOnly) { $Obj.Result = 'ARM managed'; } 
                  else { $Obj.Result = 'ARM mixed'; }
    }
    elseif ($pe32 -eq 0x10b) {#pe32
        $is32bitRequired = ($flag32bit -band $COMIMAGE_FLAGS_32BITREQUIRED) -eq $COMIMAGE_FLAGS_32BITREQUIRED;
        $is32bitPreffered = ($flag32bit -band $COMIMAGE_FLAGS_32BITPREFERRED) -eq $COMIMAGE_FLAGS_32BITPREFERRED;
        $Obj.Log += '32BIT: ' + $is32bitRequired;    
        $Obj.Log += '32BIT PREFFERED: ' + $is32bitPreffered 
        if     ($is32bitRequired  -and $isILOnly  -and $is32bitPreffered) { $Obj.Result = 'AnyCpu 32bit-preffered'; }
        elseif ($is32bitRequired  -and $isILOnly  -and !$is32bitPreffered){ $Obj.Result = 'x86 managed'; }
        elseif (!$is32bitRequired -and !$isILOnly -and $is32bitPreffered) { $Obj.Result = 'x86 mixed'; }
        elseif ($isILOnly)                                                { $Obj.Result = 'AnyCpu'; }
   }
   elseif ($pe32 -eq 0x20b) {#pe32+
        if ($isILOnly) { $Obj.Result = 'x64 managed'; } 
                  else { $Obj.Result = 'x64 mixed'; }
   }

   $b.Close();   
   if ($showLog) { Write-Host ($Obj.Log | Format-List | Out-String); }
   if ($Obj.Result -eq ''){ return 'Unknown type of file';};
   $flags = '';
   if ($isILOnly) {$flags += 'ILONLY';}
   if ($is32bitRequired) {
        if ($flags -ne '') {$flags += ' | ';}
        $flags += '32BITREQUIRED';
   }
   if ($is32bitPreffered) {
        if ($flags -ne '') {$flags += ' | ';}
        $flags += '32BITPREFERRED';
   }
   if ($flags -ne '') {$flags = ' (' + $flags +')';}
   return $Obj.Result + $flags;
}

usage example:

#$filePath = "C:\Windows\SysWOW64\regedit.exe";#32 bit native on 64bit windows
$filePath = "C:\Windows\regedit.exe";#64 bit native on 64bit windows | should be 32 bit native on 32bit windows

Get-Bitness2 $filePath $true;

you can omit second parameter if you don't need to see details

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

Encrypt & Decrypt using PyCrypto AES 256

It's little late but i think this will be very helpful. No one mention about use scheme like PKCS#7 padding. You can use it instead the previous functions to pad(when do encryption) and unpad(when do decryption).i will provide the full Source Code below.

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
import pkcs7
class Encryption:

    def __init__(self):
        pass

    def Encrypt(self, PlainText, SecurePassword):
        pw_encode = SecurePassword.encode('utf-8')
        text_encode = PlainText.encode('utf-8')

        key = hashlib.sha256(pw_encode).digest()
        iv = Random.new().read(AES.block_size)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        pad_text = pkcs7.encode(text_encode)
        msg = iv + cipher.encrypt(pad_text)

        EncodeMsg = base64.b64encode(msg)
        return EncodeMsg

    def Decrypt(self, Encrypted, SecurePassword):
        decodbase64 = base64.b64decode(Encrypted.decode("utf-8"))
        pw_encode = SecurePassword.decode('utf-8')

        iv = decodbase64[:AES.block_size]
        key = hashlib.sha256(pw_encode).digest()

        cipher = AES.new(key, AES.MODE_CBC, iv)
        msg = cipher.decrypt(decodbase64[AES.block_size:])
        pad_text = pkcs7.decode(msg)

        decryptedString = pad_text.decode('utf-8')
        return decryptedString

import StringIO
import binascii


def decode(text, k=16):
    nl = len(text)
    val = int(binascii.hexlify(text[-1]), 16)
    if val > k:
        raise ValueError('Input is not padded or padding is corrupt')

    l = nl - val
    return text[:l]


def encode(text, k=16):
    l = len(text)
    output = StringIO.StringIO()
    val = k - (l % k)
    for _ in xrange(val):
        output.write('%02x' % val)
    return text + binascii.unhexlify(output.getvalue())

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the javascript filename naming convention?

One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.

product-name.plugin-ver.sion.filetype.js

where the product-name + plugin pair can also represent a namespace and a module. The version and filetype are usually optional.

filetype can be something relative to how the content of the file is. Often seen are:

  • min for minified files
  • custom for custom built or modified files

Examples:

  • jquery-1.4.2.min.js
  • jquery.plugin-0.1.js
  • myapp.invoice.js

Property getters and setters

You are recursively defining x with x. As if someone asks you how old are you? And you answer "I am twice my age". Which is meaningless.

You must say I am twice John's age or any other variable but yourself.

computed variables are always dependent on another variable.


The rule of the thumb is never access the property itself from within the getter ie get. Because that would trigger another get which would trigger another . . . Don't even print it. Because printing also requires to 'get' the value before it can print it!

struct Person{
    var name: String{
        get{
            print(name) // DON'T do this!!!!
            return "as"
        }
        set{
        }
    }
}

let p1 = Person()

As that would give the following warning:

Attempting to access 'name' from within it's own getter.

The error looks vague like this:

enter image description here

As an alternative you might want to use didSet. With didSet you'll get a hold to the value that is was set before and just got set to. For more see this answer.

How can I extract audio from video with ffmpeg?

ffmpeg -i sample.avi will give you the audio/video format info for your file. Make sure you have the proper libraries configured to parse the input streams. Also, make sure that the file isn't corrupt.

How to print all key and values from HashMap in Android?

for (Map.Entry<String,String> entry : map.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue();
  // do stuff
}

How do you find the row count for all your tables in Postgres

To get estimates, see Greg Smith's answer.

To get exact counts, the other answers so far are plagued with some issues, some of them serious (see below). Here's a version that's hopefully better:

CREATE FUNCTION rowcount_all(schema_name text default 'public')
  RETURNS table(table_name text, cnt bigint) as
$$
declare
 table_name text;
begin
  for table_name in SELECT c.relname FROM pg_class c
    JOIN pg_namespace s ON (c.relnamespace=s.oid)
    WHERE c.relkind = 'r' AND s.nspname=schema_name
  LOOP
    RETURN QUERY EXECUTE format('select cast(%L as text),count(*) from %I.%I',
       table_name, schema_name, table_name);
  END LOOP;
end
$$ language plpgsql;

It takes a schema name as parameter, or public if no parameter is given.

To work with a specific list of schemas or a list coming from a query without modifying the function, it can be called from within a query like this:

WITH rc(schema_name,tbl) AS (
  select s.n,rowcount_all(s.n) from (values ('schema1'),('schema2')) as s(n)
)
SELECT schema_name,(tbl).* FROM rc;

This produces a 3-columns output with the schema, the table and the rows count.

Now here are some issues in the other answers that this function avoids:

  • Table and schema names shouldn't be injected into executable SQL without being quoted, either with quote_ident or with the more modern format() function with its %I format string. Otherwise some malicious person may name their table tablename;DROP TABLE other_table which is perfectly valid as a table name.

  • Even without the SQL injection and funny characters problems, table name may exist in variants differing by case. If a table is named ABCD and another one abcd, the SELECT count(*) FROM... must use a quoted name otherwise it will skip ABCD and count abcd twice. The %I of format does this automatically.

  • information_schema.tables lists custom composite types in addition to tables, even when table_type is 'BASE TABLE' (!). As a consequence, we can't iterate oninformation_schema.tables, otherwise we risk having select count(*) from name_of_composite_type and that would fail. OTOH pg_class where relkind='r' should always work fine.

  • The type of COUNT() is bigint, not int. Tables with more than 2.15 billion rows may exist (running a count(*) on them is a bad idea, though).

  • A permanent type need not to be created for a function to return a resultset with several columns. RETURNS TABLE(definition...) is a better alternative.

python: how to check if a line is an empty line

line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

Is there a better way to do optional function parameters in JavaScript?

I suggest you to use ArgueJS this way:

function myFunc(){
  arguments = __({requiredArg: undefined, optionalArg: [undefined: 'defaultValue'})

  //do stuff, using arguments.requiredArg and arguments.optionalArg
  //    to access your arguments

}

You can also replace undefined by the type of the argument you expect to receive, like this:

function myFunc(){
  arguments = __({requiredArg: Number, optionalArg: [String: 'defaultValue'})

  //do stuff, using arguments.requiredArg and arguments.optionalArg
  //    to access your arguments

}

Redirect non-www to www in .htaccess

I believe the top answer successfully redirects non-www to www (ex: mysite.com -> www.mysite.com), but doesn't take into account wildcard subdomains, which results in:

random.mysite.com -> www.random.mysite.com

Here's a solution with/without HTTPS

HTTP

RewriteEngine On

RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://www.mysite.com/$1 [L,R=301] 

HTTP/HTTPS

RewriteEngine On

RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=protocol:https]

RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=protocol:http]

RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
RewriteRule ^(.*)$ %{ENV:protocol}://www.mysite.com/$1 [L,R=301]

*note: I haven't tested https because I don't currently have a cert to test, but if someone can verify or optimize what I have that would be awesome.

Nested or Inner Class in PHP

You can, like this, in PHP 7:

class User{
  public $id;
  public $name;
  public $password;
  public $Profile;
  public $History;  /*  (optional declaration, if it isn't public)  */
  public function __construct($id,$name,$password){
    $this->id=$id;
    $this->name=$name;
    $this->name=$name;
    $this->Profile=(object)[
        'get'=>function(){
          return 'Name: '.$this->name.''.(($this->History->get)());
        }
      ];
    $this->History=(object)[
        'get'=>function(){
          return ' History: '.(($this->History->track)());
        }
        ,'track'=>function(){
          return (lcg_value()>0.5?'good':'bad');
        }
      ];
  }
}
echo ((new User(0,'Lior','nyh'))->Profile->get)();

How can I get a list of locally installed Python modules?

This will help

In terminal or IPython, type:

help('modules')

then

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

How to use NSJSONSerialization

Swift 2.0 on Xcode 7 (Beta) with do/try/catch block:

// MARK: NSURLConnectionDataDelegate

func connectionDidFinishLoading(connection:NSURLConnection) {
  do {
    if let response:NSDictionary = try NSJSONSerialization.JSONObjectWithData(receivedData, options:NSJSONReadingOptions.MutableContainers) as? Dictionary<String, AnyObject> {
      print(response)
    } else {
      print("Failed...")
    }
  } catch let serializationError as NSError {
    print(serializationError)
  }
}

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

Set the absolute position of a view

My code for Xamarin, I am using FrameLayout for this purpose and following is my code:

               List<object> content = new List<object>();

        object aWebView = new {ContentType="web",Width="300", Height = "300",X="10",Y="30",ContentUrl="http://www.google.com" };
        content.Add(aWebView);
        object aWebView2 = new { ContentType = "image", Width = "300", Height = "300", X = "20", Y = "40", ContentUrl = "https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4" };
        content.Add(aWebView2);
        FrameLayout myLayout = (FrameLayout)FindViewById(Resource.Id.frameLayout1);
        foreach (object item in content)
        {

            string contentType = item.GetType().GetProperty("ContentType").GetValue(item, null).ToString();
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(Convert.ToInt32(item.GetType().GetProperty("Width").GetValue(item, null).ToString()), Convert.ToInt32(item.GetType().GetProperty("Height").GetValue(item, null).ToString()));
            param.LeftMargin = Convert.ToInt32(item.GetType().GetProperty("X").GetValue(item, null).ToString());
            param.TopMargin = Convert.ToInt32(item.GetType().GetProperty("Y").GetValue(item, null).ToString());

            switch (contentType) {
                case "web":{
                        WebView webview = new WebView(this);

                        //webview.hei;
                        myLayout.AddView(webview, param);
                        webview.SetWebViewClient(new WebViewClient());
                        webview.LoadUrl(item.GetType().GetProperty("ContentUrl").GetValue(item, null).ToString());

                        break;
                    }
                case "image":
                    {
                        ImageView imageview = new ImageView(this);

                        //webview.hei;
                        myLayout.AddView(imageview, param);
                        var imageBitmap =  GetImageBitmapFromUrl("https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4");
                        imageview.SetImageBitmap(imageBitmap);


                        break;
                    }

            }

        }

It was useful for me because I needed the property of view to overlap each other on basis of their appearance, e.g the views get stacked one above other.

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

Install windows service without InstallUtil.exe

Not double click, you run it with the correct command line parameters, so type something like MyService -i and then MyService -u to uninstall it`.

You could otherwise use sc.exe to install and uninstall it (or copy along InstallUtil.exe).

Reading PDF content with itextsharp dll in VB.NET or C#

In my case, I just wanted the text from a specific area of the PDF document so I used a rectangle around the area and extracted the text from it. In the sample below the coordinates are for the entire page. I don't have PDF authoring tools so when it came time to narrow down the rectangle to the specific location I took a few guesses at the coordinates until the area was found.

Rectangle _pdfRect = new Rectangle(0f, 0f, 612f, 792f); // Entire page - PDF coordinate system 0,0 is bottom left corner.  72 points / inch
RenderFilter _renderfilter = new RegionTextRenderFilter(_pdfRect);
ITextExtractionStrategy _strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), _filter);
string _text = PdfTextExtractor.GetTextFromPage(_pdfReader, 1, _strategy);

As noted by the above comments the resulting text doesn't maintain any of the formatting found in the PDF document, however, I was happy that it did preserve the carriage returns. In my case, there were enough constants in the text that I was able to extract the values that I required.

What does %s and %d mean in printf in the C language?

The printf() family of functions uses % character as a placeholder. When a % is encountered, printf reads the characters following the % to determine what to do:

%s - Take the next argument and print it as a string
%d - Take the next argument and print it as an int

See this Wikipedia article for a nice picture: printf format string

The \n at the end of the string is for a newline/carriage-return character.

How to check 'undefined' value in jQuery

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

function A(val){
  if(typeof(val)  === "undefined") 
    //do this
  else
   //do this
}

Getting data posted in between two dates

Just simply write BETWEEN '{$startDate}' AND '{$endDate}' in where condition as

->where("date BETWEEN '{$startDate}' AND '{$endDate}'")

Can I override and overload static methods in Java?

Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.

This is why you get a compiler warning when you write

 MyClass myObject = new MyClass();
 myObject.myStaticMethod();
 // should be written as
 MyClass.myStaticMethod()
 // because it is not dispatched on myObject
 myObject = new MySubClass();
 myObject.myStaticMethod(); 
 // still calls the static method in MyClass, NOT in MySubClass

Static methods can be overloaded (meaning that you can have the same method name for several methods as long as they have different parameter types).

 Integer.parseInt("10");
 Integer.parseInt("AA", 16);

How do I add a newline to a TextView in Android?

This solved my problem.

stringVar.replaceAll("\\\\n", "\\\n");

Remove all unused resources from an android project

Since ADT 16 you can use Android Lint. It is really amazing tool.

Android Lint is a new tool for ADT 16 (and Tools 16) which scans Android project sources for potential bugs.

Here are some examples of the types of errors that it looks for:

  • Missing translations (and unused translations)
  • Layout performance problems (all the issues the old layoutopt tool used to find, and more)
  • Unused resources
  • Inconsistent array sizes (when arrays are defined in multiple configurations)
  • Accessibility and internationalization problems (hardcoded strings, missing contentDescription, etc)
  • Icon problems (like missing densities, duplicate icons, wrong sizes, etc)
  • Usability problems (like not specifying an input type on a text field)
  • Manifest errors and many more.

However, it has some issues (don't know if they're already fixed) and if you want to delete hundreds of supposedly unused resources I'd recommend to manually compile project several times during resource removing to be sure that Lint didn't remove something needed.

How to detect scroll direction

You can use this simple plugin to add scrollUp and scrollDown to your jQuery

https://github.com/phpust/JQueryScrollDetector

var lastScrollTop = 0;
var action = "stopped";
var timeout = 100;
// Scroll end detector:
$.fn.scrollEnd = function(callback, timeout) {    
      $(this).scroll(function(){
        // get current scroll top 
        var st = $(this).scrollTop();
        var $this = $(this);
        // fix for page loads
        if (lastScrollTop !=0 )
        {
            // if it's scroll up
            if (st < lastScrollTop){
                action = "scrollUp";
            } 
            // else if it's scroll down
            else if (st > lastScrollTop){
                action = "scrollDown";
            }
        }
        // set the current scroll as last scroll top
        lastScrollTop = st;
        // check if scrollTimeout is set then clear it
        if ($this.data('scrollTimeout')) {
          clearTimeout($this.data('scrollTimeout'));
        }
        // wait until timeout done to overwrite scrolls output
        $this.data('scrollTimeout', setTimeout(callback,timeout));
    });
};

$(window).scrollEnd(function(){
    if(action!="stopped"){
        //call the event listener attached to obj.
        $(document).trigger(action); 
    }
}, timeout);

Restricting JTextField input to Integers

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

For example: using-documentfilter-filterbypass

Also for tutorial help, please look at: Implementing a DocumentFilter.

Edit

For instance:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
   public static void main(String[] args) {
      JTextField textField = new JTextField(10);

      JPanel panel = new JPanel();
      panel.add(textField);

      PlainDocument doc = (PlainDocument) textField.getDocument();
      doc.setDocumentFilter(new MyIntFilter());


      JOptionPane.showMessageDialog(null, panel);
   }
}

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

Why is this important?

  • What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?
  • You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?
  • What if you want to allow the user to later enter double data? In scientific notation?

Get environment variable value in Dockerfile

So you can do: cat Dockerfile | envsubst | docker build -t my-target -

Then have a Dockerfile with something like:

ENV MY_ENV_VAR $MY_ENV_VAR

I guess there might be a problem with some special characters, but this works for most cases at least.

How to prevent IFRAME from redirecting top-level window

I use sandbox="..."

  • allow-forms allows form submission
  • allow-popups allows popups
  • allow-pointer-lock allows pointer lock
  • allow-same-origin allows the document to maintain its origin
  • allow-scripts allows JavaScript execution, and also allows features to trigger automatically
  • allow-top-navigation allows the document to break out of the frame by navigating the top-level window

Top navigation is what you want to prevent, so leave that out and it will not be allowed. Anything left out will be blocked

ex.

        <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"</iframe>

XAMPP - Apache could not start - Attempting to start Apache service

For those who have accidentally (or not) changed one of the .conf files and apache does not run even after trying all the above solutions.

One easy way to track where the issue is located, is to run Apache via command prompt:

(On windows) : open command prompt as admin then navigate inside the bin folder of Apache , next run

httpd in order to run apache

C:\xampp\apache\bin\httpd

For my case it was :

apache via cmd

someone had added a virtual host in the specific file that caused the problem . I commented the lines and Apache ran fine.

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

How do I find the authoritative name-server for a domain name?

I have found that for some domains, the above answers do not work. The quickest way I have found is to first check for an NS record. If that doesn't exist, check for an SOA record. If that doesn't exist, recursively resolve the name using dig and take the last NS record returned. An example that fits this is analyticsdcs.ccs.mcafee.com.

  1. Check for an NS record

host -t NS analyticsdcs.ccs.mcafee.com.

  1. If no NS found, check for an SOA record

host -t SOA analyticsdcs.ccs.mcafee.com.

  1. If neither NS or SOA, do full recursive and take the last NS returned

dig +trace analyticsdcs.ccs.mcafee.com. | grep -w 'IN[[:space:]]*NS' | tail -1

  1. Test that the name server returned works

host analyticsdcs.ccs.mcafee.com. gtm2.mcafee.com.

How can I know if a branch has been already merged into master?

There is a graphical interface solution as well. Just type

gitk --all

A new application window will prompt with a graphical representation of your whole repo, where it is very easy to realize if a branch was already merged or not

Get dates from a week number in T-SQL

You can set @WeekNum and @YearNum to whatever you want - in this example they are derived from the @datecol variable, which is set to GETDATE() for purposes of illustration. Once you have those values- you can calculate the date range for a week by using the following:

DECLARE @datecol datetime = GETDATE();
DECLARE @WeekNum INT
      , @YearNum char(4);

SELECT @WeekNum = DATEPART(WK, @datecol)
     , @YearNum = CAST(DATEPART(YY, @datecol) AS CHAR(4));

-- once you have the @WeekNum and @YearNum set, the following calculates the date range.
SELECT DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + @YearNum) + (@WeekNum-1), 6) AS StartOfWeek;
SELECT DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + @YearNum) + (@WeekNum-1), 5) AS EndOfWeek;

Are global variables bad?

No they are not bad at all. You need to look at the (machine) code produced by the compiler to make this determination, sometimes it is far far worse to use a local than a global. Also note that putting "static" on a local variable is basically making it a global (and creates other ugly problems that a real global would solve). "local globals" are particularly bad.

Globals give you clean control over your memory usage as well, something far more difficult to do with locals. These days that only matters in embedded environments where memory is quite limited. Something to know before you assume that embedded is the same as other environments and assume the programming rules are the same across the board.

It is good that you question the rules being taught, most of them are not for the reasons you are being told. The most important lesson though is not that this is a rule to carry with you forever, but this is a rule required to honor in order to pass this class and move forward. In life you will find that for company XYZ you will have other programming rules that you in the end will have to honor in order to keep getting a paycheck. In both situations you can argue the rule, but I think you will have far better luck at a job than at school. You are just another of many students, your seat will be replaced soon, the professors wont, at a job you are one of a small team of players that have to see this product to the end and in that environment the rules developed are for the benefit of the team members as well as the product and the company, so if everyone is like minded or if for the particular product there is good engineering reason to violate something you learned in college or some book on generic programming, then sell your idea to the team and write it down as a valid if not the preferred method. Everything is fair game in the real world.

If you follow all of the programming rules taught to you in school or books your programming career will be extremely limited. You can likely survive and have a fruitful career, but the breadth and width of the environments available to you will be extremely limited. If you know how and why the rule is there and can defend it, thats good, if you only reason is "because my teacher said so", well thats not so good.

Note that topics like this are often argued in the workplace and will continue to be, as compilers and processors (and languages) evolve so do these kinds of rules and without defending your position and possibly being taught a lesson by someone with another opinion you wont move forward.

In the mean time, then just do whatever the one that speaks the loudest or carries the biggest stick says (until such a time as you are the one that yells the loudest and carries the biggest stick).

Difference between /res and /assets directories

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.

CSS background opacity with rgba not working in IE 8

The best solution I found so far is the one proposed by David J Marland in his blog, to support opacity in old browsers (IE 6+):

.alpha30{
    background:rgb(255,0,0); /* Fallback for web browsers that don't support RGBa nor filter */ 
    background: transparent\9; /* backslash 9 hack to prevent IE 8 from falling into the fallback */
    background:rgba(255,0,0,0.3); /* RGBa declaration for browsers that support it */
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4cFF0000,endColorstr=#4cFF0000); /* needed for IE 6-8 */
    zoom: 1; /* needed for IE 6-8 */
}

/* 
 * CSS3 selector (not supported by IE 6 to IE 8),
 * to avoid IE more recent versions to apply opacity twice
 * (once with rgba and once with filter)
 */
.alpha30:nth-child(n) {
    filter: none;
}

Invoke-WebRequest, POST with parameters

Single command without ps variables when using JSON as body {lastName:"doe"} for POST api call:

Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
                  -Method POST `
                  -Body (@{"lastName"="doe";}|ConvertTo-Json) `
                  -Uri https://api.dummy.com/getUsers `
                  -ContentType application/json

Java Round up Any Number

int RoundedUp = (int) Math.ceil(RandomReal);

This seemed to do the perfect job. Worked everytime.

Using os.walk() to recursively traverse directories in Python

This will give you the desired result

#!/usr/bin/python

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

You only need the async pipe:

<li *ngFor="let afd of afdeling | async">
    {{afd.patientid}}
</li>

always use the async pipe when dealing with Observables directly without explicitly unsubscribe.

How can I fill a div with an image while keeping it proportional?

The only way I achieved the "best case" scenario described, was putting the image as a background:

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

How to concatenate strings in twig

Whenever you need to use a filter with a concatenated string (or a basic math operation) you should wrap it with ()'s. Eg.:

{{ ('http://' ~ app.request.host) | url_encode }}

PHPExcel Make first row bold

You can try

$objPHPExcel->getActiveSheet()->getStyle(1)->getFont()->setBold(true);

Improving bulk insert performance in Entity framework

Using the code below you can extend the partial context class with a method that will take a collection of entity objects and bulk copy them to the database. Simply replace the name of the class from MyEntities to whatever your entity class is named and add it to your project, in the correct namespace. After that all you need to do is call the BulkInsertAll method handing over the entity objects you want to insert. Do not reuse the context class, instead create a new instance every time you use it. This is required, at least in some versions of EF, since the authentication data associated with the SQLConnection used here gets lost after having used the class once. I don't know why.

This version is for EF 5

public partial class MyEntities
{
    public void BulkInsertAll<T>(T[] entities) where T : class
    {
        var conn = (SqlConnection)Database.Connection;

        conn.Open();

        Type t = typeof(T);
        Set(t).ToString();
        var objectContext = ((IObjectContextAdapter)this).ObjectContext;
        var workspace = objectContext.MetadataWorkspace;
        var mappings = GetMappings(workspace, objectContext.DefaultContainerName, typeof(T).Name);

        var tableName = GetTableName<T>();
        var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = tableName };

        // Foreign key relations show up as virtual declared 
        // properties and we want to ignore these.
        var properties = t.GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
        var table = new DataTable();
        foreach (var property in properties)
        {
            Type propertyType = property.PropertyType;

            // Nullable properties need special treatment.
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                propertyType = Nullable.GetUnderlyingType(propertyType);
            }

            // Since we cannot trust the CLR type properties to be in the same order as
            // the table columns we use the SqlBulkCopy column mappings.
            table.Columns.Add(new DataColumn(property.Name, propertyType));
            var clrPropertyName = property.Name;
            var tableColumnName = mappings[property.Name];
            bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(clrPropertyName, tableColumnName));
        }

        // Add all our entities to our data table
        foreach (var entity in entities)
        {
            var e = entity;
            table.Rows.Add(properties.Select(property => GetPropertyValue(property.GetValue(e, null))).ToArray());
        }

        // send it to the server for bulk execution
        bulkCopy.BulkCopyTimeout = 5 * 60;
        bulkCopy.WriteToServer(table);

        conn.Close();
    }

    private string GetTableName<T>() where T : class
    {
        var dbSet = Set<T>();
        var sql = dbSet.ToString();
        var regex = new Regex(@"FROM (?<table>.*) AS");
        var match = regex.Match(sql);
        return match.Groups["table"].Value;
    }

    private object GetPropertyValue(object o)
    {
        if (o == null)
            return DBNull.Value;
        return o;
    }

    private Dictionary<string, string> GetMappings(MetadataWorkspace workspace, string containerName, string entityName)
    {
        var mappings = new Dictionary<string, string>();
        var storageMapping = workspace.GetItem<GlobalItem>(containerName, DataSpace.CSSpace);
        dynamic entitySetMaps = storageMapping.GetType().InvokeMember(
            "EntitySetMaps",
            BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance,
            null, storageMapping, null);

        foreach (var entitySetMap in entitySetMaps)
        {
            var typeMappings = GetArrayList("TypeMappings", entitySetMap);
            dynamic typeMapping = typeMappings[0];
            dynamic types = GetArrayList("Types", typeMapping);

            if (types[0].Name == entityName)
            {
                var fragments = GetArrayList("MappingFragments", typeMapping);
                var fragment = fragments[0];
                var properties = GetArrayList("AllProperties", fragment);
                foreach (var property in properties)
                {
                    var edmProperty = GetProperty("EdmProperty", property);
                    var columnProperty = GetProperty("ColumnProperty", property);
                    mappings.Add(edmProperty.Name, columnProperty.Name);
                }
            }
        }

        return mappings;
    }

    private ArrayList GetArrayList(string property, object instance)
    {
        var type = instance.GetType();
        var objects = (IEnumerable)type.InvokeMember(property, BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance, null, instance, null);
        var list = new ArrayList();
        foreach (var o in objects)
        {
            list.Add(o);
        }
        return list;
    }

    private dynamic GetProperty(string property, object instance)
    {
        var type = instance.GetType();
        return type.InvokeMember(property, BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance, null, instance, null);
    }
}

This version is for EF 6

public partial class CMLocalEntities
{
    public void BulkInsertAll<T>(T[] entities) where T : class
    {
        var conn = (SqlConnection)Database.Connection;

        conn.Open();

        Type t = typeof(T);
        Set(t).ToString();
        var objectContext = ((IObjectContextAdapter)this).ObjectContext;
        var workspace = objectContext.MetadataWorkspace;
        var mappings = GetMappings(workspace, objectContext.DefaultContainerName, typeof(T).Name);

        var tableName = GetTableName<T>();
        var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = tableName };

        // Foreign key relations show up as virtual declared 
        // properties and we want to ignore these.
        var properties = t.GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
        var table = new DataTable();
        foreach (var property in properties)
        {
            Type propertyType = property.PropertyType;

            // Nullable properties need special treatment.
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                propertyType = Nullable.GetUnderlyingType(propertyType);
            }

            // Since we cannot trust the CLR type properties to be in the same order as
            // the table columns we use the SqlBulkCopy column mappings.
            table.Columns.Add(new DataColumn(property.Name, propertyType));
            var clrPropertyName = property.Name;
            var tableColumnName = mappings[property.Name];
            bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(clrPropertyName, tableColumnName));
        }

        // Add all our entities to our data table
        foreach (var entity in entities)
        {
            var e = entity;
            table.Rows.Add(properties.Select(property => GetPropertyValue(property.GetValue(e, null))).ToArray());
        }

        // send it to the server for bulk execution
        bulkCopy.BulkCopyTimeout = 5*60;
        bulkCopy.WriteToServer(table);

        conn.Close();
    }

    private string GetTableName<T>() where T : class
    {
        var dbSet = Set<T>();
        var sql = dbSet.ToString();
        var regex = new Regex(@"FROM (?<table>.*) AS");
        var match = regex.Match(sql);
        return match.Groups["table"].Value;
    }

    private object GetPropertyValue(object o)
    {
        if (o == null)
            return DBNull.Value;
        return o;
    }

    private Dictionary<string, string> GetMappings(MetadataWorkspace workspace, string containerName, string entityName)
    {
        var mappings = new Dictionary<string, string>();
        var storageMapping = workspace.GetItem<GlobalItem>(containerName, DataSpace.CSSpace);
        dynamic entitySetMaps = storageMapping.GetType().InvokeMember(
            "EntitySetMaps",
            BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
            null, storageMapping, null);

        foreach (var entitySetMap in entitySetMaps)
        {
            var typeMappings = GetArrayList("EntityTypeMappings", entitySetMap);
            dynamic typeMapping = typeMappings[0];
            dynamic types = GetArrayList("Types", typeMapping);

            if (types[0].Name == entityName)
            {
                var fragments = GetArrayList("MappingFragments", typeMapping);
                var fragment = fragments[0];
                var properties = GetArrayList("AllProperties", fragment);
                foreach (var property in properties)
                {
                    var edmProperty = GetProperty("EdmProperty", property);
                    var columnProperty = GetProperty("ColumnProperty", property);
                    mappings.Add(edmProperty.Name, columnProperty.Name);
                }
            }
        }

        return mappings;
    }

    private ArrayList GetArrayList(string property, object instance)
    {
        var type = instance.GetType();
        var objects = (IEnumerable)type.InvokeMember(
            property, 
            BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, instance, null);
        var list = new ArrayList();
        foreach (var o in objects)
        {
            list.Add(o);
        }
        return list;
    }

    private dynamic GetProperty(string property, object instance)
    {
        var type = instance.GetType();
        return type.InvokeMember(property, BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null, instance, null);
    }

}

And finally, a little something for you Linq-To-Sql lovers.

partial class MyDataContext
{
    partial void OnCreated()
    {
        CommandTimeout = 5 * 60;
    }

    public void BulkInsertAll<T>(IEnumerable<T> entities)
    {
        entities = entities.ToArray();

        string cs = Connection.ConnectionString;
        var conn = new SqlConnection(cs);
        conn.Open();

        Type t = typeof(T);

        var tableAttribute = (TableAttribute)t.GetCustomAttributes(
            typeof(TableAttribute), false).Single();
        var bulkCopy = new SqlBulkCopy(conn) { 
            DestinationTableName = tableAttribute.Name };

        var properties = t.GetProperties().Where(EventTypeFilter).ToArray();
        var table = new DataTable();

        foreach (var property in properties)
        {
            Type propertyType = property.PropertyType;
            if (propertyType.IsGenericType &&
                propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                propertyType = Nullable.GetUnderlyingType(propertyType);
            }

            table.Columns.Add(new DataColumn(property.Name, propertyType));
        }

        foreach (var entity in entities)
        {
            table.Rows.Add(properties.Select(
              property => GetPropertyValue(
              property.GetValue(entity, null))).ToArray());
        }

        bulkCopy.WriteToServer(table);
        conn.Close();
    }

    private bool EventTypeFilter(System.Reflection.PropertyInfo p)
    {
        var attribute = Attribute.GetCustomAttribute(p, 
            typeof (AssociationAttribute)) as AssociationAttribute;

        if (attribute == null) return true;
        if (attribute.IsForeignKey == false) return true; 

        return false;
    }

    private object GetPropertyValue(object o)
    {
        if (o == null)
            return DBNull.Value;
        return o;
    }
}

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

How can I create a link to a local file on a locally-run web page?

I've a way and work like this:

<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>

How to move up a directory with Terminal in OS X

To move up a directory, the quickest way would be to add an alias to ~/.bash_profile

alias ..='cd ..'

and then one would need only to type '..[return]'.

How do I limit the number of rows returned by an Oracle query after ordering?

An analytic solution with only one nested query:

SELECT * FROM
(
   SELECT t.*, Row_Number() OVER (ORDER BY name) MyRow FROM sometable t
) 
WHERE MyRow BETWEEN 10 AND 20;

Rank() could be substituted for Row_Number() but might return more records than you are expecting if there are duplicate values for name.

How to style an asp.net menu with CSS

I ran into the issue where the class of 'selected' wasn't being added to my menu item. Turns out that you can't have a NavigateUrl on it for whatever reason.

Once I removed the NavigateUrl it applied the 'selected' css class to the a tag and I was able to apply the background style with:

div.menu ul li a.static.selected
{
    background-color: #bfcbd6 !important;
    color: #465c71 !important;
    text-decoration: none !important;
}

How can I return two values from a function in Python?

you can try this

class select_choice():
    return x, y

a, b = test()

How do I assign a null value to a variable in PowerShell?

Use $dec = $null

From the documentation:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

Selenium Webdriver submit() vs click()

.Click() - Perform only click operation as like mouse click.

.Submit() - Perform Enter operation as like keyboard Enter event.

For Example. Consider a login page where it contains username and password and submit button.

On filling password if we want to login without clicking login button. we need to user .submit button on password where .click() operation does not work.[to login into application]

Brif.

driver.get("https:// anyURL"); 
driver.manage().window().maximize(); 
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
driver.findElement(By.id("txtUserId")).sendKeys("[email protected]"); 
WebElement text = driver.findElement(By.id("txtPassword")); text.sendKeys("password"); 
Thread.sleep(1000); 
text.click();   //This will not work - it will on perform click operation not submit operation
text.submit(); //This will perform submit operation has enter key 

Create an empty data.frame

The most efficient way to do this is to use structure to create a list that has the class "data.frame":

structure(list(Date = as.Date(character()), File = character(), User = character()), 
          class = "data.frame")
# [1] Date File User
# <0 rows> (or 0-length row.names)

To put this into perspective compared to the presently accepted answer, here's a simple benchmark:

s <- function() structure(list(Date = as.Date(character()), 
                               File = character(), 
                               User = character()), 
                          class = "data.frame")
d <- function() data.frame(Date = as.Date(character()),
                           File = character(), 
                           User = character(), 
                           stringsAsFactors = FALSE) 
library("microbenchmark")
microbenchmark(s(), d())
# Unit: microseconds
#  expr     min       lq     mean   median      uq      max neval
#   s()  58.503  66.5860  90.7682  82.1735 101.803  469.560   100
#   d() 370.644 382.5755 523.3397 420.1025 604.654 1565.711   100

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

PHP, getting variable from another php-file

You could also use file_get_contents

 $url_a="http://127.0.0.1/get_value.php?line=a&shift=1&tgl=2017-01-01";
 $data_a=file_get_contents($url_a);

 echo $data_a;

git rebase: "error: cannot stat 'file': Permission denied"

In my case, I had a webpack dev server running behind.

VB.Net Properties - Public Get, Private Set

If you are using VS2010 or later it is even easier than that

Public Property Name as String

You get the private properties and Get/Set completely for free!

see this blog post: Scott Gu's Blog

What is the difference between prefix and postfix operators?

Actually what happens is when you use postfix i.e. i++, the initial value of i is used for returning rather than the incremented one. After this the value of i is increased by 1. And this happens with any statement that uses i++, i.e. first initial value of i is used in the expression and then it is incremented.

And the exact opposite happens in prefix. If you would have returned ++i, then the incremented value i.e. 11 is returned, which is because adding 1 is performed first and then it is returned.

How to pass values between Fragments

As noted at developer site

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

communication between fragments should be done through the associated Activity.

Let's have the following components:

An activity hosts fragments and allow fragments communication

FragmentA first fragment which will send data

FragmentB second fragment which will receive datas from FragmentA

FragmentA's implementation is:

public class FragmentA extends Fragment 
{
    DataPassListener mCallback;
    
    public interface DataPassListener{
        public void passData(String data);
    }

    @Override
    public void onAttach(Context context) 
    {
        super.onAttach(context);
        // This makes sure that the host activity has implemented the callback interface
        // If not, it throws an exception
        try 
        {
            mCallback = (OnImageClickListener) context;
        }
        catch (ClassCastException e) 
        {
            throw new ClassCastException(context.toString()+ " must implement OnImageClickListener");
        }
    }
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        // Suppose that when a button clicked second FragmentB will be inflated
        // some data on FragmentA will pass FragmentB
        // Button passDataButton = (Button).........
        
        passDataButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (view.getId() == R.id.passDataButton) {
                    mCallback.passData("Text to pass FragmentB");
                }
            }
        });
    }
}

MainActivity implementation is:

public class MainActivity extends ActionBarActivity implements DataPassListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (findViewById(R.id.container) != null) {
            if (savedInstanceState != null) {
                return;
            }
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new FragmentA()).commit();
        }
    }
    
    @Override
    public void passData(String data) {
        FragmentB fragmentB = new FragmentB ();
        Bundle args = new Bundle();
        args.putString(FragmentB.DATA_RECEIVE, data);
        fragmentB .setArguments(args);
        getFragmentManager().beginTransaction()
            .replace(R.id.container, fragmentB )
            .commit();
    }
}

FragmentB implementation is:

public class FragmentB extends Fragment{
    final static String DATA_RECEIVE = "data_receive";
    TextView showReceivedData;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_B, container, false);
        showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        Bundle args = getArguments();
        if (args != null) {
            showReceivedData.setText(args.getString(DATA_RECEIVE));
        }
    }
}

I hope this will help..

background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent and background-image: none) without explicitly specifying any value such as transparent or none, you can do so by writing:

background: initial;

Is there a 'box-shadow-color' property?

Actually… there is! Sort of. box-shadow defaults to color, just like border does.

According to http://dev.w3.org/.../#the-box-shadow

The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.

In practice, you have to change the color property and leave box-shadow without a color:

box-shadow: 1px 2px 3px;
color: #a00;

Support

  • Safari 6+
  • Chrome 20+ (at least)
  • Firefox 13+ (at least)
  • IE9+ (IE8 doesn't support box-shadow at all)

Demo

_x000D_
_x000D_
div {_x000D_
    box-shadow: 0 0 50px;_x000D_
    transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
    color: green;_x000D_
}_x000D_
.red {_x000D_
    color: red;_x000D_
}_x000D_
div:hover {_x000D_
    color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
div {_x000D_
    display: inline-block;_x000D_
    background: white;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    margin: 30px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
_x000D_
_x000D_

The bug mentioned in the comment below has since been fixed :)

Image is not showing in browser?

do not place *jsp or *html in root folder of webapp and images you want to display in same root folder browser cannot acess the image in WEB-INF folder

Adding div element to body or document in JavaScript

Try this out:-

http://jsfiddle.net/adiioo7/vmfbA/

Use

document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

instead of

document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';

Edit:- Ideally you should use body.appendChild method instead of changing the innerHTML

var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

java get file size efficiently

All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.

Looking at result I think File.length() is the winner really.

Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.

---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764

---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652

--- 
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5

Merging 2 branches together in GIT

If you want to merge changes in SubBranch to MainBranch

  1. you should be on MainBranch git checkout MainBranch
  2. then run merge command git merge SubBranch

PuTTY scripting to log onto host

When you use the -m option putty does not allocate a tty, it runs the command and quits. If you want to run an interactive script (such as a sql client), you need to tell it to allocate a tty with -t, see 3.8.3.12 -t and -T: control pseudo-terminal allocation. You'll avoid keeping a script on the server, as well as having to invoke it once you're connected.

Here's what I'm using to connect to mysql from a batch file:

#mysql.bat start putty -t -load "sessionname" -l username -pw password -m c:\mysql.sh

#mysql.sh mysql -h localhost -u username --password="foo" mydb

https://superuser.com/questions/587629/putty-run-a-remote-command-after-login-keep-the-shell-running

Generate PDF from Swagger API documentation

You can modify your REST project, so as to produce the needed static documents (html, pdf etc) upon building the project.

If you have a Java Maven project you can use the pom snippet below. It uses a series of plugins to generate a pdf and an html documentation (of the project's REST resources).

  1. rest-api -> swagger.json : swagger-maven-plugin
  2. swagger.json -> Asciidoc : swagger2markup-maven-plugin
  3. Asciidoc -> PDF : asciidoctor-maven-plugin

Please be aware that the order of execution matters, since the output of one plugin, becomes the input to the next:

<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.3</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>false</springmvc>
                <locations>some.package</locations>
                <basePath>/api</basePath>
                <info>
                    <title>Put your REST service's name here</title>
                    <description>Add some description</description>
                    <version>v1</version>
                </info>
                <swaggerDirectory>${project.build.directory}/api</swaggerDirectory>
                <attachSwaggerArtifact>true</attachSwaggerArtifact>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <!-- fx process-classes phase -->
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>io.github.robwin</groupId>
    <artifactId>swagger2markup-maven-plugin</artifactId>
    <version>0.9.3</version>
    <configuration>
        <inputDirectory>${project.build.directory}/api</inputDirectory>
        <outputDirectory>${generated.asciidoc.directory}</outputDirectory>
        <!-- specify location to place asciidoc files -->
        <markupLanguage>asciidoc</markupLanguage>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-swagger</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <version>1.5.3</version>
    <dependencies>
        <dependency>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoctorj-pdf</artifactId>
            <version>1.5.0-alpha.11</version>
        </dependency>
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby-complete</artifactId>
            <version>1.7.21</version>
        </dependency>
    </dependencies>
    <configuration>
        <sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
        <!-- You will need to create an .adoc file. This is the input to this plugin -->
        <sourceDocumentName>swagger.adoc</sourceDocumentName>
        <attributes>
            <doctype>book</doctype>
            <toc>left</toc>
            <toclevels>2</toclevels>
            <generated>${generated.asciidoc.directory}</generated>
            <!-- this path is referenced in swagger.adoc file. The given file will simply 
                point to the previously create adoc files/assemble them. -->
        </attributes>
    </configuration>
    <executions>
        <execution>
            <id>asciidoc-to-html</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>html5</backend>
                <outputDirectory>${generated.html.directory}</outputDirectory>
                <!-- specify location to place html file -->
            </configuration>
        </execution>
        <execution>
            <id>asciidoc-to-pdf</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>pdf</backend>
                <outputDirectory>${generated.pdf.directory}</outputDirectory>
                <!-- specify location to place pdf file -->
            </configuration>
        </execution>
    </executions>
</plugin>

The asciidoctor plugin assumes the existence of an .adoc file to work on. You can create one that simply collects the ones that were created by the swagger2markup plugin:

include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/definitions.adoc[]

If you want your generated html document to become part of your war file you have to make sure that it is present on the top level - static files in the WEB-INF folder will not be served. You can do this in the maven-war-plugin:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <warSourceDirectory>WebContent</warSourceDirectory>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <webResources>
            <resource>
                <directory>${generated.html.directory}</directory>
            <!-- Add swagger.pdf to WAR file, so as to make it available as static content. -->
            </resource>
            <resource>
                <directory>${generated.pdf.directory}</directory>
            <!-- Add swagger.html to WAR file, so as to make it available as static content. -->
            </resource>
        </webResources>
    </configuration>
</plugin>

The war plugin works on the generated documentation - as such, you must make sure that those plugins have been executed in an earlier phase.

Creating and playing a sound in swift

Swift 4

import UIKit
import AudioToolbox

class ViewController: UIViewController{

var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7]

override func viewDidLoad() {
    super.viewDidLoad()

    for index in 0...sounds.count-1 {
        let fileName : String = "note\(sounds[index])"

        if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") {
            AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index])
        }
    }
}



@IBAction func notePressed(_ sender: UIButton) {
    switch sender.tag {
    case 1:
        AudioServicesPlaySystemSound(sounds[0])
    case 2:
        AudioServicesPlaySystemSound(sounds[1])
    case 3:
        AudioServicesPlaySystemSound(sounds[2])
    case 4:
        AudioServicesPlaySystemSound(sounds[3])
    case 5:
        AudioServicesPlaySystemSound(sounds[4])
    case 6:
        AudioServicesPlaySystemSound(sounds[5])
    default:
        AudioServicesPlaySystemSound(sounds[6])
    }
}
}

or

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate{

var audioPlayer : AVAudioPlayer!

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func notePressed(_ sender: UIButton) {

    let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    }
    catch {
        print(error)
    }

    audioPlayer.play()

}
}

Center Triangle at Bottom of Div

Check this:

http://jsfiddle.net/SxKr5/3/

.hero1
{
    width: 90%;
    height: 200px;
    margin: auto;
    background-color: #e15915;
}

.hero2
{
    width: 0px;
    height: 0px;
    border-style: solid;
    margin: auto;
    border-width: 90px 58px 0 58px;
    border-color: #e15915 transparent transparent transparent;
    line-height: 0px;
    _border-color: #e15915 #000000 #000000 #000000;
    _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000')
}

How can I display a tooltip message on hover using jQuery?

You can do it using just css without using any jQiuery.

<a class="tooltips">
    Hover Me
    <span>My Tooltip Text</span>
</a>
<style>
    a.tooltips {
        position: relative;
        display: inline;
    }

        a.tooltips span {
            position: absolute;
            width: 200px;
            color: #FFFFFF;
            background: #000000;
            height: 30px;
            line-height: 30px;
            text-align: center;
            visibility: hidden;
            border-radius: 6px;
        }

            a.tooltips span:after {
                content: '';
                position: absolute;
                top: 100%;
                left: 35%;
                margin-left: -8px;
                width: 0;
                height: 0;
                border-top: 8px solid #000000;
                border-right: 8px solid transparent;
                border-left: 8px solid transparent;
            }

    a:hover.tooltips span {
        visibility: visible;
        opacity: 0.8;
        bottom: 30px;
        left: 50%;
        margin-left: -76px;
        z-index: 999;
    }
</style>

How to plot data from multiple two column text files with legends in Matplotlib?

This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:

import pylab

datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]

for data, label in datalist:
    pylab.plot( data[:,0], data[:,1], label=label )

pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")

You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

Column name or number of supplied values does not match table definition

I hope you have found a good solution. I had the same problem, and the way I worked around it is probably not the best but it is working now.

it involves creating a linked server and using dynamic sql - not the best, but if anyone can suggest something better, please comment/answer.

declare @sql nvarchar(max)


DECLARE @DB_SPACE TABLE (
[DatabaseName] NVARCHAR(128) NOT NULL,
[FILEID] [smallint] NOT NULL,
[FILE_SIZE_MB] INT NOT NULL DEFAULT (0),
[SPACE_USED_MB] INT NULL DEFAULT (0),
[FREE_SPACE_MB] INT NULL DEFAULT (0),
[LOGICALNAME] SYSNAME NOT NULL,
[DRIVE] NCHAR(1) NOT NULL,
[FILENAME] NVARCHAR(260) NOT NULL,
[FILE_TYPE] NVARCHAR(260) NOT NULL,
[THE_AUTOGROWTH_IN_KB] INT NOT NULL DEFAULT(0)
,filegroup VARCHAR(128)
,maxsize VARCHAR(25)

PRIMARY KEY CLUSTERED ([DatabaseName] ,[FILEID] )
)  


SELECT @SQL ='SELECT [DatabaseName],
        [FILEID],
        [FILE_SIZE_MB],
        [SPACE_USED_MB],
        [FREE_SPACE_MB],
        [LOGICALNAME],
        [DRIVE],
        [FILENAME],
        [FILE_TYPE],
        [THE_AUTOGROWTH_IN_KB]
        ,filegroup
        ,maxsize FROM OPENQUERY('+ QUOTENAME('THE_MONITOR') + ','''+ ' EXEC MASTER.DBO.monitoring_database_details '  +''')'
exec sp_executesql @sql


      INSERT INTO @DB_SPACE(
                            [DatabaseName],
                            [FILEID],
                            [FILE_SIZE_MB],
                            [SPACE_USED_MB],
                            [FREE_SPACE_MB],
                            [LOGICALNAME],
                            [DRIVE],
                            [FILENAME],
                            [FILE_TYPE],
                            THE_AUTOGROWTH_IN_KB,
                            [filegroup],
                            maxsize
                          )

      EXEC SP_EXECUTESQL @SQL

this is working for me now. I can guarantee the number of columns and type of columns returned by the stored procedure are the same as in this table, simply because I return the same table from the stored procedure.

thanks and regards marcelo

Getting title and meta tags from external website

Here is PHP simple DOM HTML Class two line code to get page META details.

$html = file_get_html($link);
$meat_description = $html->find('head meta[name=description]', 0)->content;
$meat_keywords = $html->find('head meta[name=keywords]', 0)->content;

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

adding 30 minutes to datetime php/mysql

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

If one wants to support Generics (in an extension method) this is the pattern...

public  static List<T> Deserialize<T>(this string SerializedJSONString)
{
    var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
    return stuff;
}

It is used like this:

var rc = new MyHttpClient(URL);
//This response is the JSON Array (see posts above)
var response = rc.SendRequest();
var data = response.Deserialize<MyClassType>();

MyClassType looks like this (must match name value pairs of JSON array)

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
 public class MyClassType
 {
    [JsonProperty(PropertyName = "Id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "Manager")]
    public string Manager { get; set; }

    [JsonProperty(PropertyName = "LastUpdate")]
    public DateTime LastUpdate { get; set; }
 }

Use NUGET to download Newtonsoft.Json add a reference where needed...

using Newtonsoft.Json;

How to add anchor tags dynamically to a div in Javascript?

<script type="text/javascript" language="javascript">
function createDiv()
{
  var divTag = document.createElement("div");            
  divTag.innerHTML = "Div tag created using Javascript DOM dynamically";        
  document.body.appendChild(divTag);
}
</script>

Session timeout in ASP.NET

if you are want session timeout for website than remove

<authentication mode="Forms">
      <forms timeout="50"/>
</authentication>

tag from web.config file.

format statement in a string resource file

Quote from Android Docs:

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

How to convert int to NSString?

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

SQL Query to fetch data from the last 30 days?

SELECT productid FROM product WHERE purchase_date > sysdate-30

Pass a string parameter in an onclick function

It looks like you're building DOM elements from strings. You just need to add some quotes around result.name:

'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'

You should really be doing this with proper DOM methods though.

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
    gotoNode(result.name);
});

?document.body.appendChild(inputElement);?

Just be aware that if this is a loop or something, result will change before the event fires and you'd need to create an additional scope bubble to shadow the changing variable.

Generic Interface

I'd stay with two different interfaces.

You said that 'I want to group my service executors under a common interface... It also seems overkill creating two separate interfaces for the two different service calls... A class will only implement one of these interfaces'

It's not clear what is the reason to have a single interface then. If you want to use it as a marker, you can just exploit annotations instead.

Another point is that there is a possible case that your requirements change and method(s) with another signature appears at the interface. Of course it's possible to use Adapter pattern then but it would be rather strange to see that particular class implements interface with, say, three methods where two of them trow UnsupportedOperationException. It's possible that the forth method appears etc.

What's the best practice for primary keys in tables?

I suspect Steven A. Lowe's rolled up newspaper therapy is required for the designer of the original data structure.

As an aside, GUIDs as a primary key can be a performance hog. I wouldn't recommend it.

In a javascript array, how do I get the last 5 elements, excluding the first element?

If you are using lodash, its even simpler with takeRight.

_.takeRight(arr, 5);

Difference of keywords 'typename' and 'class' in templates?

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

Producing a new line in XSLT

You can try,

<xsl:text>&#xA;</xsl:text>

It will work.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

For me the answer of @Dane White is OK, first I did not like using Runnable but I could not find any alternatives.

Here another implementation I preferred more:

public class OptionalConsumer<T> {
    private Optional<T> optional;

    private OptionalConsumer(Optional<T> optional) {
        this.optional = optional;
    }

    public static <T> OptionalConsumer<T> of(Optional<T> optional) {
        return new OptionalConsumer<>(optional);
    }

    public OptionalConsumer<T> ifPresent(Consumer<T> c) {
        optional.ifPresent(c);
        return this;
    }

    public OptionalConsumer<T> ifNotPresent(Runnable r) {
        if (!optional.isPresent()) {
            r.run();
        }
        return this;
    }
}

Then:

Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s -> System.out.println("isPresent " + s))
                .ifNotPresent(() -> System.out.println("! isPresent"));

Update 1:

the above solution for the traditional way of development when you have the value and want to process it but what if I want to define the functionality and the execution will be then, check below enhancement;

public class OptionalConsumer<T> implements Consumer<Optional<T>> {
private final Consumer<T> c;
private final Runnable r;

public OptionalConsumer(Consumer<T> c, Runnable r) {
    super();
    this.c = c;
    this.r = r;
}

public static <T> OptionalConsumer<T> of(Consumer<T> c, Runnable r) {
    return new OptionalConsumer(c, r);
}

@Override
public void accept(Optional<T> t) {
    if (t.isPresent()) {
        c.accept(t.get());
    }
    else {
        r.run();
    }
}

Then could be used as:

Consumer<Optional<Integer>> c = OptionalConsumer.of(
    System.out::println, 
    () -> System.out.println("Not fit")
);

IntStream.range(0, 100)
    .boxed()
    .map(i -> Optional.of(i)
    .filter(j -> j % 2 == 0))
    .forEach(c);

In this new code you have 3 things:

  1. can define the functionality before the existing of an object easy.
  2. not creating object reference for each Optional, only one, you have so less memory than less GC.
  3. it is implementing consumer for better usage with other components.

By the way, now its name is more descriptive it is actually Consumer<Optional<?>>

Pure JavaScript Send POST Data Without a Form

Did you know that JavaScript has it's built-in methods and libs to create forms and submit them?

I am seeing a lot of replies here all asking to use a 3rd party library which I think is an overkill.

I would do the following in pure Javascript:

<script>
function launchMyForm()
{
   var myForm = document.createElement("FORM");
   myForm.setAttribute("id","TestForm");
   document.body.appendChild(myForm);

// this will create a new FORM which is mapped to the Java Object of myForm, with an id of TestForm. Equivalent to: <form id="TestForm"></form>

   var myInput = document.createElement("INPUT");
   myInput.setAttribute("id","MyInput");
   myInput.setAttribute("type","text");
   myInput.setAttribute("value","Heider");
   document.getElementById("TestForm").appendChild(myInput);

// This will create an INPUT equivalent to: <INPUT id="MyInput" type="text" value="Heider" /> and then assign it to be inside the TestForm tags. 
}
</script>

This way (A) you don't need to rely on 3rd parties to do the job. (B) It's all built-in to all browsers, (C) faster, (D) it works, feel free to try it out.

I hope this helps. H

How to run a command in the background and get no output?

Use nohup if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.

Redirect the stdout and stderr to /dev/null to ignore the output.

nohup /path/to/your/script.sh > /dev/null 2>&1 &

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

How do I use JDK 7 on Mac OSX?

The instructions by peter_budo worked perfectly. I had to add the jars under /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home/jre/lib/ to my IntelliJ project libraries. Now it works like a charm. Note that I didn't need my IDE itself to run under 1.7; rather, I only needed to be able to compile and run against 1.7. I'll most likely continue to use Apple's JRE for running the IDE since it's probably more stable with respect to graphics routines (Swing, AWT). Like the OP, I was really keen on testing out the new NIO2 API. Looking good so far. Thanks, Peter.

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

How to display list items on console window in C#

Console.WriteLine(string.Join<TYPE>("\n", someObjectList));