Programs & Examples On #Hypervisor

How to disable Hyper-V in command line?

This command works

Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

Run it then agree to restart the computer when prompted.

I ran it in elevated permissions PowerShell on Windows 10, but it should also work on Win 8 or 7.

How to display a list inline using Twitter's Bootstrap

I couldn't find anything specific within the bootstrap.css file. So, I added the css to a custom css file.

.inline li {
    display: inline;
}

How can I maintain fragment state when added to the back stack?

I guess there is an alternative way to achieve what you are looking for. I don't say its a complete solution but it served the purpose in my case.

What I did is instead of replacing the fragment I just added target fragment. So basically you will be going to use add() method instead replace().

What else I did. I hide my current fragment and also add it to backstack.

Hence it overlaps new fragment over the current fragment without destroying its view.(check that its onDestroyView() method is not being called. Plus adding it to backstate gives me the advantage of resuming the fragment.

Here is the code :

Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();

AFAIK System only calls onCreateView() if the view is destroyed or not created. But here we have saved the view by not removing it from memory. So it will not create a new view.

And when you get back from Destination Fragment it will pop the last FragmentTransaction removing top fragment which will make the topmost(SourceFragment's) view to appear over the screen.

COMMENT: As I said it is not a complete solution as it doesn't remove the view of Source fragment and hence occupying more memory than usual. But still, serve the purpose. Also, we are using a totally different mechanism of hiding view instead of replacing it which is non traditional.

So it's not really for how you maintain the state, but for how you maintain the view.

Reading Email using Pop3 in C#

You can also try Mail.dll mail component, it has SSL support, unicode, and multi-national email support:

using(Pop3 pop3 = new Pop3())
{
    pop3.Connect("mail.host.com");           // Connect to server and login
    pop3.Login("user", "password");

    foreach(string uid in pop3.GetAll())
    {
        IMail email = new MailBuilder()
            .CreateFromEml(pop3.GetMessageByUID(uid));
          Console.WriteLine( email.Subject );
    }
    pop3.Close(false);      
}

You can download it here at https://www.limilabs.com/mail

Please note that this is a commercial product I've created.

How to view data saved in android database(SQLite)?

Try this..

  1. Download the Sqlite Manager jar file here.

  2. Add it to your eclipse > dropins Directory.

  3. Restart eclipse.

  4. Launch the compatible emulator or device

  5. Run your application.

  6. Go to Window > Open Perspective > DDMS >

  7. Choose the running device.

  8. Go to File Explorer tab.

  9. Select the directory called databases under your application's package.

  10. Select the .db file under the database directory.

  11. Then click Sqlite manager icon like this Sqlite manager icon.

  12. Now you're able to see the .db file.

Happy coding.....

Implementing a simple file download servlet

That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect().

If it's not, you'll need to manually copy it to response output stream:

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
    out.write(buffer, 0, length);
}
in.close();
out.flush();

You'll need to handle the appropriate exceptions, of course.

Is it possible to interactively delete matching search pattern in Vim?

http://vim.wikia.com/wiki/Search_and_replace

Try this search and replace:

:%s/foo/bar/gc

Change each 'foo' to 'bar', but ask for confirmation first.

Press y or n to change or keep your text.

@Cacheable key on multiple method arguments

This will work

@Cacheable(value="bookCache", key="#checkwarehouse.toString().append(#isbn.toString())")

Wildcard string comparison in Javascript

var searchArray = function(arr, str){
    // If there are no items in the array, return an empty array
    if(typeof arr === 'undefined' || arr.length === 0) return [];
    // If the string is empty return all items in the array
    if(typeof str === 'undefined' || str.length === 0) return arr;

    // Create a new array to hold the results.
    var res = [];

    // Check where the start (*) is in the string
    var starIndex = str.indexOf('*');

    // If the star is the first character...
    if(starIndex === 0) {

        // Get the string without the star.
        str = str.substr(1);
        for(var i = 0; i < arr.length; i++) {

            // Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
            // It doesn't necessarily mean it IS a string either.
            if(!arr[i].indexOf) continue;

            // Check if the string is at the end of each item.
            if(arr[i].indexOf(str) === arr[i].length - str.length) {                    
                // If it is, add the item to the results.
                res.push(arr[i]);
            }
        }
    }
    // Otherwise, if the star is the last character
    else if(starIndex === str.length - 1) {
        // Get the string without the star.
        str = str.substr(0, str.length - 1);
        for(var i = 0; i < arr.length; i++){
            // Check indexOf function                
            if(!arr[i].indexOf) continue;
            // Check if the string is at the beginning of each item
            if(arr[i].indexOf(str) === 0) {
                // If it is, add the item to the results.
                res.push(arr[i]);
            }
        }
    }
    // In any other case...
    else {            
        for(var i = 0; i < arr.length; i++){
            // Check indexOf function
            if(!arr[i].indexOf) continue;
            // Check if the string is anywhere in each item
            if(arr[i].indexOf(str) !== -1) {
                // If it is, add the item to the results
                res.push(arr[i]);
            }
        }
    }

    // Return the results as a new array.
    return res;
}

var birds = ['bird1','somebird','bird5','bird-big','abird-song'];

var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song

There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.

Fiddle

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is an option that's easier to extend than yours, but no, there is none built into the library itself.

private static List<string> suffixes = new List<string> { " B", " KB", " MB", " GB", " TB", " PB" };
public static string Foo(int number)
{
    for (int i = 0; i < suffixes.Count; i++)
    {
        int temp = number / (int)Math.Pow(1024, i + 1);
        if (temp == 0)
            return (number / (int)Math.Pow(1024, i)) + suffixes[i];
    }
    return number.ToString();
}

How do I find out what version of WordPress is running?

Because I can not comment to @Michelle 's answer, I post my trick here.

Instead of checking the version on meta tag that usually is removed by a customized theme.

Check the rss feed by append /feed to almost any link from that site, then search for some keywords (wordpress, generator), you will have a better chance.

<lastBuildDate>Fri, 29 May 2015 10:08:40 +0000</lastBuildDate>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>http://wordpress.org/?v=4.2.2</generator>

jQuery add class .active on menu

No other "addClass" methods worked for me when adding a class to an 'a' element on menu except this one:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

This took me four hours to find it.

How to detect current state within directive

Also you can use ui-sref-active directive:

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  </li>
  <!-- ... -->
</ul>

Or filters: "stateName" | isState & "stateName" | includedByState

How can I stop a While loop?

just indent your code correctly:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period

You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.

Following your idea to use an infinite loop, this is the best way to write it:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

How to get div height to auto-adjust to background size?

There is a pure CSS solution that the other answers have missed.

The "content:" property is mostly used to insert text content into an element, but can also be used to insert image content.

.my-div:before {
    content: url("image.png");
}

This will cause the div to resize its height to the actual pixel size of the image. To resize the width too, add:

.my-div {
    display: inline-block;
}

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

What is the most efficient way to check if a value exists in a NumPy array?

How about

if value in my_array[:, col_num]:
    do_whatever

Edit: I think __contains__ is implemented in such a way that this is the same as @detly's version

How to get current time and date in Android

SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");


String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
String currentDateandTime = sdf1.format(new Date());     //30.06.09
String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date());     //8:29 PM
String currentDateandTime = sdf5.format(new Date());     //8:29
String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM

Date format Patterns

G   Era designator (before christ, after christ)
y   Year (e.g. 12 or 2012). Use either yy or yyyy.
M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.g. d or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g. 1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone

How can I install Apache Ant on Mac OS X?

MacPorts will install ant for you in MacOSX 10.9. Just use

$ sudo port install apache-ant

and it will install.

Angular 2 - NgFor using numbers instead collections

<div *ngFor="let number of [].constructor(myCollection)">
    <div>
        Hello World
    </div>
</div>

This is a nice and quick way to repeat for the amount of times in myCollection.

So if myCollection was 5, Hello World would be repeated 5 times.

What is the difference between a strongly typed language and a statically typed language?

One does not imply the other. For a language to be statically typed it means that the types of all variables are known or inferred at compile time.

A strongly typed language does not allow you to use one type as another. C is a weakly typed language and is a good example of what strongly typed languages don't allow. In C you can pass a data element of the wrong type and it will not complain. In strongly typed languages you cannot.

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Cannot use Server.MapPath

Try adding System.Web as a reference to your project.

How do I push amended commit to the remote Git repository?

Quick rant: The fact that no one has posted the simple answer here demonstrates the desperate user-hostility exhibited by the Git CLI.

Anyway, the "obvious" way to do this, assuming you haven't tried to force the push, is to pull first. This pulls the change that you amended (and so no longer have) so that you have it again.

Once you have resolved any conflicts, you can push again.

So:

git pull

If you get errors in pull, maybe something is wrong in your local repository configuration (I had a wrong ref in the .git/config branch section).

And after

git push

Maybe you will get an extra commit with the subject telling about a "Trivial merge".

How to convert JSON to a Ruby hash

Have you tried: http://flori.github.com/json/?

Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.

How to show an alert box in PHP?

I don't know about php but i belive the problem is from this :

echo '<script language="javascript>';
echo 'alery("message successfully sent")';
echo '</script>';

Try to change this with :

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

You can use the Logical NOT ! operator:

if (!$(this).parent().next().is('ul')){

Or equivalently (see comments below):

if (! ($(this).parent().next().is('ul'))){

For more information, see the Logical Operators section of the MDN docs.

image.onload event and browser cache

I found that you can just do this in Chrome:

  $('.onload-fadein').each(function (k, v) {
    v.onload = function () {
        $(this).animate({opacity: 1}, 2000);
    };
    v.src = v.src;
});

Setting the .src to itself will trigger the onload event.

How to execute a program or call a system command from Python

A simple way is to use the os module:

import os
os.system('ls')

Alternatively, you can also use the subprocess module:

import subprocess
subprocess.check_call('ls')

If you want the result to be stored in a variable try:

import subprocess
r = subprocess.check_output('ls')

What is the role of the package-lock.json?

One important thing to mention as well is the security improvement that comes with the package-lock file. Since it keeps all the hashes of the packages if someone would tamper with the public npm registry and change the source code of a package without even changing the version of the package itself it would be detected by the package-lock file.

How to assign more memory to docker container

Allocate maximum memory to your docker machine from (docker preference -> advance )

Screenshot of advance settings: Screenshot of advance settings.

This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.

docker run -m=4g {imageID}

Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.

What is the best way to prevent session hijacking?

Use SSL only and instead of encrypting the HTTP_USER_AGENT in the session id and verifying it on every request, just store the HTTP_USER_AGENT string in your session db as well.

Now you only have a simple server based string compare with the ENV'HTTP_USER_AGENT'.

Or you can add a certain variation in your string compare to be more robust against browser version updates. And you could reject certain HTTP_USER_AGENT id's. (empty ones i.e.) Does not resolve the problem completley, but it adds at least a bit more complexity.

Another method could be using more sophisticated browser fingerprinting techniques and combine theyse values with the HTTP_USER_AGENT and send these values from time to time in a separate header values. But than you should encrypt the data in the session id itself.

But that makes it far more complex and raises the CPU usage for decryption on every request.

Trying to handle "back" navigation button action in iOS

Perhaps this answers doesn't fit your explanation but question title. It's useful when you are trying to know when you tapped the back button on an UINavigationBar.

In this case you can use UINavigationBarDelegate protocol and implement one of this methods:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;
- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item;

When didPopItem method is called, it's because you either tapped the back button or you used [UINavigationBar popNavigationItemAnimated:] method and the navigation bar did pop the item.

Now, if you want to know what action triggered the didPopItem method you can use a flag.

With this approach I don't need to manually add a left bar button item with an arrow image in order to make it similar to iOS back button, and be able to set my custom target/action.


Let's see an example:

I have a view controller that has a page view controller, and a custom page indicator view. I'm also using a custom UINavigationBar to display a title to know on what page am I and the back button to go back to the previous page. And I also can swipe to previous/next page on page controller.

#pragma mark - UIPageViewController Delegate Methods
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {

    if( completed ) {

        //...

        if( currentIndex > lastIndex ) {

            UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"Some page title"];

            [[_someViewController navigationBar] pushNavigationItem:navigationItem animated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        } else {
            _autoPop = YES; //We pop the item automatically from code.
            [[_someViewController navigationBar] popNavigationItemAnimated:YES];
            [[_someViewController pageControl] setCurrentPage:currentIndex];
        }
    }

}

So then I implement UINavigationBar delegate methods:

#pragma mark - UINavigationBar Delegate Methods
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if( !_autoPop ) {
        //Pop by back button tap
    } else {
        //Pop from code
    }

    _autoPop = NO;

    return YES;
}

In this case I used shouldPopItem because the pop is animated and I wanted to handle the back button immediately and not to wait until transition is finished.

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

Java Class.cast() vs. cast operator

Personally, I've used this before to build a JSON to POJO converter. In the case that the JSONObject processed with the function contains an array or nested JSONObjects (implying that the data here isn't of a primitive type or String), I attempt to invoke the setter method using class.cast() in this fashion:

public static Object convertResponse(Class<?> clazz, JSONObject readResultObject) {
    ...
    for(Method m : clazz.getMethods()) {
        if(!m.isAnnotationPresent(convertResultIgnore.class) && 
            m.getName().toLowerCase().startsWith("set")) {
        ...
        m.invoke(returnObject,  m.getParameters()[0].getClass().cast(convertResponse(m.getParameters()[0].getType(), readResultObject.getJSONObject(key))));
    }
    ...
}

Not sure if this is extremely helpful, but as said here before, reflection is one of the very few legitimate use case of class.cast() I can think of, at least you have another example now.

Remove border from IFrame

To remove border you can use CSS border property to none.

<iframe src="myURL" width="300" height="300" style="border: none">Browser not compatible.</iframe>

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Getting execute permission to xp_cmdshell

tchester said :

(2) Create a login for the non-sysadmin user that has public access to the master database

I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.

After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"

Yves

Filter dict to contain only certain keys?

We can do simply with lambda function like this:

>>> dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
>>> large_dict = {"a":1,"b":2,"c":3,"d":4}
>>> new_dict_keys = ("c","d")
>>> small_dict=dict_filter(large_dict, new_dict_keys)
>>> print(small_dict)
{'c': 3, 'd': 4}
>>> 

exceeds the list view threshold 5000 items in Sharepoint 2010

You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).

When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.

This article is a good overview: http://office.microsoft.com/en-us/sharepoint-foundation-help/manage-lists-and-libraries-with-many-items-HA010377496.aspx

how to instanceof List<MyType>?

You can use a fake factory to include many methods instead of using instanceof:

public class Message1 implements YourInterface {
   List<YourObject1> list;
   Message1(List<YourObject1> l) {
       list = l;
   }
}

public class Message2 implements YourInterface {
   List<YourObject2> list;
   Message2(List<YourObject2> l) {
       list = l;
   }
}

public class FactoryMessage {
    public static List<YourInterface> getMessage(List<YourObject1> list) {
        return (List<YourInterface>) new Message1(list);
    }
    public static List<YourInterface> getMessage(List<YourObject2> list) {
        return (List<YourInterface>) new Message2(list);
    }
}

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

you just need to run the command as a super user:

just type from the terminal: sudo su mongod

How to split a data frame?

The answer you want depends very much on how and why you want to break up the data frame.

For example, if you want to leave out some variables, you can create new data frames from specific columns of the database. The subscripts in brackets after the data frame refer to row and column numbers. Check out Spoetry for a complete description.

newdf <- mydf[,1:3]

Or, you can choose specific rows.

newdf <- mydf[1:3,]

And these subscripts can also be logical tests, such as choosing rows that contain a particular value, or factors with a desired value.

What do you want to do with the chunks left over? Do you need to perform the same operation on each chunk of the database? Then you'll want to ensure that the subsets of the data frame end up in a convenient object, such as a list, that will help you perform the same command on each chunk of the data frame.

Differences between Emacs and Vim

For me, emacs has better development tools(not only tags based tools).

How to open the default webbrowser using java

As noted in the answer provided by Tim Cooper, java.awt.Desktop has provided this capability since Java version 6 (1.6), but with the following caveat:

Use the isDesktopSupported() method to determine whether the Desktop API is available. On the Solaris Operating System and the Linux platform, this API is dependent on Gnome libraries. If those libraries are unavailable, this method will return false.

For platforms which do not support or provide java.awt.Desktop, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.

Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:

This code is Copyright 1999-2001 by Eric Albert ([email protected]) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.

Credits: Steven Spencer, JavaWorld magazine (Java Tip 66) Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk

Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.

Basic example for sharing text or image with UIActivityViewController in Swift

I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work

//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
     popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
     popoverController.sourceView = self.view
     popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}

That's how it works for me

func shareData(_ dataToShare: [Any]){

        let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)

        //exclude some activity types from the list (optional)
        //activityViewController.excludedActivityTypes = [
            //UIActivity.ActivityType.postToFacebook
        //]

        //avoiding to crash on iPad
        if let popoverController = activityViewController.popoverPresentationController {
            popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
            popoverController.sourceView = self.view
            popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        }

        self.present(activityViewController, animated: true, completion: nil)
    }

Get Current Session Value in JavaScript?

i tested this method and it worked for me. hope its useful.

assuming that you have a file named index.php
and when the user logs in, you store the username in a php session; ex. $_SESSION['username'];

you can do something like this in you index.php file

<script type='text/javascript'>
  var userName = "<?php echo $_SESSION['username'] ?>"; //dont forget to place the PHP code block inside the quotation 
</script>

now you can access the variable userId in another script block placed in the index.php file, or even in a .js file linked to the index.php

ex. in the index.js file

$(document).ready(function(){
    alert(userId);   
})

it could be very useful, since it enables us to use the username and other user data stoerd as cookies in ajax queries, for updating database tables and such.

if you dont want to use a javascript variable to contain the info, you can use an input with "type='hidden';

ex. in your index.php file, write:

<?php echo "<input type='hidden' id='username' value='".$_SESSION['username']."'/>";
?>

however, this way the user can see the hidden input if they ask the browser to show the source code of the page. in the source view, the hidden input is visible with its content. you may find that undesireble.

Reading e-mails from Outlook with Python through MAPI

I have created my own iterator to iterate over Outlook objects via python. The issue is that python tries to iterates starting with Index[0], but outlook expects for first item Index[1]... To make it more Ruby simple, there is below a helper class Oli with following methods:

.items() - yields a tuple(index, Item)...

.prop() - helping to introspect outlook object exposing available properties (methods and attributes)

from win32com.client import constants
from win32com.client.gencache import EnsureDispatch as Dispatch

outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")

class Oli():
    def __init__(self, outlook_object):
        self._obj = outlook_object

    def items(self):
        array_size = self._obj.Count
        for item_index in xrange(1,array_size+1):
            yield (item_index, self._obj[item_index])

    def prop(self):
        return sorted( self._obj._prop_map_get_.keys() )

for inx, folder in Oli(mapi.Folders).items():
    # iterate all Outlook folders (top level)
    print "-"*70
    print folder.Name

    for inx,subfolder in Oli(folder.Folders).items():
        print "(%i)" % inx, subfolder.Name,"=> ", subfolder

How can I jump to class/method definition in Atom text editor?

Check out goto package:

This is a replacement for Atom’s built-in symbols-view package that uses Atom’s own syntax files to identify symbols rather than ctags. The ctags project is very useful but it is never going to keep up with all of the new Atom syntaxes that will be created as Atom grows.

Commands:

  • cmd-r - Goto File Symbol
  • cmd-shift-r - Goto Project Symbol
  • cmd-alt-down - Goto Declaration
  • Rebuild Index
  • Invalidate Index

Link here: https://atom.io/packages/goto (or search "goto" in package installer)

How to format strings using printf() to get equal length in the output

printf allows formatting with width specifiers. For example,

printf( "%-30s %s\n", "Starting initialization...", "Ok." );

You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

difference between css height : 100% vs height : auto

The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

Transparent scrollbar with css

Try this one, it works fine for me.

In CSS:

::-webkit-scrollbar
{
    width: 0px;
}
::-webkit-scrollbar-track-piece
{
    background-color: transparent;
    -webkit-border-radius: 6px;
}

and here is the working demo: https://jsfiddle.net/qpvnecz5/

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

How to remove leading and trailing white spaces from a given html string?

01). If you need to remove only leading and trailing white space use this:

var address = "  No.255 Colombo  "
address.replace(/^[ ]+|[ ]+$/g,'');

this will return string "No.255 Colombo"

02). If you need to remove all the white space use this:

var address = "  No.255 Colombo  "
address.replace(/\s/g,"");

this will return string "No.255Colombo"

Best way to check if an PowerShell Object exist?

I would stick with the $null check since any value other than '' (empty string), 0, $false and $null will pass the check: if ($ie) {...}.

Android new Bottom Navigation bar or BottomNavigationView

You can also use Tab Layout with custom tab view to achieve this.

custom_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?attr/selectableItemBackground"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="10dp"
    android:paddingTop="8dp">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:scaleType="centerInside"
        android:src="@drawable/ic_recents_selector" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAllCaps="false"
        android:textColor="@color/tab_color"
        android:textSize="12sp"/>
</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager

        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        style="@style/AppTabLayout"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private TabLayout mTabLayout;

    private int[] mTabsIcons = {
            R.drawable.ic_recents_selector,
            R.drawable.ic_favorite_selector,
            R.drawable.ic_place_selector};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Setup the viewPager
        ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
        mTabLayout.setupWithViewPager(viewPager);

        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }

        mTabLayout.getTabAt(0).getCustomView().setSelected(true);
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {

        public final int PAGE_COUNT = 3;

        private final String[] mTabsTitle = {"Recents", "Favorites", "Nearby"};

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public View getTabView(int position) {
            // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
            TextView title = (TextView) view.findViewById(R.id.title);
            title.setText(mTabsTitle[position]);
            ImageView icon = (ImageView) view.findViewById(R.id.icon);
            icon.setImageResource(mTabsIcons[position]);
            return view;
        }

        @Override
        public Fragment getItem(int pos) {
            switch (pos) {

                case 0:
                    return PageFragment.newInstance(1);

                case 1:
                    return PageFragment.newInstance(2);
                case 2:
                    return PageFragment.newInstance(3);

            }
            return null;
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTabsTitle[position];
        }
    }

}

Download Complete Sample Project

Python: pandas merge multiple dataframes

Looks like the data has the same columns, so you can:

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

merged_df = pd.concat([df1, df2])

How to install python modules without root access?

Install Python package without Admin rights

import sys

!{sys.executable} -m pip install package_name

Example

import sys

!{sys.executable} -m pip install kivy

Reference: https://docs.python.org/3.4/library/sys.html#sys.executable

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !

component.html

<div *ngFor="let choice of checks; let i=index" class="col-md-2">
  <label>
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
    {{choice.description}}
  </label>
</div>

component.ts

// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),
  }
}

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
}

When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

How to trigger jQuery change event in code

The parameterless form of the change() method triggers a change event. You can write something like:

$(document).ready(function() {
    $("#yourInitialElementID").change(function() {
        // Do something here...
        $(".yourDropDownClass").change();
    });
});

How do I load an HTML page in a <div> using JavaScript?

This is usually needed when you want to include header.php or whatever page.

In Java it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Java function in script tag.

In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php I.e convert the php include function to Java function in script tag and place all your content in that included file.

Warning message: In `...` : invalid factor level, NA generated

If you are reading directly from CSV file then do like this.

myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE)

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Single line sftp from terminal

A minor modification like below worked for me when using it from within perl and system() call:

sftp {user}@{host} <<< $'put {local_file_path} {remote_file_path}'

Making a <button> that's a link in HTML

_x000D_
_x000D_
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
_x000D_
_x000D_

Why are exclamation marks used in Ruby methods?

Called "Destructive Methods" They tend to change the original copy of the object you are referring to.

numbers=[1,0,10,5,8]
numbers.collect{|n| puts n*2} # would multiply each number by two
numbers #returns the same original copy
numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
numbers   # returns [nil,nil,nil,nil,nil]

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Accessing localhost:port from Android emulator

If you are using IIS Express you may need to bind to all hostnames instead of just `localhost'. Check this fine answer:

https://stackoverflow.com/a/15809698/383761

Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file (typically %userprofile%\My Documents\IISExpress\config\applicationhost.config, or $(solutionDir).vs\config\applicationhost.config for Visual Studio 2015), find your site's binding element, and add

<binding protocol="http" bindingInformation="*:8080:*" />

Make sure to add it as a second binding instead of modifying the existing one or VS will just re-add a new site appended with a (1) Also, you may need to run VS as an administrator.

Working copy XXX locked and cleanup failed in SVN

I had this problem because external folders do not want to be linked into an existing folder. If you add an svn:externals property line where the destination is an existing (versioned or non-versioned) folder, you will get the SVN Woring Copy locked error. Here a cleanup will also tell you that everthing is all right but still updating won't work.

Solution: Delete the troubling folder from the repository and make an update in the root folder where the svn:externals property is set. This will create the folder and all will be fine again.

This problem arose for me because svn:externals for files requires the destination folder to be version controlled. After I noticed that this doesn't work across different repositories, I swaped from external files to external folder and got into this mess.

Compiling and Running Java Code in Sublime Text 2

Alex Yao's Answer is the simplest solution, if you just want to build and run Java program w/o taking any input from the console use the solution provided by Alex Yao. However if you would like to take input from the console then refer to the following link

Java console input in Sublime Text 2?

Can I stretch text using CSS?

Technically, no. But what you can do is use a font size that is as tall as you would like the stretched font to be, and then condense it horizontally with font-stretch.

Grant Select on all Tables Owned By Specific User

yes, its possible, run this command:

lets say you have user called thoko

grant select any table, insert any table, delete any table, update any table to thoko;

note: worked on oracle database

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

"sed" command in bash

sed is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.

The s,%,$,g part of the command line is the sed command to execute. The s stands for substitute, the , characters are delimiters (other characters can be used; /, : and @ are popular). The % is the pattern to match (here a literal percent sign) and the $ is the second pattern to match (here a literal dollar sign). The g at the end means to globally replace on each line (otherwise it would only update the first match).

How to pass arguments from command line to gradle

As of Gradle 4.9 Application plugin understands --args option, so passing the arguments is as simple as:

build.gradle

plugins {
    id 'application'
}

mainClassName = "my.App"

src/main/java/my/App.java

public class App {
    public static void main(String[] args) {
        System.out.println(args);
    }
}

bash

./gradlew run --args='This string will be passed into my.App#main arguments'

or in Windows, use double quotes:

gradlew run --args="This string will be passed into my.App#main arguments"

Why do I get a "permission denied" error while installing a gem?

Your Ruby is installed in /usr/local/Cellar/ruby/....

That is a restricted path and can only be written to when you use elevated privileges, either by running as root or by using sudo. I won't recommend you run things as root since you don't understand how paths and permissions work. You can use sudo gem install jekyll, which will temporarily elevate your permissions, giving your command the rights needed to write to that directory.

However, I'd recommend you give serious thought into NOT doing that, and instead use your RVM to install Ruby into your own home directory, where you'll automatically be able to install Rubies and gems without permission issues. See the directions for installing into a local RVM sandbox in "Single-User installations".

Because you have RVM in your ~/.bash_profile, but it doesn't show up in your Gem environment listing, I suspect you either haven't followed the directions for installing RVM correctly, or you haven't used the all-important command:

rvm use 2.0.0 --default

to configure a default Ruby.

For most users, the "Single-User installation" is the way to go. If you have to use sudo with that configuration you've done something wrong.

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

Is there an ignore command for git like there is for svn?

Using the answers already provided, you can roll your own git ignore command using an alias. Either add this to your ~/.gitconfig file:

ignore = !sh -c 'echo $1 >> .gitignore' -

Or run this command from the (*nix) shell of your choice:

git config --global alias.ignore '!sh -c "echo $1 >> .gitignore" -'

You can likewise create a git exclude command by replacing ignore with exclude and .gitignore with .git/info/exclude in the above.

(If you don't already understand the difference between these two files having read the answers here, see this question.)

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Note: This has major security implications.

Open your terminal and run following command:

export GIT_SSL_NO_VERIFY=1

It works for me and I am using Linux system.

System.IO.IOException: file used by another process

Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :

 using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
 { 
   fs.close();
 }
 using (StreamWriter sw = new StreamWriter(@"File.txt")) 
 { 
   sw.WriteLine("bla bla bla"); 
   sw.Close(); 
 } 

phpmailer - The following SMTP Error: Data not accepted

If you are using the Office 365 SMTP gateway then "SMTP Error: data not accepted." is the response you will get if the mailbox is full (even if you are just sending from it).

Try deleting some messages out of the mailbox.

Scanner vs. StringTokenizer vs. String.Split

If you have a String object you want to tokenize, favor using String's split method over a StringTokenizer. If you're parsing text data from a source outside your program, like from a file, or from the user, that's where a Scanner comes in handy.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment here), which is the same thing that hitting CTRL+C would do. Some processes within python handle SIGINTs more abruptly than others.

If you desperately need to stop something that is running in iPython Notebook and you started iPython Notebook from a terminal, you can hit CTRL+C twice in that terminal to interrupt the entire iPython Notebook server. This will stop iPython Notebook alltogether, which means it won't be possible to restart or save your work, so this is obviously not a great solution (you need to hit CTRL+C twice because it's a safety feature so that people don't do it by accident). In case of emergency, however, it generally kills the process more quickly than the "interrupt kernel" button.

IBOutlet and IBAction

Ran into the diagram while looking at key-value coding, thought it might help someone. It helps with understanding of what IBOutlet is.

By looking at the flow, one could see that IBOutlets are only there to match the property name with a control name in the Nib file.

How nib file is loaded, screenshot of Matt's online book for iOS6

Core Data: Quickest way to delete all instances of an entity

Extending Dave Delong's answer.

Swift Version that takes care of iOS 9 and previous versions as well. I have also covered Error handling in this:

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let fetchRequest = NSFetchRequest(entityName: "Car")
    if #available(iOS 9.0, *) {
        let delete = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try appDelegate.persistentStoreCoordinator.executeRequest(delete, withContext: appDelegate.managedObjectContext)
        } catch let error as NSError {
            print("Error occured while deleting: \(error)")
        }
    } else {
        // Fallback on earlier versions
        let carRequest = NSFetchRequest()
        carRequest.entity = NSEntityDescription.entityForName("Cars", inManagedObjectContext: appDelegate.managedObjectContext)
        carRequest.includesPropertyValues = false

        do {
            let cars: NSArray = try appDelegate.managedObjectContext.executeFetchRequest(carRequest)

            for car in cars {
                appDelegate.managedObjectContext.delete(car)
            }

            try appDelegate.managedObjectContext.save()

        } catch let error as NSError {
            print("Error occured while fetching or saving: \(error)")
        }
    }

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

You can first use String.trim(), and then apply the regex replace command on the result.

What's the difference between OpenID and OAuth?

There are three ways to compare OAuth and OpenID:

1. Purposes

OpenID was created for federated authentication, that is, letting a third-party authenticate your users for you, by using accounts they already have. The term federated is critical here because the whole point of OpenID is that any provider can be used (with the exception of white-lists). You don't need to pre-choose or negotiate a deal with the providers to allow users to use any other account they have.

OAuth was created to remove the need for users to share their passwords with third-party applications. It actually started as a way to solve an OpenID problem: if you support OpenID on your site, you can't use HTTP Basic credentials (username and password) to provide an API because the users don't have a password on your site.

The problem is with this separation of OpenID for authentication and OAuth for authorization is that both protocols can accomplish many of the same things. They each provide a different set of features which are desired by different implementations but essentially, they are pretty interchangeable. At their core, both protocols are an assertion verification method (OpenID is limited to the 'this is who I am' assertion, while OAuth provides an 'access token' that can be exchanged for any supported assertion via an API).

2. Features

Both protocols provide a way for a site to redirect a user somewhere else and come back with a verifiable assertion. OpenID provides an identity assertion while OAuth is more generic in the form of an access token which can then be used to "ask the OAuth provider questions". However, they each support different features:

OpenID - the most important feature of OpenID is its discovery process. OpenID does not require hard coding each the providers you want to use ahead of time. Using discovery, the user can choose any third-party provider they want to authenticate. This discovery feature has also caused most of OpenID's problems because the way it is implemented is by using HTTP URIs as identifiers which most web users just don't get. Other features OpenID has is its support for ad-hoc client registration using a DH exchange, immediate mode for optimized end-user experience, and a way to verify assertions without making another round-trip to the provider.

OAuth - the most important feature of OAuth is the access token which provides a long lasting method of making additional requests. Unlike OpenID, OAuth does not end with authentication but provides an access token to gain access to additional resources provided by the same third-party service. However, since OAuth does not support discovery, it requires pre-selecting and hard-coding the providers you decide to use. A user visiting your site cannot use any identifier, only those pre-selected by you. Also, OAuth does not have a concept of identity so using it for login means either adding a custom parameter (as done by Twitter) or making another API call to get the currently "logged in" user.

3. Technical Implementations

The two protocols share a common architecture in using redirection to obtain user authorization. In OAuth the user authorizes access to their protected resources and in OpenID, to their identity. But that's all they share.

Each protocol has a different way of calculating a signature used to verify the authenticity of the request or response, and each has different registration requirements.

How to return a file using Web API?

I made the follow action:

[HttpGet]
[Route("api/DownloadPdfFile/{id}")]
public HttpResponseMessage DownloadPdfFile(long id)
{
    HttpResponseMessage result = null;
    try
    {
        SQL.File file = db.Files.Where(b => b.ID == id).SingleOrDefault();

        if (file == null)
        {
            result = Request.CreateResponse(HttpStatusCode.Gone);
        }
        else
        {
            // sendo file to client
            byte[] bytes = Convert.FromBase64String(file.pdfBase64);


            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(bytes);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = file.name + ".pdf";
        }

        return result;
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.Gone);
    }
}

Which JDK version (Language Level) is required for Android Studio?

Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.

Running an Excel macro via Python?

A variation on SMNALLY's code that doesn't quit Excel if you already have it open:

import os, os.path
import win32com.client
    
if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    wb.Close(False) #close the work sheet object rather than quitting excel
    del wb
    del xl

Combine Regexp?

Doesn't contain @: /(^[^@]*$)/

Combining works if the intended result of combination is that any of them matching results in the whole regexp matching.

How to add images in select list?

I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.

Worket well for me. Hope it can help someone else.

Convert ASCII TO UTF-8 Encoding

Use utf8_encode()

Man page can be found here http://php.net/manual/en/function.utf8-encode.php

Also read this article from Joel on Software. It provides an excellent explanation if what Unicode is and how it works. http://www.joelonsoftware.com/articles/Unicode.html

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

libxml/tree.h no such file or directory

I found that with xCode 4.3.2 I had to enter $(SDKROOT)/usr/include/libxml2 into the Header Search field rather than simply /usr/include/libxml2

Python - Create list with numbers between 2 values?

In python you can do this very eaisly

start=0
end=10
arr=list(range(start,end+1))
output: arr=[0,1,2,3,4,5,6,7,8,9,10]

or you can create a recursive function that returns an array upto a given number:

ar=[]
def diff(start,end):
    if start==end:
        d.append(end)
        return ar
    else:
        ar.append(end)
        return diff(start-1,end) 

output: ar=[10,9,8,7,6,5,4,3,2,1,0]

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

How can I create objects while adding them into a vector?

You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.

If the type Player has a default constructor, you can create a temporary object by doing Player(), and that should work for your case:

vectorOfGamers.push_back(Player());

JAXB Exception: Class not known to this context

I had this error because I registered the wrong class in this line of code:

JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);

How to get duplicate items from a list using LINQ?

  List<String> list = new List<String> { "6", "1", "2", "4", "6", "5", "1" };

    var q = from s in list
            group s by s into g
            where g.Count() > 1
            select g.First();

    foreach (var item in q)
    {
        Console.WriteLine(item);

    }

Uncaught SyntaxError: Unexpected token :

I did Wrong in this

   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`

Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error...

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

Angular CLI: 6.0.8
Node: 10.4.0
OS: linux x64
Angular: 6.0.4

In case there is a feature module (e.g. manager.module.ts inside the e.g. "/manager" sub-folder) with the routing module externalized into the separate NgModule (e.g. manager-routing.module.ts) the error message:

More than one module matches. Use skip-import option to skip importing the component into the closest module.

does not appear and the component is properly generated and added to the manager.module.ts module.

BUT BE CAREFUL the naming convention! the name of the routing module must terminate with "-routing"!

If the routing module is given a name like e.g. manager-router.module.ts, CLI will complain with the error message and expect you to provide --module option to automatically add the component import:

ng generate component some-name --module=manager.module.ts

or

ng generate component some-name --skip-import

if you prefer to add the import of the component manually

How can I quickly delete a line in VIM starting at the cursor position?

D or dd deletes and copies the line to the register. You can use Vx which only deletes the line and stays in the normal mode.

Real world use of JMS/message queues?

We are using JMS for communication with systems in a huge number of remote sites over unreliable networks. The loose coupling in combination with reliable messaging produces a stable system landscape: Each message will be sent as soon it is technically possible, bigger problems in network will not have influence on the whole system landscape...

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

I also tried a very simple app on 10.8 (one button, sets text on a label). It crashed at startup, as Greg Parker stated:

Dyld Error Message:
  Symbol not found: __dispatch_source_type_memorypressure
  Referenced from: /Volumes/*/SwifTest.app/Contents/MacOS/../Frameworks/libswiftDispatch.dylib
  Expected in: /usr/lib/libSystem.B.dylib
in /Volumes/*/SwifTest.app/Contents/MacOS/../Frameworks/libswiftDispatch.dylib

(This was using a deployment target of 10.7)

How to check existence of user-define table type in SQL Server 2008?

You can look in sys.types or use TYPE_ID:

IF TYPE_ID(N'MyType') IS NULL ...

Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.

Can we have functions inside functions in C++?

No, it's not allowed. Neither C nor C++ support this feature by default, however TonyK points out (in the comments) that there are extensions to the GNU C compiler that enable this behavior in C.

Calculating the difference between two Java date instances

public static String getDifferenceBtwTime(Date dateTime) {

    long timeDifferenceMilliseconds = new Date().getTime() - dateTime.getTime();
    long diffSeconds = timeDifferenceMilliseconds / 1000;
    long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
    long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
    long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
    long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
    long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
    long diffYears = (long)(timeDifferenceMilliseconds / (1000 * 60 * 60 * 24 * 365));

    if (diffSeconds < 1) {
        return "one sec ago";
    } else if (diffMinutes < 1) {
        return diffSeconds + " seconds ago";
    } else if (diffHours < 1) {
        return diffMinutes + " minutes ago";
    } else if (diffDays < 1) {
        return diffHours + " hours ago";
    } else if (diffWeeks < 1) {
        return diffDays + " days ago";
    } else if (diffMonths < 1) {
        return diffWeeks + " weeks ago";
    } else if (diffYears < 12) {
        return diffMonths + " months ago";
    } else {
        return diffYears + " years ago";
    }
}   

Finding the layers and layer sizes for each Docker image

It's indeed doable to query the manifest or blob info from docker registry server without pulling the image to local disk.

You can refer to the Registry v2 API to fetch the manifest of image.

GET /v2/<name>/manifests/<reference>

Note, you have to handle different manifest version. For v2 you can directly get the size of layer and digest of blob. For v1 manifest, you can HEAD the blob download url to get the actual layer size.

There is a simple script for handling above cases that will be continuously maintained.

Jersey stopped working with InjectionManagerFactory not found

Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager and InjectionManagerFactory. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory. There are two implementations of this, which are for HK2 and CDI. The HK2 dependency is the jersey-hk2 others are talking about.

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.26</version>
</dependency>

The CDI dependency is

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-cdi2-se</artifactId>
    <version>2.26</version>
</dependency>

This (jersey-cdi2-se) should only be used for SE environments and not EE environments.

Jersey made this change to allow others to provide their own dependency injection framework. They don't have any plans to implement any other InjectionManagers, though others have made attempts at implementing one for Guice.

Difference between binary tree and binary search tree

Binary Tree is a specialized form of tree with two child (left child and right Child). It is simply representation of data in Tree structure

Binary Search Tree (BST) is a special type of Binary Tree that follows following condition:

  1. left child node is smaller than its parent Node
  2. right child node is greater than its parent Node

Get human readable version of file size?

The HumanFriendly project helps with this.

import humanfriendly
humanfriendly.format_size(1024)

The above code will give 1KB as answer.
Examples can be found here.

Checkbox angular material checked by default

// in component.ts
checked: boolean = true;
indeterminate:boolean = false;
disabled:boolean = false;
label:string;

onCheck() {
    this.label = this.checked?'ON':'OFF';
}

// in component.html`enter code here`
<mat-checkbox class="example-margin" [color]="primary" [(ngModel)]="checked" [(indeterminate)]="indeterminate" [labelPosition]="after" [disabled]="disabled" (change)="onCheck()">
                    {{label}}
                  </mat-checkbox>

The above code should work fine. Mat checkbox allows you to make it checked/unchecked, disabled, set indeterminate state, do some operation onChange of the state etc. Refer API for more details.

Int or Number DataType for DataAnnotation validation attribute

public class IsNumericAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            decimal val;
            var isNumeric = decimal.TryParse(value.ToString(), out val);

            if (!isNumeric)
            {                   
                return new ValidationResult("Must be numeric");                    
            }
        }

        return ValidationResult.Success;
    }
}

Creating a constant Dictionary in C#

Why not:

public class MyClass
{
    private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { "A", 1 }, { "B", 2 }, { "C", 3 } };

    public IEnumerable<KeyValuePair<string,int>> MyCollection
    {
        get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }
    }
}

How do I link to part of a page? (hash?)

You use an anchor and a hash. For example:

Target of the Link:

 <a name="name_of_target">Content</a>

Link to the Target:

 <a href="#name_of_target">Link Text</a>

Or, if linking from a different page:

 <a href="http://path/to/page/#name_of_target">Link Text</a>

How to right-align form input boxes?

I answered this question in a blog post: https://wscherphof.wordpress.com/2015/06/17/right-align-form-elements-with-css/ It refers to this fiddle: https://jsfiddle.net/wscherphof/9sfcw4ht/9/

Spoiler: float: right; is the right direction, but it takes just a little more attention to get neat results.

Build project into a JAR automatically in Eclipse

This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.

Check to see if python script is running

The other answers are great for things like cron jobs, but if you're running a daemon you should monitor it with something like daemontools.

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

//In the Application_OnBeginRequest method in GLOBAL.ASX add the following:-  

var res = HttpContext.Current.Response;  
var req = HttpContext.Current.Request;  
res.AppendHeader("Access-Control-Allow-Origin", "*");  
res.AppendHeader("Access-Control-Allow-Credentials", "true");  
res.AppendHeader("Access-Control-Allow-Headers", "Authorization");  
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");  

    // ==== Respond to the OPTIONS verb =====
    if (req.HttpMethod == "OPTIONS")
    {
        res.StatusCode = 200;
        res.End();
    }

//Remove any entries in the custom headers as this will throw an error that there's to  
//many values in the header.  

<httpProtocol>
    <customHeaders>
    </customHeaders>
</httpProtocol>

Which one is the best PDF-API for PHP?

The Zend Framework's Zend_Pdf is really good. It's on par with pdflib in terms of control of output and complexity and is more portable because its a pure php solution. That said, its slower and uses more memory than pdflib. Pecl modules are always more efficient than a php solution.

DOMPdf is the easiest way to make a pdf quickly. Like Mike said, feed it html and it outputs a pdf. Under the hood, it has the option to use either r&ospdf or pdflib as the rendering engine.

Openssl is not recognized as an internal or external command

Well at the place of openssl ... you have to put actually the path to your openssl folder that you have downloaded. Your actual command should look like:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | "C:\Users\abc\openssl\bin\openssl.exe" sha1 -binary | "C:\Users\abc\openssl\bin\openssl.exe" base64

Remember, path that you will enter will be the path where you have installed the openssl...hope this helps..:-)

Edit:

you can download openssl for windows 32 and 64 bit from the respective links below:

OpenSSL for 64 Bits

OpenSSL for 32 Bits

Should I write script in the body or the head of the html?

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

How to try convert a string to a Guid

Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.

Those are:

  • ArgumentNullException
  • FormatException
  • OverflowException

I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

Why aren't programs written in Assembly more often?

As others mentioned before, the reason for any tool to exist is how efficiently it can work. As HLLs can accomplish the same jobs as many lines of asm code I guess it's natural for assembly to be superseded by other languages. And for the close-to-hardware fiddling - there's inline assembly in C and other variants as per language. Dr. Paul Carter in says in the PC Assembly Language

"...a better understanding of how computers really work at a lower level than in programming languages like Pascal. By gaining a deeper understanding of how computers work, the reader can often be much more productive developing software in higher level languages such as C and C++. Learning to program in assembly language is an excellent way to achieve this goal."

We've got introduction to assembly in my college courses. It'll help to clear concepts. However I doubt any of us would write 90% of code in assembly. How relevant is in-depth assembly knowledge today?

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Its work for me

        np_load_old = np.load
        np.load = lambda *a: np_load_old(*a, allow_pickle=True)
        (x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=None, test_split=0.2)
        np.load = np_load_old

Best way to resolve file path too long exception

If you are having an issue with your bin files due to a long path, In Visual Studio 2015 you can go to the offending project's property page and change the relative Output Directory to a shorter one.

E.g. bin\debug\ becomes C:\_bins\MyProject\

Pass variables to Ruby script via command line

You should try console_runner gem. This gem makes your pure Ruby code executable from command-line. All you need is to add YARD annotations to your code:

# @runnable This tool can talk to you. Run it when you are lonely.
#   Written in Ruby.  
class MyClass

    def initialize
      @hello_msg = 'Hello' 
      @bye_msg = 'Good Bye' 
    end

    # @runnable Say 'Hello' to you.
    # @param [String] name Your name
    # @param [Hash] options options
    # @option options [Boolean] :second_meet Have you met before?
    # @option options [String] :prefix Your custom prefix
    def say_hello(name, options = {})
      second_meet = nil
      second_meet = 'Nice to see you again!' if options['second_meet']
      prefix = options['prefix']
      message = @hello_msg + ', '
      message += "#{prefix} " if prefix
      message += "#{name}. "
      message += second_meet if second_meet
      puts message
    end

end

Then run it from console:

$ c_run /projects/example/my_class.rb  say_hello -n John --second-meet --prefix Mr. 
-> Hello, Mr. John. Nice to see you again!

Remove files from Git commit

If you're using GitHub and haven't yet pushed the commit, GitHub Desktop solves this problem easily:

  1. Choose Repository -> Undo Most Recent Commit
  2. Unselect the file that you mistakenly added. Your previous commit message will be in the dialog box already.
  3. Press the Commit button!

java.util.zip.ZipException: error in opening zip file

Make sure your jar file is not corrupted. If it's corrupted or not able to unzip, this error will occur.

jQuery trigger event when click outside the element

function handler(event) {
 var target = $(event.target);
 if (!target.is("div.menuWraper")) {
  alert("outside");
 }
}
$("#myPage").click(handler);

How to create a md5 hash of a string in C?

It would appear that you should

  • Create a struct MD5context and pass it to MD5Init to get it into a proper starting condition
  • Call MD5Update with the context and your data
  • Call MD5Final to get the resulting hash

These three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly.

The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire).

PHP - If variable is not empty, echo some html code

Simply use if ($web). This is true if the variable has any truthy value.

You don't need isset or empty since you know the variable exists, since you have just set it in the previous line.

Parse date without timezone javascript

Just a generic note. a way to keep it flexible.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

We can use getMinutes(), but it return only one number for the first 9 minutes.

_x000D_
_x000D_
let epoch = new Date() // Or any unix timestamp_x000D_
_x000D_
let za = new Date(epoch),_x000D_
    zaR = za.getUTCFullYear(),_x000D_
    zaMth = za.getUTCMonth(),_x000D_
    zaDs = za.getUTCDate(),_x000D_
    zaTm = za.toTimeString().substr(0,5);_x000D_
_x000D_
console.log(zaR +"-" + zaMth + "-" + zaDs, zaTm)
_x000D_
_x000D_
_x000D_

Date.prototype.getDate()
    Returns the day of the month (1-31) for the specified date according to local time.
Date.prototype.getDay()
    Returns the day of the week (0-6) for the specified date according to local time.
Date.prototype.getFullYear()
    Returns the year (4 digits for 4-digit years) of the specified date according to local time.
Date.prototype.getHours()
    Returns the hour (0-23) in the specified date according to local time.
Date.prototype.getMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to local time.
Date.prototype.getMinutes()
    Returns the minutes (0-59) in the specified date according to local time.
Date.prototype.getMonth()
    Returns the month (0-11) in the specified date according to local time.
Date.prototype.getSeconds()
    Returns the seconds (0-59) in the specified date according to local time.
Date.prototype.getTime()
    Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
Date.prototype.getTimezoneOffset()
    Returns the time-zone offset in minutes for the current locale.
Date.prototype.getUTCDate()
    Returns the day (date) of the month (1-31) in the specified date according to universal time.
Date.prototype.getUTCDay()
    Returns the day of the week (0-6) in the specified date according to universal time.
Date.prototype.getUTCFullYear()
    Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
Date.prototype.getUTCHours()
    Returns the hours (0-23) in the specified date according to universal time.
Date.prototype.getUTCMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to universal time.
Date.prototype.getUTCMinutes()
    Returns the minutes (0-59) in the specified date according to universal time.
Date.prototype.getUTCMonth()
    Returns the month (0-11) in the specified date according to universal time.
Date.prototype.getUTCSeconds()
    Returns the seconds (0-59) in the specified date according to universal time.
Date.prototype.getYear()
    Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead. 

Jquery sortable 'change' event element position

If anyone is interested in a sortable list with a changing index per listitem (1st, 2nd, 3th etc...:

http://jsfiddle.net/aph0c1rL/1/

$(".sortable").sortable(
{
  handle:         '.handle'
, placeholder:    'sort-placeholder'
, forcePlaceholderSize: true
, start: function( e, ui )
{
    ui.item.data( 'start-pos', ui.item.index()+1 );
}
, change: function( e, ui )
  {
      var seq
      , startPos = ui.item.data( 'start-pos' )
      , $index
      , correction
      ;

      // if startPos < placeholder pos, we go from top to bottom
      // else startPos > placeholder pos, we go from bottom to top and we need to correct the index with +1
      //
      correction = startPos <= ui.placeholder.index() ? 0 : 1;

      ui.item.parent().find( 'li.prize').each( function( idx, el )
      {
        var $this = $( el )
        , $index = $this.index()
        ;

        // correction 0 means moving top to bottom, correction 1 means bottom to top
        //
        if ( ( $index+1 >= startPos && correction === 0) || ($index+1 <= startPos && correction === 1 ) )
        {
          $index = $index + correction;
          $this.find( '.ordinal-position').text( $index + ordinalSuffix( $index ) );
        }

      });

      // handle dragged item separatelly
      seq = ui.item.parent().find( 'li.sort-placeholder').index() + correction;
      ui.item.find( '.ordinal-position' ).text( seq + ordinalSuffix( seq ) );
} );

// this function adds the correct ordinal suffix to the provide number
function ordinalSuffix( number )
{
  var suffix = '';

  if ( number / 10 % 10 === 1 )
  {
    suffix = "th";
  }
  else if ( number > 0 )
  {

    switch( number % 10 )
    {
      case 1:
        suffix = "st";
        break;
      case 2:
        suffix = "nd";
        break;
      case 3:
        suffix = "rd";
        break;
      default:
        suffix = "th";
        break;
    }
  }
  return suffix;
}

Your markup can look like this:

<ul class="sortable ">
<li >        
    <div>
        <span class="ordinal-position">1st</span>
         A header
    </div>
    <div>
        <span class="icon-button handle"><i class="fa fa-arrows"></i></span>
    </div>
    <div class="bpdy" >
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
</li>
 <li >        
    <div>
        <span class="ordinal-position">2nd</span>
         A header
    </div>
    <div>
        <span class="icon-button handle"><i class="fa fa-arrows"></i></span>
    </div>
    <div class="bpdy" >
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
</li>
etc....
</ul>

How to list files in a directory in a C program?

Here is a complete program how to recursively list folder's contents:

#include <dirent.h> 
#include <stdio.h> 
#include <string.h>

#define NORMAL_COLOR  "\x1B[0m"
#define GREEN  "\x1B[32m"
#define BLUE  "\x1B[34m"



/* let us make a recursive function to print the content of a given folder */

void show_dir_content(char * path)
{
  DIR * d = opendir(path); // open the path
  if(d==NULL) return; // if was not able return
  struct dirent * dir; // for the directory entries
  while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
    {
      if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
        printf("%s%s\n",BLUE, dir->d_name);
      else
      if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
      {
        printf("%s%s\n",GREEN, dir->d_name); // print its name in green
        char d_path[255]; // here I am using sprintf which is safer than strcat
        sprintf(d_path, "%s/%s", path, dir->d_name);
        show_dir_content(d_path); // recall with the new path
      }
    }
    closedir(d); // finally close the directory
}

int main(int argc, char **argv)
{

  printf("%s\n", NORMAL_COLOR);

    show_dir_content(argv[1]);

  printf("%s\n", NORMAL_COLOR);
  return(0);
}

xampp MySQL does not start

If you have previously installed MySQL Workbench the problem is that another MySQL instance is running at 3306 port.

So uninstall MySQL and XAMPP and after that, reinstall only XAMPP.

This worked for me.

Get most recent file in a directory on Linux

Recursively:

find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

How do I add a custom script to my package.json file that runs a javascript file?

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

How to enable C++11 in Qt Creator?

Add this to your .pro file

QMAKE_CXXFLAGS += -std=c++11

or

CONFIG += c++11

django order_by query set, ascending and descending

If for some reason you have null values you can use the F function like this:

from django.db.models import F

Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))

So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values

How to calculate time elapsed in bash script?

Or wrap it up a bit

alias timerstart='starttime=$(date +"%s")'
alias timerstop='echo seconds=$(($(date +"%s")-$starttime))'

Then this works.

timerstart; sleep 2; timerstop
seconds=2

How can I add a line to a file in a shell script?

As far as I understand, you want to prepend column1, column2, column3 to your existing one, two, three.

I would use ed in place of sed, since sed write on the standard output and not in the file.

The command:

printf '0a\ncolumn1, column2, column3\n.\nw\n' | ed testfile.csv

should do the work.

perl -i is worth taking a look as well.

pip installs packages successfully, but executables not found from command line

Solution

Based on other answers, for linux and mac you can run the following:

echo "export PATH=\"`python3 -m site --user-base`/bin:$PATH\"" >> ~/.bashrc
source ~/.bashrc

instead of python3 you can use any other link to python version: python, python2.7, python3.6, python3.9, etc.

Explanation

In order to know where the user packages are installed in the current OS (win, mac, linux), we run:

python3 -m site --user-base

We know that the scripts go to the bin/ folder where the packages are installed.

So we concatenate the paths:

echo `python3 -m site --user-base`/bin

Then we export that to an environment variable.

export PATH=\"`python3 -m site --user-base`/bin:$PATH\"

Finally, in order to avoid repeating the export command we add it to our .bashrc file and we run source to run the new changes, giving us the suggested solution mentioned at the beginning.

using javascript to detect whether the url exists before display in iframe

Due to my low reputation I couldn't comment on Derek ????'s answer. I've tried that code as it is and it didn't work well. There are three issues on Derek ????'s code.

  1. The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.

  2. The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:

    • Remove the quotes that surrounds 404, making it an integer;
    • Use the javascript's operator '==' so you will be testing if the two objects are similar.
  3. The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax

The code that really worked for me was:

var request;
if(window.XMLHttpRequest)
    request = new XMLHttpRequest();
else
    request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
    alert("The page you are trying to reach is not available.");
}

SQL Query with Join, Count and Where

I have used sub-query and it worked great!

SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories

Order columns through Bootstrap4

even this will work:

<div class="container">
            <div class="row">
                <div class="col-4 col-sm-4 col-md-6 order-1">
                    1
                </div>
                <div class="col-4 col-sm-4  col-md-6 order-3">
                    2
                </div>
                <div class="col-4 col-sm-4  col-md-12 order-2">
                    3
                </div>
            </div>
          </div>

Javascript Array of Functions

I have many problems trying to solve this one... tried the obvious, but did not work. It just append an empty function somehow.

array_of_functions.push(function() { first_function('a string') });

I solved it by using an array of strings, and later with eval:

array_of_functions.push("first_function('a string')");

for (var Func of array_of_functions) {
   eval(Func);
   }

Removing cordova plugins from the project

I do it with this python one-liner:

python -c "import subprocess as sp;[sp.call('cordova plugin rm ' + p.split()[0], shell=True) for p in sp.check_output('cordova plugin', shell=True).split('\n') if p]"

Obviously it doesn't handle any sort of error conditions, but it gets the job done.

How do I dynamically change the content in an iframe using jquery?

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

JSON: why are forward slashes escaped?

The JSON spec says you CAN escape forward slash, but you don't have to.

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

Center Align on a Absolutely Positioned Div

_x000D_
_x000D_
.contentBlock {_x000D_
    width: {define width}_x000D_
    width: 400px;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
 _x000D_
}
_x000D_
_x000D_
_x000D_

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

Simple Remove Your Jar file from dependencies gardle.project as v7 and run your project

jquery select option click handler

you can attach a focus event to select

$('#select_id').focus(function() {
    console.log('Handler for .focus() called.');
});

Java string to date conversion

Simple two formatters we have used:

  1. Which format date do we want?
  2. Which format date is actually present?

We parse the full date to time format:

date="2016-05-06 16:40:32";

public static String setDateParsing(String date) throws ParseException {

    // This is the format date we want
    DateFormat mSDF = new SimpleDateFormat("hh:mm a");

    // This format date is actually present
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm");
    return mSDF.format(formatter.parse(date));
}

Finding duplicate rows in SQL Server

i think i know what you need i needed to mix between the answers and i think i got the solution he wanted:

select o.id,o.orgName, oc.dupeCount, oc.id,oc.orgName
from organizations o
inner join (
    SELECT MAX(id) as id, orgName, COUNT(*) AS dupeCount
    FROM organizations
    GROUP BY orgName
    HAVING COUNT(*) > 1
) oc on o.orgName = oc.orgName

having the max id will give you the id of the dublicate and the one of the original which is what he asked for:

id org name , dublicate count (missing out in this case) 
id doublicate org name , doub count (missing out again because does not help in this case)

only sad thing you get it put out in this form

id , name , dubid , name

hope it still helps

writing to serial port from linux command line

echo '\x12\x02'

will not be interpreted, and will literally write the string \x12\x02 (and append a newline) to the specified serial port. Instead use

echo -n ^R^B

which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.

The stty command should work, unless another program is interfering. A common culprit is gpsd which looks for GPS devices being plugged in.

how to make a countdown timer in java

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}

Try this.

How to put labels over geom_bar in R with ggplot2

To plot text on a ggplot you use the geom_text. But I find it helpful to summarise the data first using ddply

dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)

Since the data is pre-summarized, you need to remember to change add the stat="identity" parameter to geom_bar:

ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
    geom_text(aes(label=y), vjust=0) +
    opts(axis.text.x=theme_blank(),
        axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),
        legend.title=theme_blank(),
        axis.title.y=theme_blank()
)

enter image description here

How to set connection timeout with OkHttp

You can set a call timeout to cover the entire cycle from resolving DNS, connecting, writing the request body, server processing, and reading the response body.

val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()

C# - Simplest way to remove first occurrence of a substring from another string

Wrote a quick TDD Test for this

    [TestMethod]
    public void Test()
    {
        var input = @"ProjectName\Iteration\Release1\Iteration1";
        var pattern = @"\\Iteration";

        var rgx = new Regex(pattern);
        var result = rgx.Replace(input, "", 1);

        Assert.IsTrue(result.Equals(@"ProjectName\Release1\Iteration1"));
    }

rgx.Replace(input, "", 1); says to look in input for anything matching the pattern, with "", 1 time.

How to delete the top 1000 rows from a table using Sql Server 2008?

I agree with the Hamed elahi and Glorfindel.

My suggestion to add is you can delete and update using aliases

/* 
  given a table bi_customer_actions
  with a field bca_delete_flag of tinyint or bit
    and a field bca_add_date of datetime

  note: the *if 1=1* structure allows me to fold them and turn them on and off
 */
declare
        @Nrows int = 1000

if 1=1 /* testing the inner select */
begin
  select top (@Nrows) * 
    from bi_customer_actions
    where bca_delete_flag = 1
    order by bca_add_date
end

if 1=1 /* delete or update or select */
begin
  --select bca.*
  --update bca  set bca_delete_flag = 0
  delete bca
    from (
      select top (@Nrows) * 
        from bi_customer_actions
        where bca_delete_flag = 1
        order by bca_add_date
    ) as bca
end 

A cron job for rails: best practices?

I've used the extremely popular Whenever on projects that rely heavily on scheduled tasks, and it's great. It gives you a nice DSL to define your scheduled tasks instead of having to deal with crontab format. From the README:

Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.

Example from the README:

every 3.hours do
  runner "MyModel.some_process"       
  rake "my:rake:task"                 
  command "/usr/bin/my_great_command"
end

every 1.day, :at => '4:30 am' do 
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this is not an answer, but I'd like to contribute to this matter for what it's worth. It would be great if they could release justify-self for flexbox to make it truly flexible.

It's my belief that when there are multiple items on the axis, the most logical way for justify-self to behave is to align itself to its nearest neighbours (or edge) as demonstrated below.

I truly hope, W3C takes notice of this and will at least consider it. =)

enter image description here

This way you can have an item that is truly centered regardless of the size of the left and right box. When one of the boxes reaches the point of the center box it will simply push it until there is no more space to distribute.

enter image description here

The ease of making awesome layouts are endless, take a look at this "complex" example.

enter image description here

Trigger an event on `click` and `enter`

You call both event listeners using .on() then use a if inside the function:

$(function(){
  $('#searchButton').on('keypress click', function(e){
    var search = $('#usersSearch').val();
    if (e.which === 13 || e.type === 'click') {
      $.post('../searchusers.php', {search: search}, function (response) {
        $('#userSearchResultsTable').html(response);
      });
    }
  });
});

Where does Android app package gets installed on phone

The package it-self is located under /data/app/com.company.appname-xxx.apk.

/data/app/com.company.appname is only a directory created to store files like native libs, cache, ecc...

You can retrieve the package installation path with the Context.getPackageCodePath() function call.

Can you use @Autowired with static fields?

You can use ApplicationContextAware

@Component
public class AppContext implements ApplicationContextAware{
    public static ApplicationContext applicationContext;

    public AppBeans(){
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

then

static ABean bean = AppContext.applicationContext.getBean("aBean",ABean.class);

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

Printing variables in Python 3.4

Try the format syntax:

print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))

Outputs:

1. b appears 3.1415 times.

The print function is called just like any other function, with parenthesis around all its arguments.

how to add css class to html generic control div?

If you're going to be repeating this, might as well have an extension method:

// appends a string class to the html controls class attribute
public static void AddClass(this HtmlControl control, string newClass)
{
    if (control.Attributes["class"].IsNotNullAndNotEmpty())
    {
        control.Attributes["class"] += " " + newClass;
    }
    else
    {
        control.Attributes["class"] = newClass;
    }
}

How do you get a directory listing sorted by creation date in python?

Turns out os.listdir sorts by last modified but in reverse so you can do:

import os
last_modified=os.listdir()[::-1]

How to create a private class method?

By default all class methods are public. To make them private you can use Module#private_class_method like @tjwallace wrote or define them differently, as you did:

class << self

  private

  def method_name
    ...
  end
end

class << self opens up self's singleton class, so that methods can be redefined for the current self object. This is used to define class/module ("static") method. Only there, defining private methods really gives you private class methods.

How do I execute code AFTER a form has loaded?

First time it WILL NOT start "AfterLoading",
It will just register it to start NEXT Load.

private void Main_Load(object sender, System.EventArgs e)
{
    //Register it to Start in Load 
    //Starting from the Next time.
    this.Activated += AfterLoading;
}

private void AfterLoading(object sender, EventArgs e)
{
    this.Activated -= AfterLoading;
    //Write your code here.
}

Creating a file name as a timestamp in a batch job

Maybe this can help:

echo off
@prompt set date=$d$_ set time=$t$h$h$h
echo some log >> %date% %time%.log
exit

or

echo off
set v=%date%.log
echo some log >> %v%

How do I write JSON data to a file?

Writing JSON to a File

import json

data = {}
data['people'] = []
data['people'].append({
    'name': 'Scott',
    'website': 'stackabuse.com',
    'from': 'Nebraska'
})
data['people'].append({
    'name': 'Larry',
    'website': 'google.com',
    'from': 'Michigan'
})
data['people'].append({
    'name': 'Tim',
    'website': 'apple.com',
    'from': 'Alabama'
})

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

Reading JSON from a File

import json

with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
        print('Name: ' + p['name'])
        print('Website: ' + p['website'])
        print('From: ' + p['from'])
        print('')

What is the argument for printf that formats a long?

I think to answer this question definitively would require knowing the compiler name and version that you are using and the platform (CPU type, OS etc.) that it is compiling for.

Select count(*) from multiple tables

For a bit of completeness - this query will create a query to give you a count of all of the tables for a given owner.

select 
  DECODE(rownum, 1, '', ' UNION ALL ') || 
  'SELECT ''' || table_name || ''' AS TABLE_NAME, COUNT(*) ' ||
  ' FROM ' || table_name  as query_string 
 from all_tables 
where owner = :owner;

The output is something like

SELECT 'TAB1' AS TABLE_NAME, COUNT(*) FROM TAB1
 UNION ALL SELECT 'TAB2' AS TABLE_NAME, COUNT(*) FROM TAB2
 UNION ALL SELECT 'TAB3' AS TABLE_NAME, COUNT(*) FROM TAB3
 UNION ALL SELECT 'TAB4' AS TABLE_NAME, COUNT(*) FROM TAB4

Which you can then run to get your counts. It's just a handy script to have around sometimes.

How to test if a double is zero?

In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

enum Values to NSString (iOS)

I didn't like putting the enum on the heap, without providing a heap function for translation. Here's what I came up with:

typedef enum {value1, value2, value3} myValue;
#define myValueString(enum) [@[@"value1",@"value2",@"value3"] objectAtIndex:enum]

This keeps the enum and string declarations close together for easy updating when needed.

Now, anywhere in the code, you can use the enum/macro like this:

myValue aVal = value2;
NSLog(@"The enum value is '%@'.", myValueString(aVal));

outputs: The enum value is 'value2'.

To guarantee the element indexes, you can always explicitly declare the start(or all) enum values.

enum {value1=0, value2=1, value3=2};

Setting cursor at the end of any text of a textbox

There are multiple options:

txtBox.Focus();
txtBox.SelectionStart = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.CaretIndex = txtBox.Text.Length;

OR

txtBox.Focus();
txtBox.Select(txtBox.Text.Length, 0);

How do I sort a dictionary by value?

You can also use custom function that can be passed to key.

def dict_val(x):
    return x[1]
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=dict_val)

How do I serialize a C# anonymous type to a JSON string?

You can try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContract's, Any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

Basic Example

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

How to do a non-greedy match in grep?

The short answer is using the next regular expression:

(?s)<car .*? model=BMW .*?>.*?</car>
  • (?s) - this makes a match across multiline
  • .*? - matches any character, a number of times in a lazy way (minimal match)

A (little) more complicated answer is:

(?s)<([a-z\-_0-9]+?) .*? model=BMW .*?>.*?</\1>

This will makes possible to match car1 and car2 in the following text

<car1 ... model=BMW ...>
...
...
...
</car1>
<car2 ... model=BMW ...>
...
...
...
</car2>
  • (..) represents a capturing group
  • \1 in this context matches the sametext as most recently matched by capturing group number 1

Possible cases for Javascript error: "Expected identifier, string or number"

Here is a easy technique to debug the problem: echo out the script/code to the console. Copy the code from the console into your IDE. Most IDE's perform error checking on the code and highlight errors. You should be able to see the error almost immediately in your JavaScript/HTML editor.

Python: Assign Value if None Exists

If you mean a variable at the module level then you can use "globals":

if "var1" not in globals():
    var1 = 4

but the common Python idiom is to initialize it to say None (assuming that it's not an acceptable value) and then testing with if var1 is not None.

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

simple code with LINQ

string s = "abc"
byte[] b = s.Select(e => (byte)e).ToArray();

EDIT : as commented below, it is not a good way.

but you can still use it to understand LINQ with a more appropriate coding :

string s = "abc"
byte[] b = s.Cast<byte>().ToArray();

What's the difference between import java.util.*; and import java.util.Date; ?

Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

installing JDK8 on Windows XP - advapi32.dll error

Oracle has announced fix for Windows XP installation error

Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.

However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.

See the Oracle blog post here.

You can get the latest JRE8 right off the Oracle downloads site.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

How to get TimeZone from android mobile?

Try this code-

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

It will return user selected timezone.