Programs & Examples On #Nsuinteger

How to force view controller orientation in iOS 8?

The combination of Sids and Koreys answers worked for me.

Extending the Navigation Controller:

extension UINavigationController {
    public override func shouldAutorotate() -> Bool {
        return visibleViewController.shouldAutorotate()
    }
}

Then disabling rotation on the single View

class ViewController: UIViewController {
    override func shouldAutorotate() -> Bool {
        return false
    }
}

And rotating to the appropriate orientation before the segue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "SomeSegue")
    {
        let value = UIInterfaceOrientation.Portrait.rawValue;
        UIDevice.currentDevice().setValue(value, forKey: "orientation")
    }
}

How to validate an e-mail address in swift?

There are a lot of right answers here, but many of the "regex" are incomplete and it can happen that an email like: "name@domain" results a valid email, but it is not. Here the complete solution:

extension String {

    var isEmailValid: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .CaseInsensitive)
            return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
        } catch {
            return false
        }
    }
}

tap gesture recognizer - which object was tapped?

Its been a year asking this question but still for someone.

While declaring the UITapGestureRecognizer on a particular view assign the tag as

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandlerMethod:)];
[yourGestureEnableView addGestureRecognizer:tapRecognizer];
yourGestureEnableView.tag=2;

and in your handler do like this

-(void)gestureHandlerMethod:(UITapGestureRecognizer*)sender {
    if(sender.view.tag == 2) {
        // do something here
    }
}

How do I programmatically set device orientation in iOS 7?

I was in a similar problem than you. I need to lock device orientation for some screens (like Login) and allow rotation in others.

After a few changes and following some answers below I did it by:

  • Enabling all the orientations in the Project's Info.plist.

enter image description here

  • Disabling orientation in those ViewControllers where I need the device not to rotate, like in the Login screen in my case. I needed to override shouldAutorotate method in this VC:

-(BOOL)shouldAutorotate{ return NO; }

Hope this will work for you.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

The count method of NSArray returns an NSUInteger, and on the 64-bit OS X platform

  • NSUInteger is defined as unsigned long, and
  • unsigned long is a 64-bit unsigned integer.
  • int is a 32-bit integer.

So int is a "smaller" datatype than NSUInteger, therefore the compiler warning.

See also NSUInteger in the "Foundation Data Types Reference":

When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.

To fix that compiler warning, you can either declare the local count variable as

NSUInteger count;

or (if you are sure that your array will never contain more than 2^31-1 elements!), add an explicit cast:

int count = (int)[myColors count];

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

Assign a variable inside a Block to a variable outside a Block

Just use the __block prefix to declare and assign any type of variable inside a block.

For example:

__block Person *aPerson = nil;

__block NSString *name = nil;

When to use NSInteger vs. int

You should use NSIntegers if you need to compare them against constant values such as NSNotFound or NSIntegerMax, as these values will differ on 32-bit and 64-bit systems, so index values, counts and the like: use NSInteger or NSUInteger.

It doesn't hurt to use NSInteger in most circumstances, excepting that it takes up twice as much memory. The memory impact is very small, but if you have a huge amount of numbers floating around at any one time, it might make a difference to use ints.

If you DO use NSInteger or NSUInteger, you will want to cast them into long integers or unsigned long integers when using format strings, as new Xcode feature returns a warning if you try and log out an NSInteger as if it had a known length. You should similarly be careful when sending them to variables or arguments that are typed as ints, since you may lose some precision in the process.

On the whole, if you're not expecting to have hundreds of thousands of them in memory at once, it's easier to use NSInteger than constantly worry about the difference between the two.

How to do a LIKE query with linq?

String [] obj = (from c in db.Contacts
                           where c.FirstName.StartsWith(prefixText)
                           select c.FirstName).ToArray();
            return obj;

StartsWith() and EndsWith() can help you a lot here. If you want to find data in between the field, then Contains() can be used.

How to dynamically change header based on AngularJS partial view?

Note that you can also set the title directly with javascript, i.e.,

$window.document.title = someTitleYouCreated;

This does not have data binding, but it suffices when putting ng-app in the <html> tag is problematic. (For example, using JSP templates where <head> is defined in exactly one place, yet you have more than one app.)

inline if statement java, why is not working

Syntax is Shown below:

"your condition"? "step if true":"step if condition fails"

Export to xls using angularjs

When I needed something alike, ng-csv and other solutions here didn't completely help. My data was in $scope and there were no tables showing it. So, I built a directive to export given data to Excel using Sheet.js (xslsx.js) and FileSaver.js.

Here is my solution packed.

For example, the data is:

$scope.jsonToExport = [
    {
      "col1data": "1",
      "col2data": "Fight Club",
      "col3data": "Brad Pitt"
    },
    {
      "col1data": "2",
      "col2data": "Matrix Series",
      "col3data": "Keanu Reeves"
    },
    {
      "col1data": "3",
      "col2data": "V for Vendetta",
      "col3data": "Hugo Weaving"
    }
];

I had to prepare data as array of arrays for my directive in my controller:

$scope.exportData = [];
// Headers:
$scope.exportData.push(["#", "Movie", "Actor"]);
// Data:
angular.forEach($scope.jsonToExport, function(value, key) {
  $scope.exportData.push([value.col1data, value.col2data, value.col3data]);
});

Finally, add directive to my template. It shows a button. (See the fiddle).

<div excel-export export-data="exportData" file-name="{{fileName}}"></div>

PHP PDO with foreach and fetch

foreach over a statement is just a syntax sugar for the regular one-way fetch() loop. If you want to loop over your data more than once, select it as a regular array first

$sql = "SELECT * FROM users";
$stm = $dbh->query($sql);
// here you go:
$users = $stm->fetchAll();

foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Also quit that try..catch thing. Don't use it, but set the proper error reporting for PHP and PDO

"Error: Main method not found in class MyClass, please define the main method as..."

I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a

java.lang.NoSuchMethodError: No virtual method

How do I test if a variable does not equal either of two values?

I do that using jQuery

if ( 0 > $.inArray( test, [a,b] ) ) { ... }

How to remove "href" with Jquery?

Your title question and your example are completely different. I'll start by answering the title question:

$("a").removeAttr("href");

And as far as not requiring an href, the generally accepted way of doing this is:

<a href"#" onclick="doWork(); return false;">link</a>

The return false is necessary so that the href doesn't actually go anywhere.

Compare cell contents against string in Excel

You can use the EXACT Function for exact string comparisons.

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

How to center a label text in WPF?

use the HorizontalContentAlignment property.

Sample

<Label HorizontalContentAlignment="Center"/>

Why do people write #!/usr/bin/env python on the first line of a Python script?

You can try this issue using virtualenv

Here is test.py

#! /usr/bin/env python
import sys
print(sys.version)

Create virtual environments

virtualenv test2.6 -p /usr/bin/python2.6
virtualenv test2.7 -p /usr/bin/python2.7

activate each environment then check the differences

echo $PATH
./test.py

java.lang.IllegalArgumentException: View not attached to window manager

@Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (progressDialog != null && progressDialog.isShowing()) {
                Log.i(TAG, "onPostexucte");
                progressDialog.dismiss();
}
}

Reducing the gap between a bullet and text in a list item

ul li:before {
    content: "";
    margin-left: "your negative value";
}

Difference between iCalendar (.ics) and the vCalendar (.vcs)

The VCS files can have its information coded in Quoted printable which is a nightmare. The above solution recommending "VCS to ICS Calendar Converter" is the way to go.

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

How do I show/hide a UIBarButtonItem?

I know this answer is late for this question. However, it might help if anybody else faces a similar situation.

In iOS 7, to hide a bar button item, we can use the following two techniques :-

  • use SetTitleTextAttributes :- This works great on bar button items like "Done", "Save" etc. However, it does not work on items like Add, Trash symbol etc.(atleast not for me) since they are not texts.
  • use TintColor :- If I have a bar button item called "deleteButton" :-

To hide the button, I used the following code:-

[self.deleteButton setEnabled:NO]; 
[self.deleteButton setTintColor: [UIColor clearColor]];

To show the button again I used the following code:-

[self.deleteButton setEnabled:YES];
[self.deleteButton setTintColor:nil];

Lumen: get URL parameter in a Blade view

This works fine for me:

{{ app('request')->input('a') }}

Ex: to get pagination param on blade view:

{{ app('request')->input('page') }}

SQLException : String or binary data would be truncated

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in that case: you specify transaction_status varchar(10) but you actually trying to store _transaction_status which contain 19 characters. that's why you faced this type of error in this code

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

How to save a figure in MATLAB from the command line?

These days (May 2017), MATLAB still suffer from a robust method to export figures, especially in GNU/Linux systems when exporting figures in batch mode. The best option is to use the extension export_fig

Just download the source code from Github and use it:

plot(cos(linspace(0, 7, 1000)));
set(gcf, 'Position', [100 100 150 150]);
export_fig test2.png

R solve:system is exactly singular

I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Android- create JSON Array and JSON Object

It's too late to answer, sorry about it, for creating the below body:

{
    "username": "?Rajab",
    "email": "[email protected]",
    "phone": "+93767626554",
    "password": "123asd",
    "carType": "600fdcc646bc6409ae97e2ab",
    "fcmToken":"lljlkdsajfljasldfj;lsa",
    "profilePhoto": "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg",
    "documents": {
        "DL": [
            {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
        "Registration": [
            {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
        "Insurance":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
         "CarInside":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ],
         "CarOutside":[
              {
                "_id": "5fccb687c5b4260011810125",
                "uriPath": "https://webfume-onionai.s3.amazonaws.com/guest/public/document/326634-beats_by_dre-wallpaper-1366x768.jpg"
            }
        ]
    }
}

You can create dynamically like the below code:

JSONObject jsonBody = new JSONObject();
try {
    jsonBody.put("username", userName);
    jsonBody.put("email", email);
    jsonBody.put("phone", contactNumber);
    jsonBody.put("password", password);
    jsonBody.put("carType", carType);
    jsonBody.put("fcmToken", "lljlkdsajfljasldfj;lsa");
    jsonBody.put("profilePhoto", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg");

    JSONObject document = new JSONObject();

    try {
        document.put("DL", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Registration", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("Insurance", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarInside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
        document.put("CarOutside", createDocument("5fccb687c5b4260011810125", "https://st.depositphotos.com/2101611/3925/v/600/depositphotos_39258143-stock-illustration-businessman-avatar-profile-picture.jpg"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    jsonBody.put("documents", document.toString());

    Log.i("MAHDI", "Hello: Mahdi: Data: " + jsonBody);
} catch (JSONException e) {
    e.printStackTrace();
}

And the createDocument method code:

public JSONArray createDocument(String id, String imageUrl) {

JSONObject dlObject = new JSONObject();
try {
    dlObject.put("_id", id);
    dlObject.put("uriPath", imageUrl);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
JSONArray dlArray = new JSONArray();
dlArray.put(dlObject);

return dlArray;
}

Safely remove migration In Laravel

 php artisan migrate:fresh

Should do the job, if you are in development and the desired outcome is to start all over.

In production, that maybe not the desired thing, so you should be adverted. (The migrate:fresh command will drop all tables from the database and then execute the migrate command).

How can I add an item to a IEnumerable<T> collection?

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:

IEnumerable<string> ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}

IEnumerable<string> lines = ReadLines();
lines.Add("foo") // so what is this supposed to do??

What you can do, however, is create a new IEnumerable object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat for that:

 items = items.Concat(new[] { "foo" });

This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).

How to pass parameters on onChange of html select

This worked for me onchange = setLocation($(this).val())

Here.

    @Html.DropDownList("Demo", 
new SelectList(ViewBag.locs, "Value", "Text"), 
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });

Sort a list of tuples by 2nd item (integer value)

Adding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)

Bootstrap: add margin/padding space between columns

For the more curious, I have also found that adding

border: 5px solid white

or any other variant of your liking, to make it blend in, works superbly.

Fastest method to escape HTML tags as HTML entities?

I'm not entirely sure about speed, but if you are looking for simplicity I would suggest using the lodash/underscore escape function.

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

Generate a random date between two other dates

from random import randrange
from datetime import timedelta

def random_date(start, end):
    """
    This function will return a random datetime between two datetime 
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last line's calculation.

example run:

from datetime import datetime

d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))

output:

2008-12-04 01:50:17

What exactly is Python's file.flush() doing?

Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

Replace "\\" with "\" in a string in C#

I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.

If print it out in the console, or in a message box, does it show with two backslashes or one?

If you actually want to replace a double backslash with a single one, it's easy to do so:

text = text.Replace(@"\\", @"\");

... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.

EDIT: In response to the edited question, your stringToBeReplaced only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length and count the characters.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

MVC 3: How to render a view without its layout page when loaded via ajax?

In ~/Views/ViewStart.cshtml:

@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

and in the controller:

public ActionResult Index()
{
    return View();
}

Concatenating Matrices in R

Sounds like you're looking for rbind:

> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30  5

Similarly, cbind stacks the matrices horizontally.

I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")

Format date with Moment.js

moment().format();                                // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA");                       // "Mon, 5PM"

Getting individual colors from a color map in matplotlib

I had precisely this problem, but I needed sequential plots to have highly contrasting color. I was also doing plots with a common sub-plot containing reference data, so I wanted the color sequence to be consistently repeatable.

I initially tried simply generating colors randomly, reseeding the RNG before each plot. This worked OK (commented-out in code below), but could generate nearly indistinguishable colors. I wanted highly contrasting colors, ideally sampled from a colormap containing all colors.

I could have as many as 31 data series in a single plot, so I chopped the colormap into that many steps. Then I walked the steps in an order that ensured I wouldn't return to the neighborhood of a given color very soon.

My data is in a highly irregular time series, so I wanted to see the points and the lines, with the point having the 'opposite' color of the line.

Given all the above, it was easiest to generate a dictionary with the relevant parameters for plotting the individual series, then expand it as part of the call.

Here's my code. Perhaps not pretty, but functional.

from matplotlib import cm
cmap = cm.get_cmap('gist_rainbow')  #('hsv') #('nipy_spectral')

max_colors = 31   # Constant, max mumber of series in any plot.  Ideally prime.
color_number = 0  # Variable, incremented for each series.

def restart_colors():
    global color_number
    color_number = 0
    #np.random.seed(1)

def next_color():
    global color_number
    color_number += 1
    #color = tuple(np.random.uniform(0.0, 0.5, 3))
    color = cmap( ((5 * color_number) % max_colors) / max_colors )
    return color

def plot_args():  # Invoked for each plot in a series as: '**(plot_args())'
    mkr = next_color()
    clr = (1 - mkr[0], 1 - mkr[1], 1 - mkr[2], mkr[3])  # Give line inverse of marker color
    return {
        "marker": "o",
        "color": clr,
        "mfc": mkr,
        "mec": mkr,
        "markersize": 0.5,
        "linewidth": 1,
    }

My context is JupyterLab and Pandas, so here's sample plot code:

restart_colors()  # Repeatable color sequence for every plot

fig, axs = plt.subplots(figsize=(15, 8))
plt.title("%s + T-meter"%name)

# Plot reference temperatures:
axs.set_ylabel("°C", rotation=0)
for s in ["T1", "T2", "T3", "T4"]:
    df_tmeter.plot(ax=axs, x="Timestamp", y=s, label="T-meter:%s" % s, **(plot_args()))

# Other series gets their own axis labels
ax2 = axs.twinx()
ax2.set_ylabel(units)

for c in df_uptime_sensors:
    df_uptime[df_uptime["UUID"] == c].plot(
        ax=ax2, x="Timestamp", y=units, label="%s - %s" % (units, c), **(plot_args())
    )

fig.tight_layout()
plt.show()

The resulting plot may not be the best example, but it becomes more relevant when interactively zoomed in. uptime + T-meter

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this

    router.post('/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


    return res.json({Name: req.body.name, Phone: req.body.phone});
});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"
}

<script>
  $(document).ready(function(){

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

If you need the X last bits of your integer, use a binary mask :

unsigned last8bitsvalue=(32 bit integer) & 0xFF
unsigned last16bitsvalue=(32 bit integer) & 0xFFFF

Copy files to network computers on windows command line

Below command will work in command prompt:

copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y

To Copy all files:

copy c:\folder\*.* \\dest-machine\destfolder /Z /Y

What's the best way to dedupe a table?

Here's one I've run into, in real life.

Assume you have a table of external/3rd party logins for users, and you're going to merge two users and want to dedupe on the provider/provider key values.

    ;WITH Logins AS
    (
        SELECT [LoginId],[UserId],[Provider],[ProviderKey]
        FROM [dbo].[UserLogin] 
        WHERE [UserId]=@FromUserID -- is the user we're deleting
              OR [UserId]=@ToUserID -- is the user we're moving data to
    ), Ranked AS 
    (
        SELECT Logins.*
            , [Picker]=ROW_NUMBER() OVER (
                       PARTITION BY [Provider],[ProviderKey]
                       ORDER BY CASE WHEN [UserId]=@FromUserID THEN 1 ELSE 0 END)
        FROM Logins
    )
    MERGE Logins AS T
    USING Ranked AS S
    ON S.[LoginId]=T.[LoginID]
    WHEN MATCHED AND S.[Picker]>1 -- duplicate Provider/ProviderKey
                 AND T.[UserID]=@FromUserID -- safety check 
    THEN DELETE
    WHEN MATCHED AND S.[Picker]=1 -- the only or best one
                 AND T.[UserID]=@FromUserID
    THEN UPDATE SET T.[UserID]=@ToUserID
    OUTPUT $action, DELETED.*, INSERTED.*;

force browsers to get latest js and css files in asp.net application

In ASP.NET Core (MVC 6) this works out of the box via the asp-append-version tag helper:

<script src="scripts/myjavascript.js" asp-append-version="true"></script>
<link href="styles/mystyle.css rel="stylesheet" asp-append-version="true" />

Bound method error

The syntax problem is shadowing method and variable names. In the current version sort_word_list() is a method, and sorted_word_list is a variable, whereas num_words is both. Also, list.sort() modifies the list and replaces it with a sorted version; the sorted(list) function actually returns a new list.

But I suspect this indicates a design problem. What's the point of calls like

test.parser()
test.sort_word_list()
test.num_words()

which don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something.

E.G.,

def sort_word_list(self):
   if self.sorted_word_list is not None:
      self.sorted_word_list = sorted(self.word_list)
   return self.sorted_word_list

(Alternately, you could use properties.)

Binding Listbox to List<object> in WinForms

Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:

listBox.DataSource = customerListObject;
listBox.DataTextField = "customerName";
listBox.DataValueField = "customerId";
listBox.DataBind();

Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)

Best practices to test protected methods with PHPUnit

I think troelskn is close. I would do this instead:

class ClassToTest
{
   protected function testThisMethod()
   {
     // Implement stuff here
   }
}

Then, implement something like this:

class TestClassToTest extends ClassToTest
{
  public function testThisMethod()
  {
    return parent::testThisMethod();
  }
}

You then run your tests against TestClassToTest.

It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).

Node.js throws "btoa is not defined" error

Here's a concise universal solution for base64 encoding:

const nodeBtoa = (b) => Buffer.from(b).toString('base64');
export const base64encode = typeof btoa !== 'undefined' ? btoa : nodeBtoa;

What does [object Object] mean?

You can see value inside [object Object] like this

Alert.alert(  JSON.stringify(userDate)  );

Try like this

    realm.write(() => {
       const userFormData = realm.create('User',{
       user_email: value.username,
       user_password: value.password,
      });
     });

      const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
      Alert.alert(  JSON.stringify(userDate)  );

reference

https://off.tokyo/blog/react-native-object-object/

How to create global variables accessible in all views using Express / Node.JS?

In your app.js you need add something like this

global.myvar = 100;

Now, in all your files you want use this variable, you can just access it as myvar

How to make a input field readonly with JavaScript?

document.getElementById("").readOnly = true

Good Patterns For VBA Error Handling

Error Handling in VBA


  • On Error Goto ErrorHandlerLabel
  • Resume (Next | ErrorHandlerLabel)
  • On Error Goto 0 (disables current error handler)
  • Err object

The Err object's properties are normally reset to zero or a zero-length string in the error handling routine, but it can also be done explicitly with Err.Clear.

Errors in the error handling routine are terminating.

The range 513-65535 is available for user errors. For custom class errors, you add vbObjectError to the error number. See MS documentation about Err.Raise and the list of error numbers.

For not implemented interface members in a derived class, you should use the constant E_NOTIMPL = &H80004001.


Option Explicit

Sub HandleError()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0

  Debug.Print "This line won't be executed."

DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub RaiseAndHandleError()
  On Error GoTo errMyErrorHandler
    ' The range 513-65535 is available for user errors.
    ' For class errors, you add vbObjectError to the error number.
    Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
  On Error GoTo 0

  Debug.Print "This line will be executed."

Exit Sub
errMyErrorHandler:
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
  Err.Clear
Resume Next
End Sub

Sub FailInErrorHandler()
  Dim a As Integer
  On Error GoTo errMyErrorHandler
    a = 7 / 0
  On Error GoTo 0

  Debug.Print "This line won't be executed."

DoCleanUp:
  a = 0
Exit Sub
errMyErrorHandler:
  a = 7 / 0 ' <== Terminating error!
  MsgBox Err.Description, _
    vbExclamation + vbOKCancel, _
    "Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub

Sub DontDoThis()

  ' Any error will go unnoticed!
  On Error Resume Next
  ' Some complex code that fails here.
End Sub

Sub DoThisIfYouMust()

  On Error Resume Next
  ' Some code that can fail but you don't care.
  On Error GoTo 0

  ' More code here
End Sub

Finding the average of a list

Combining a couple of the above answers, I've come up with the following which works with reduce and doesn't assume you have L available inside the reducing function:

from operator import truediv

L = [15, 18, 2, 36, 12, 78, 5, 6, 9]

def sum_and_count(x, y):
    try:
        return (x[0] + y, x[1] + 1)
    except TypeError:
        return (x + y, 2)

truediv(*reduce(sum_and_count, L))

# prints 
20.11111111111111

Implement Stack using Two Queues

Below is a very simple Java solution which supports the push operation efficient.

Algorithm -

  1. Declare two Queues q1 and q2.

  2. Push operation - Enqueue element to queue q1.

  3. Pop operation - Ensure that queue q2 is not empty. If it is empty, then dequeue all the elements from q1 except the last element and enqueue it to q2 one by one. Dequeue the last element from q1 and store it as the popped element. Swap the queues q1 and q2. Return the stored popped element.

  4. Peek operation - Ensure that queue q2 is not empty. If it is empty, then dequeue all the elements from q1 except the last element and enqueue it to q2 one by one. Dequeue the last element from q1 and store it as the peeked element. Enqueue it back to queue q2 and swap the queues q1 and q2. Return the stored peeked element.

Below is the code for above algorithm -

class MyStack {

    java.util.Queue<Integer> q1;
    java.util.Queue<Integer> q2;
    int SIZE = 0;

    /** Initialize your data structure here. */
    public MyStack() {
        q1 = new LinkedList<Integer>();
        q2 = new LinkedList<Integer>();

    }

    /** Push element x onto stack. */
    public void push(int x) {
        q1.add(x);
        SIZE ++;

    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        ensureQ2IsNotEmpty();
        int poppedEle = q1.remove();
        SIZE--;
        swapQueues();
        return poppedEle;
    }

    /** Get the top element. */
    public int top() {
        ensureQ2IsNotEmpty();
        int peekedEle = q1.remove();
        q2.add(peekedEle);
        swapQueues();
        return peekedEle;
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty() && q2.isEmpty();

    }

    /** move all elements from q1 to q2 except last element */
    public void ensureQ2IsNotEmpty() {
        for(int i=0; i<SIZE-1; i++) {
            q2.add(q1.remove());
        }
    }

    /** Swap queues q1 and q2 */
    public void swapQueues() {
        Queue<Integer> temp = q1;
        q1 = q2;
        q2 = temp;
    }
}

Double array initialization in Java

This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:

int[] x = {1,2,3,4};
String y = {"a","b","c"};

If you're not on the RHS of a variable declaration, use an array constructor instead:

int[] x;
x = new int[]{1,2,3,4};
String y;
y = new String[]{"a","b","c"};

These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.

In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:

double[][] m = new double[4][4];

for(int i=0; i<4; i++) {
    for(int j=0; j<4; j++) {
        m[i][j] = i*j;
    }
}

How to call base.base.method()?

You can't from C#. From IL, this is actually supported. You can do a non-virt call to any of your parent classes... but please don't. :)

How to get height of Keyboard?

// Step 1 :- Register NotificationCenter

ViewDidLoad() {

   self.yourtextfield.becomefirstresponder()

   // Register your Notification, To know When Key Board Appears.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides

    func keyboardWillShow(notification:NSNotification) {
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary
        let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
    }

    func keyboardWillHide(notification:NSNotification) {
        tblViewListData.frame.size.height = fltTblHeight
    }

How can you determine a point is between two other points on a line segment?

Here's another approach:

  • Lets assume the two points be A (x1,y1) and B (x2,y2)
  • The equation of the line passing through those points is (x-x1)/(y-y1)=(x2-x1)/(y2-y1) .. (just making equating the slopes)

Point C (x3,y3) will lie between A & B if:

  • x3,y3 satisfies the above equation.
  • x3 lies between x1 & x2 and y3 lies between y1 & y2 (trivial check)

What's the difference between all the Selection Segues?

Here is a quick summary of the segues and an example for each type.

Show - Pushes the destination view controller onto the navigation stack, sliding overtop from right to left, providing a back button to return to the source - or if not embedded in a navigation controller it will be presented modally
Example: Navigating inboxes/folders in Mail

Show Detail - For use in a split view controller, replaces the detail/secondary view controller when in an expanded 2 column interface, otherwise if collapsed to 1 column it will push in a navigation controller
Example: In Messages, tapping a conversation will show the conversation details - replacing the view controller on the right when in a two column layout, or push the conversation when in a single column layout

Present Modally - Presents a view controller in various animated fashions as defined by the Presentation option, covering the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, or on iPad it's common to present it as a centered box that darkens the presenting view controller
Example: Selecting Touch ID & Passcode in Settings

Popover Presentation - When run on iPad, the destination appears in a popover, and tapping anywhere outside of this popover will dismiss it, or on iPhone popovers are supported as well but by default it will present the destination modally over the full screen
Example: Tapping the + button in Calendar

Custom - You may implement your own custom segue and have control over its behavior

The deprecated segues are essentially the non-adaptive equivalents of those described above. These segue types were deprecated in iOS 8: Push, Modal, Popover, Replace.

For more info, you may read over the Using Segues documentation which also explains the types of segues and how to use them in a Storyboard. Also check out Session 216 Building Adaptive Apps with UIKit from WWDC 2014. They talked about how you can build adaptive apps using these new Adaptive Segues, and they built a demo project that utilizes these segues.

Jquery: Find Text and replace

Warning string.replace('string','new string') not replaced all character. You have to use regax replace.

For exp: I have a sting old string1, old string2, old string3 and want to replace old to new

Then i used.

    var test = 'old string1, old string2, old string3';

   //***** Wrong method **********
    test = test.replace('old', 'new'); // This  will replaced only first match not all
    Result: new string1, old string2, old string3

  //***** Right method **********
    test = test.replace(/([old])+/g, 'new'); // This  will replaced all match 
    Result: new string1, new string2, new string3

How to iterate over a JSONObject?

I made a small recursive function that goes through the entire json object and saves the key path and its value.

// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();

// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();

// Recursive function that goes through a json object and stores 
// its key and values in the hashmap 
private void loadJson(JSONObject json){
    Iterator<?> json_keys = json.keys();

    while( json_keys.hasNext() ){
        String json_key = (String)json_keys.next();

        try{
            key_path.push(json_key);
            loadJson(json.getJSONObject(json_key));
       }catch (JSONException e){
           // Build the path to the key
           String key = "";
           for(String sub_key: key_path){
               key += sub_key+".";
           }
           key = key.substring(0,key.length()-1);

           System.out.println(key+": "+json.getString(json_key));
           key_path.pop();
           myKeyValues.put(key, json.getString(json_key));
        }
    }
    if(key_path.size() > 0){
        key_path.pop();
    }
}

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

"Non-static method cannot be referenced from a static context" error

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media();
media.setLoanItem("Yes");

(Btw it would be better to use a boolean instead of a string containing "Yes".)

How to undo a successful "git cherry-pick"?

If possible, avoid hard resets. Hard resets are one of the very few destructive operations in git. Luckily, you can undo a cherry-pick without resets and avoid anything destructive.

Note the hash of the cherry-pick you want to undo, say it is ${bad_cherrypick}. Do a git revert ${bad_cherrypick}. Now the contents of your working tree are as they were before your bad cherry-pick.

Repeat your git cherry-pick ${wanted_commit}, and when you're happy with the new cherry-pick, do a git rebase -i ${bad_cherrypick}~1. During the rebase, delete both ${bad_cherrypick} and its corresponding revert.

The branch you are working on will only have the good cherry-pick. No resets needed!

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];

Use a loop to plot n charts Python

Use a dictionary!!

You can also use dictionaries that allows you to have more control over the plots:

import matplotlib.pyplot as plt
#   plot 0     plot 1    plot 2   plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]

plots = zip(x,y)
def loop_plot(plots):
    figs={}
    axs={}
    for idx,plot in enumerate(plots):
        figs[idx]=plt.figure()
        axs[idx]=figs[idx].add_subplot(111)
        axs[idx].plot(plot[0],plot[1])
return figs, axs

figs, axs = loop_plot(plots)

Now you can select the plot that you want to modify easily:

axs[0].set_title("Now I can control it!")

Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

Oracle PL/SQL - How to create a simple array variable?

You can also use an oracle defined collection

DECLARE 
  arrayvalues sys.odcivarchar2list;
BEGIN
  arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
  FOR x IN ( SELECT m.column_value m_value
               FROM table(arrayvalues) m )
  LOOP
    dbms_output.put_line (x.m_value||' is a good pal');
  END LOOP;
END;

I would use in-memory array. But with the .COUNT improvement suggested by uziberia:

DECLARE
  TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
  arrayvalues t_people;
BEGIN
  SELECT *
   BULK COLLECT INTO arrayvalues
   FROM (select 'Matt' m_value from dual union all
         select 'Joanne'       from dual union all
         select 'Robert'       from dual
    )
  ;
  --
  FOR i IN 1 .. arrayvalues.COUNT
  LOOP
    dbms_output.put_line(arrayvalues(i)||' is my friend');
  END LOOP;
END;

Another solution would be to use a Hashmap like @Jchomel did here.

NB:

With Oracle 12c you can even query arrays directly now!

Determine a user's timezone

The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such.

I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. You need to use Assembly.LoadFrom to load the assembly into memory, then you can use Activator.CreateInstance to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:

Assembly assembly = Assembly.LoadFrom("MyNice.dll");

Type type = assembly.GetType("MyType");

object instanceOfMyType = Activator.CreateInstance(type);

Update

When you have the assembly file name and the type name, you can use Activator.CreateInstance(assemblyName, typeName) to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

Dynamically load JS inside JS

The jQuery.getScript() method is a shorthand of the Ajax function (with the dataType attribute: $.ajax({ url: url,dataType: "script"}))

If you want the scripts to be cachable, either use RequireJS or follow jQuery's example on extending the jQuery.getScript method similar to the following.

jQuery.cachedScript = function( url, options ) {

  // Allow user to set any option except for dataType, cache, and url
  options = $.extend( options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
  console.log( textStatus );
});

Reference: jQuery.getScript() | jQuery API Documentation

MongoDB: How to update multiple documents with a single command?

You can use.`

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  `

"Application tried to present modally an active controller"?

The same problem error happened to me when I tried to present a child view controller instead of its UINavigationViewController parent

How do I `jsonify` a list in Flask?

Solved, no fuss. You can be lazy and use jsonify, all you need to do is pass in items=[your list].

Take a look here for the solution

https://github.com/mitsuhiko/flask/issues/510

Display curl output in readable JSON format in Unix shell script

You can use the json node module:

npm i -g json

then simply append | json after curl. curl http://localhost:8880/test.json | json

How to insert a timestamp in Oracle?

CREATE TABLE Table1 (
id int identity(1, 1) NOT NULL,
Somecolmn varchar (5),
LastChanged [timestamp] NOT NULL)

this works for mssql 2012

INSERT INTO Table1 VALUES('hello',DEFAULT)  

Check if element exists in jQuery

$('elemId').length doesn't work for me.

You need to put # before element id:

$('#elemId').length
---^

With vanilla JavaScript, you don't need the hash (#) e.g. document.getElementById('id_here') , however when using jQuery, you do need to put hash to target elements based on id just like CSS.

How do I create a user account for basic authentication?

I know this is a really old question but I wanted to add a bit of explanation that I discovered the hard way (this is n00b information).

"Basic Authentication" shares the same accounts that you have on your local computer or network. If you leave the domain and realm empty, local accounts are what are actually being used. So to add a new account you follow the exact process you would for adding a normal new user account to your local computer (as answered by JoshM or shown here). If you enter a domain and realm you can create network accounts in your local active directory and these are what will be used to log the user in and out.

Because it has been around for so long, basic authentication is generally compatible with any browser/system out there but it does have to major flaws:

  • user and password are sent in the clear (except over SSL)
  • you need to have a user account for each user or client

For more information about basic authentication or user accounts see the following MSDN page.

How to search file text for a pattern and replace it with a given value

Here an alternative to the one liner from jim, this time in a script

ARGV[0..-3].each{|f| File.write(f, File.read(f).gsub(ARGV[-2],ARGV[-1]))}

Save it in a script, eg replace.rb

You start in on the command line with

replace.rb *.txt <string_to_replace> <replacement>

*.txt can be replaced with another selection or with some filenames or paths

broken down so that I can explain what's happening but still executable

# ARGV is an array of the arguments passed to the script.
ARGV[0..-3].each do |f| # enumerate the arguments of this script from the first to the last (-1) minus 2
  File.write(f,  # open the argument (= filename) for writing
    File.read(f) # open the argument (= filename) for reading
    .gsub(ARGV[-2],ARGV[-1])) # and replace all occurances of the beforelast with the last argument (string)
end

EDIT: if you want to use a regular expression use this instead Obviously, this is only for handling relatively small text files, no Gigabyte monsters

ARGV[0..-3].each{|f| File.write(f, File.read(f).gsub(/#{ARGV[-2]}/,ARGV[-1]))}

How to change an application icon programmatically in Android?

Try this solution

<activity android:name=".SplashActivity"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity-alias android:label="ShortCut"
        android:icon="@drawable/ic_short_cut"
        android:name=".SplashActivityAlias"
        android:enabled="false"
        android:targetActivity=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>

Add the following code when you want to change your app icon

PackageManager pm = getPackageManager();
                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivity"),
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);

                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivityAlias"),
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP);

Why do I need 'b' to encode a string with Base64?

There is all you need:

expected bytes, not str

The leading b makes your string binary.

What version of Python do you use? 2.x or 3.x?

Edit: See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit for the gory details of strings in Python 3.x

Why is my power operator (^) not working?

Well, first off, the ^ operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.

Now, regarding your problem with using the pow() function, some googling shows that casting one of the arguments to double helps:

result = (int) pow((double) a,i);

Note that I also cast the result to int as all pow() overloads return double, not int. I don't have a MS compiler available so I couldn't check the code above, though.

Since C99, there are also float and long double functions called powf and powl respectively, if that is of any help.

The source was not found, but some or all event logs could not be searched

For me this error was due to the command prompt, which was not running under administrator privileges. You need to right click on the command prompt and say "Run as administrator".

You need administrator role to install or uninstall a service.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

I have just asked the Spring Cloud guys and thought I should share the info I have here.

bootstrap.yml is loaded before application.yml.

It is typically used for the following:

  • when using Spring Cloud Config Server, you should specify spring.application.name and spring.cloud.config.server.git.uri inside bootstrap.yml
  • some encryption/decryption information

Technically, bootstrap.yml is loaded by a parent Spring ApplicationContext. That parent ApplicationContext is loaded before the one that uses application.yml.

how to compare the Java Byte[] array?

You can also use a ByteArrayComparator from Apache Directory. In addition to equals it lets you compare if one array is greater than the other.

How to 'update' or 'overwrite' a python list

What about replace the item if you know the position:

aList[0]=2014

Or if you don't know the position loop in the list, find the item and then replace it

aList = [123, 'xyz', 'zara', 'abc']
    for i,item in enumerate(aList):
      if item==123:
        aList[i]=2014
        break
    
    print aList

python inserting variable string as file name

Even better are f-strings in python 3!

f = open(f'{name}.csv', 'wb')

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

How to INNER JOIN 3 tables using CodeIgniter

I created a function to get an array with the values ??for the fields and to join. This goes in the model:

  public function GetDataWhereExtenseJoin($table,$fields,$data) {
    //pega os campos passados para o select
    foreach($fields as $coll => $value){
        $this->db->select($value);
    }
    //pega a tabela
    $this->db->from($table);
    //pega os campos do join
    foreach($data as $coll => $value){
        $this->db->join($coll, $value);
    }
    //obtem os valores
    $query = $this->db->get();
    //retorna o resultado
    return $query->result();

}

This goes in the controller:

$data_field = array(
        'NameProduct' => 'product.IdProduct',
        'IdProduct' => 'product.NameProduct',
        'NameCategory' => 'category.NameCategory',
        'IdCategory' => 'category.IdCategory'
        );
    $data_join = array
                    ( 'product' => 'product_category.IdProduct = product.IdProduct',
                      'category' => 'product_category.IdCategory = category.IdCategory',
                      'product' => 'product_category.IdProduct = product.IdProduct'
                    );
    $product_category = $this->mmain->GetDataWhereExtenseJoin('product_category', $data_field, $data_join);

result:

echo '<pre>';
    print_r($product_category);
    die;

Change tab bar tint color on iOS 7

Write this in your View Controller class of your Tab Bar:

// Generate a black tab bar
self.tabBarController.tabBar.barTintColor = [UIColor blackColor];

// Set the selected icons and text tint color
self.tabBarController.tabBar.tintColor = [UIColor orangeColor];

SQL Server 2000: How to exit a stored procedure?

Its because you have no BEGIN and END statements. You shouldn't be seeing the prints, or errors running this statement, only Statement Completed (or something like that).

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

Return multiple values from a function in swift

Also:

func getTime() -> (hour: Int, minute: Int,second: Int) {
    let hour = 1
    let minute = 2
    let second = 3
    return ( hour, minute, second)
}

Then it's invoked as:

let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")

This is the standard way how to use it in the book The Swift Programming Language written by Apple.

or just like:

let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")

it's the same but less clearly.

How to use Sublime over SSH

You can use sftp to mount the remote directory on your location machine and then simply open the files using Sublime text the way you normally would.

To mount remote directory using sftp, enter the following on your Linux file manager;

sftp://user@remote_box.com:22/home/user/code_directory

It might seem slow depending on your internet speeds. But this worked for me.

Scroll RecyclerView to show selected item on top

In my case my RecyclerView have a padding top like this

<android.support.v7.widget.RecyclerView
     ...
     android:paddingTop="100dp"
     android:clipToPadding="false"
/>

Then for scroll a item to top, I need to

recyclerViewLinearLayoutManager.scrollToPositionWithOffset(position, -yourRecyclerView.getPaddingTop());

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

What is in your .vimrc?

You asked for it :-)

"{{{Auto Commands

" Automatically cd into the directory that the file is in
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')

" Remove any trailing whitespace that is in the file
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif

" Restore cursor position to where it was before
augroup JumpCursorOnEdit
   au!
   autocmd BufReadPost *
            \ if expand("<afile>:p:h") !=? $TEMP |
            \   if line("'\"") > 1 && line("'\"") <= line("$") |
            \     let JumpCursorOnEdit_foo = line("'\"") |
            \     let b:doopenfold = 1 |
            \     if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
            \        let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
            \        let b:doopenfold = 2 |
            \     endif |
            \     exe JumpCursorOnEdit_foo |
            \   endif |
            \ endif
   " Need to postpone using "zv" until after reading the modelines.
   autocmd BufWinEnter *
            \ if exists("b:doopenfold") |
            \   exe "normal zv" |
            \   if(b:doopenfold > 1) |
            \       exe  "+".1 |
            \   endif |
            \   unlet b:doopenfold |
            \ endif
augroup END

"}}}

"{{{Misc Settings

" Necesary  for lots of cool vim things
set nocompatible

" This shows what you are typing as a command.  I love this!
set showcmd

" Folding Stuffs
set foldmethod=marker

" Needed for Syntax Highlighting and stuff
filetype on
filetype plugin on
syntax enable
set grepprg=grep\ -nH\ $*

" Who doesn't like autoindent?
set autoindent

" Spaces are better than a tab character
set expandtab
set smarttab

" Who wants an 8 character tab?  Not me!
set shiftwidth=3
set softtabstop=3

" Use english for spellchecking, but don't spellcheck by default
if version >= 700
   set spl=en spell
   set nospell
endif

" Real men use gcc
"compiler gcc

" Cool tab completion stuff
set wildmenu
set wildmode=list:longest,full

" Enable mouse support in console
set mouse=a

" Got backspace?
set backspace=2

" Line Numbers PWN!
set number

" Ignoring case is a fun trick
set ignorecase

" And so is Artificial Intellegence!
set smartcase

" This is totally awesome - remap jj to escape in insert mode.  You'll never type jj anyway, so it's great!
inoremap jj <Esc>

nnoremap JJJJ <Nop>

" Incremental searching is sexy
set incsearch

" Highlight things that we find with the search
set hlsearch

" Since I use linux, I want this
let g:clipbrdDefaultReg = '+'

" When I close a tab, remove the buffer
set nohidden

" Set off the other paren
highlight MatchParen ctermbg=4
" }}}

"{{{Look and Feel

" Favorite Color Scheme
if has("gui_running")
   colorscheme inkpot
   " Remove Toolbar
   set guioptions-=T
   "Terminus is AWESOME
   set guifont=Terminus\ 9
else
   colorscheme metacosm
endif

"Status line gnarliness
set laststatus=2
set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]

" }}}

"{{{ Functions

"{{{ Open URL in browser

function! Browser ()
   let line = getline (".")
   let line = matchstr (line, "http[^   ]*")
   exec "!konqueror ".line
endfunction

"}}}

"{{{Theme Rotating
let themeindex=0
function! RotateColorTheme()
   let y = -1
   while y == -1
      let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#"
      let x = match( colorstring, "#", g:themeindex )
      let y = match( colorstring, "#", x + 1 )
      let g:themeindex = x + 1
      if y == -1
         let g:themeindex = 0
      else
         let themestring = strpart(colorstring, x + 1, y - x - 1)
         return ":colorscheme ".themestring
      endif
   endwhile
endfunction
" }}}

"{{{ Paste Toggle
let paste_mode = 0 " 0 = normal, 1 = paste

func! Paste_on_off()
   if g:paste_mode == 0
      set paste
      let g:paste_mode = 1
   else
      set nopaste
      let g:paste_mode = 0
   endif
   return
endfunc
"}}}

"{{{ Todo List Mode

function! TodoListMode()
   e ~/.todo.otl
   Calendar
   wincmd l
   set foldlevel=1
   tabnew ~/.notes.txt
   tabfirst
   " or 'norm! zMzr'
endfunction

"}}}

"}}}

"{{{ Mappings

" Open Url on this line with the browser \w
map <Leader>w :call Browser ()<CR>

" Open the Project Plugin <F2>
nnoremap <silent> <F2> :Project<CR>

" Open the Project Plugin
nnoremap <silent> <Leader>pal  :Project .vimproject<CR>

" TODO Mode
nnoremap <silent> <Leader>todo :execute TodoListMode()<CR>

" Open the TagList Plugin <F3>
nnoremap <silent> <F3> :Tlist<CR>

" Next Tab
nnoremap <silent> <C-Right> :tabnext<CR>

" Previous Tab
nnoremap <silent> <C-Left> :tabprevious<CR>

" New Tab
nnoremap <silent> <C-t> :tabnew<CR>

" Rotate Color Scheme <F8>
nnoremap <silent> <F8> :execute RotateColorTheme()<CR>

" DOS is for fools.
nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR>

" Paste Mode!  Dang! <F10>
nnoremap <silent> <F10> :call Paste_on_off()<CR>
set pastetoggle=<F10>

" Edit vimrc \ev
nnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR>

" Edit gvimrc \gv
nnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR>

" Up and down are more logical with g..
nnoremap <silent> k gk
nnoremap <silent> j gj
inoremap <silent> <Up> <Esc>gka
inoremap <silent> <Down> <Esc>gja

" Good call Benjie (r for i)
nnoremap <silent> <Home> i <Esc>r
nnoremap <silent> <End> a <Esc>r

" Create Blank Newlines and stay in Normal mode
nnoremap <silent> zj o<Esc>
nnoremap <silent> zk O<Esc>

" Space will toggle folds!
nnoremap <space> za

" Search mappings: These will make it so that going to the next one in a
" search will center on the line it's found in.
map N Nzz
map n nzz

" Testing
set completeopt=longest,menuone,preview

inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"
inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"

" Swap ; and :  Convenient.
nnoremap ; :
nnoremap : ;

" Fix email paragraphs
nnoremap <leader>par :%s/^>$//<CR>

"ly$O#{{{ "lpjjj_%A#}}}jjzajj

"}}}

"{{{Taglist configuration
let Tlist_Use_Right_Window = 1
let Tlist_Enable_Fold_Column = 0
let Tlist_Exit_OnlyWindow = 1
let Tlist_Use_SingleClick = 1
let Tlist_Inc_Winwidth = 0
"}}}

let g:rct_completion_use_fri = 1
"let g:Tex_DefaultTargetFormat = "pdf"
let g:Tex_ViewRule_pdf = "kpdf"

filetype plugin indent on
syntax on

Docker-Compose persistent data MySQL

You have to create a separate volume for mysql data.

So it will look like this:

volumes_from:
  - data
volumes:
  - ./mysql-data:/var/lib/mysql

And no, /var/lib/mysql is a path inside your mysql container and has nothing to do with a path on your host machine. Your host machine may even have no mysql at all. So the goal is to persist an internal folder from a mysql container.

How can I customize the tab-to-space conversion factor?

Menu File ? Preferences ? Settings

Add to user settings:

"editor.tabSize": 2,
"editor.detectIndentation": false

then right click your document if you have one opened already and click Format Document to have your existing document follow these new settings.

Convert named list to vector with values only

Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE)

What's the equivalent of Java's Thread.sleep() in JavaScript?

This eventually helped me:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

What do 'lazy' and 'greedy' mean in the context of regular expressions?

As far as I know, most regex engine is greedy by default. Add a question mark at the end of quantifier will enable lazy match.

As @Andre S mentioned in comment.

  • Greedy: Keep searching until condition is not satisfied.
  • Lazy: Stop searching once condition is satisfied.

Refer to the example below for what is greedy and what is lazy.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String args[]){
        String money = "100000000999";
        String greedyRegex = "100(0*)";
        Pattern pattern = Pattern.compile(greedyRegex);
        Matcher matcher = pattern.matcher(money);
        while(matcher.find()){
            System.out.println("I'm greeedy and I want " + matcher.group() + " dollars. This is the most I can get.");
        }

        String lazyRegex = "100(0*?)";
        pattern = Pattern.compile(lazyRegex);
        matcher = pattern.matcher(money);
        while(matcher.find()){
            System.out.println("I'm too lazy to get so much money, only " + matcher.group() + " dollars is enough for me");
        }
    }
}


The result is:

I'm greeedy and I want 100000000 dollars. This is the most I can get.

I'm too lazy to get so much money, only 100 dollars is enough for me

res.sendFile absolute path

I tried this and it worked.

app.get('/', function (req, res) {
    res.sendFile('public/index.html', { root: __dirname });
});

I ran into a merge conflict. How can I abort the merge?

Sourcetree

Because you not commit your merge, then just double click on another branch (which mean checkout it) and when sourcetree ask you about discarding all changes then agree :)

Update

I see many down-votes but any commet... I will left this answer which is addressed for those who use SourceTree as git client (as I - when I looking for solution for question asked by OP)

How to make child element higher z-index than parent?

Try using this code, it worked for me:

z-index: unset;

Exercises to improve my Java programming skills

You could try the problems at RosettaCode, many of which lack Java solutions at the moment. The problems are of many different difficulties, but each has a solution already in another language which should help with the algorithmic side.

continuing execution after an exception is thrown in java

Try this:

try
{
    throw new InvalidEmployeeTypeException();
    input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
      //do error handling
}

continue;

Return JSON response from Flask view

Flask 1.1.x supports returning a JSON dict without calling jsonify. If you want to return something besides a dict, you still need to call jsonify.

@app.route("/")
def index():
    return {
        "api_stuff": "values",
    }

is equivalent to

@app.route("/")
def index():
    return jsonify({
        "api_stuff": "values",
    })

See the pull request that added this: https://github.com/pallets/flask/pull/3111

Installing a local module using npm?

you just provide one <folder> argument to npm install, argument should point toward the local folder instead of the package name:

npm install /path

how to re-format datetime string in php?

For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php

$datetime = "20130409163705"; 
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want

Result:

09/04/2013 16:37:05

How to replace multiple white spaces with one white space

I'm sharing what I use, because it appears I've come up with something different. I've been using this for a while and it is fast enough for me. I'm not sure how it stacks up against the others. I uses it in a delimited file writer and run large datatables one field at a time through it.

    public static string NormalizeWhiteSpace(string S)
    {
        string s = S.Trim();
        bool iswhite = false;
        int iwhite;
        int sLength = s.Length;
        StringBuilder sb = new StringBuilder(sLength);
        foreach(char c in s.ToCharArray())
        {
            if(Char.IsWhiteSpace(c))
            {
                if (iswhite)
                {
                    //Continuing whitespace ignore it.
                    continue;
                }
                else
                {
                    //New WhiteSpace

                    //Replace whitespace with a single space.
                    sb.Append(" ");
                    //Set iswhite to True and any following whitespace will be ignored
                    iswhite = true;
                }  
            }
            else
            {
                sb.Append(c.ToString());
                //reset iswhitespace to false
                iswhite = false;
            }
        }
        return sb.ToString();
    }

How can I use iptables on centos 7?

Put the IPtables configuration in the traditional file and it will be loaded after boot:

/etc/sysconfig/iptables

Why does Python code use len() function instead of a length method?

Something missing from the rest of the answers here: the len function checks that the __len__ method returns a non-negative int. The fact that len is a function means that classes cannot override this behaviour to avoid the check. As such, len(obj) gives a level of safety that obj.len() cannot.

Example:

>>> class A:
...     def __len__(self):
...         return 'foo'
...
>>> len(A())
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    len(A())
TypeError: 'str' object cannot be interpreted as an integer
>>> class B:
...     def __len__(self):
...         return -1
... 
>>> len(B())
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    len(B())
ValueError: __len__() should return >= 0

Of course, it is possible to "override" the len function by reassigning it as a global variable, but code which does this is much more obviously suspicious than code which overrides a method in a class.

Android Activity as a dialog

Use this code so that the dialog activity won't be closed when the user touches outside the dialog box:

this.setFinishOnTouchOutside(false);

requires API level 11

Copying text outside of Vim with set mouse=a enabled

I accidently explained how to switch off set mouse=a, when I reread the question and found out that the OP did not want to switch it off in the first place. Anyway for anyone searching how to switch off the mouse (set mouse=) centrally, I leave a reference to my answer here: https://unix.stackexchange.com/a/506723/194822

Detect when browser receives file download

"How to detect when browser receives file download?"
I faced the same problem with that config:
struts 1.2.9
jquery-1.3.2.
jquery-ui-1.7.1.custom
IE 11
java 5


My solution with a cookie:
- Client side:
When submitting your form, call your javascript function to hide your page and load your waiting spinner

function loadWaitingSpinner(){
... hide your page and show your spinner ...
}

Then, call a function that will check every 500ms whether a cookie is coming from server.

function checkCookie(){
    var verif = setInterval(isWaitingCookie,500,verif);
}

If the cookie is found, stop checking every 500ms, expire the cookie and call your function to come back to your page and remove the waiting spinner (removeWaitingSpinner()). It is important to expire the cookie if you want to be able to download another file again!

function isWaitingCookie(verif){
    var loadState = getCookie("waitingCookie");
    if (loadState == "done"){
        clearInterval(verif);
        document.cookie = "attenteCookie=done; expires=Tue, 31 Dec 1985 21:00:00 UTC;";
        removeWaitingSpinner();
    }
}
    function getCookie(cookieName){
        var name = cookieName + "=";
        var cookies = document.cookie
        var cs = cookies.split(';');
        for (var i = 0; i < cs.length; i++){
            var c = cs[i];
            while(c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0){
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
function removeWaitingSpinner(){
... come back to your page and remove your spinner ...
}

- Server side:
At the end of your server process, add a cookie to the response. That cookie will be sent to the client when your file will be ready for download.

Cookie waitCookie = new Cookie("waitingCookie", "done");
response.addCookie(waitCookie);

I hope to help someone!

Getting JSONObject from JSONArray

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

nginx: send all requests to a single html page

Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just

rewrite ^ /base.html break;

You should be able to put that in a location or directly in the server.

How to add a new row to datagridview programmatically

Like this:

var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
//....

android.os.NetworkOnMainThreadException with android 4.2

android.os.NetworkOnMainThreadException occurs when you try to access network on your main thread (You main activity execution). To avoid this, you must create a separate thread or AsyncTask or Runnable implementation to execute your JSON data loading. Since HoneyComb you can not further execute the network task on main thread. Here is the implementation using AsyncTask for a network task execution

How do I send email with JavaScript without opening the mail client?

You cannot cause the user's browser to send email silently. That would be a horrible security problem as any website could use their system as a spam relay and/or harvest their email address.

You need to make an HTTP request to a server side process (written in the language of your choice) which sends the mail from your server.

Catch multiple exceptions in one line (except block)

From Python documentation -> 8.3 Handling Exceptions:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):
    pass

Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

The gacutil utility is not available on client machines, and the Window SDK license forbids redistributing it to your customers. When your customer can not, will not, (and really should not) download the 300MB Windows SDK as part of your application's install process.

There is an officially supported API you (or your installer) can use to register an assembly in the global assembly cache. Microsoft's Windows Installer technology knows how to call this API for you. You would have to consult your MSI installer utility (e.g. WiX, InnoSetup) for their own syntax of how to indicate you want an assembly to be registered in the Global Assembly Cache.

But MSI, and gacutil, are doing nothing special. They simply call the same API you can call yourself. For documentation on how to register an assembly through code, see:

KB317540: DOC: Global Assembly Cache (GAC) APIs Are Not Documented in the .NET Framework Software Development Kit (SDK) Documentation

var IAssemblyCache assemblyCache;
CreateAssemblyCache(ref assemblyCache, 0);


String manifestPath = "D:\Program Files\Contoso\Frobber\Grob.dll";

FUSION_INSTALL_REFERENCE refData;
refData.cbSize = SizeOf(refData); //The size of the structure in bytes
refData.dwFlags = 0; //Reserved, must be zero
refData.guidScheme = FUSION_REFCOUNT_FILEPATH_GUID; //The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file.
refData.szIdentifier = "D:\Program Files\Contoso\Frobber\SuperGrob.exe"; //A unique string that identifies the application that installed the assembly
refData.szNonCannonicalData = "Super cool grobber 9000"; //A string that is only understood by the entity that adds the reference. The GAC only stores this string

//Add a new assembly to the GAC. 
//The assembly must be persisted in the file system and is copied to the GAC.
assemblyCache.InstallAssembly(
      IASSEMBLYCACHE_INSTALL_FLAG_FORCE_REFRESH, //The files of an existing assembly are overwritten regardless of their version number
      manifestPath, //A string pointing to the dynamic-linked library (DLL) that contains the assembly manifest. Other assembly files must reside in the same directory as the DLL that contains the assembly manifest.
      refData);

More documentation before the KB article is deleted:

The fields of the structure are defined as follows:

  • cbSize - The size of the structure in bytes.
  • dwFlags - Reserved, must be zero.
  • guidScheme - The entity that adds the reference.
  • szIdentifier - A unique string that identifies the application that installed the assembly.
  • szNonCannonicalData - A string that is only understood by the entity that adds the reference. The GAC only stores this string.

Possible values for the guidScheme field can be one of the following:

FUSION_REFCOUNT_MSI_GUID - The assembly is referenced by an application that has been installed by using Windows Installer. The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer. This scheme must only be used by Windows Installer itself. FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID - The assembly is referenced by an application that appears in Add/Remove Programs. The szIdentifier field is the token that is used to register the application with Add/Remove programs. FUSION_REFCOUNT_FILEPATH_GUID - The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file. FUSION_REFCOUNT_OPAQUE_STRING_GUID - The assembly is referenced by an application that is only represented by an opaque string. The szIdentifier is this opaque string. The GAC does not perform existence checking for opaque references when you remove this.

Loop through the rows of a particular DataTable

Here's the best way I found:

    For Each row As DataRow In your_table.Rows
        For Each cell As String In row.ItemArray
            'do what you want!
        Next
    Next

What are the lengths of Location Coordinates, latitude and longitude?

Please check the UTM coordinate system https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

These values must be in meters for a specific map projection. For example, the peak of Mount Assiniboine (at 50°52'10"N 115°39'03"W) in UTM Zone 11 is represented by 11U 594934.108296 5636174.091274 where (594934.108296, 5636174.091274) are in meters.

Using %s in C correctly - very basic level

For both *printf and *scanf, %s expects the corresponding argument to be of type char *, and for scanf, it had better point to a writable buffer (i.e., not a string literal).

char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";

printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);

scanf("%55s", str_buf);

Using %s in scanf without an explcit field width opens the same buffer overflow exploit that gets did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf, you can't supply the field with as a run time argument:

printf("%*s\n", field_width, string);

One option is to build the format string dynamically:

char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"

EDIT

Using scanf with the %s conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like

"This is a test"

then scanf("%55s", str_buf) will read and assign "This" to str_buf. Note that the field with specifier doesn't make a difference in this case.

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

Getting activity from context in android

Context may be an Application, a Service, an Activity, and more.

Normally the context of Views in an Activity is the Activity itself so you may think you can just cast this Context to Activity but actually you can't always do it, because the context can also be a ContextThemeWrapper in this case.

ContextThemeWrapper is used heavily in the recent versions of AppCompat and Android (thanks to the android:theme attribute in layouts) so I would personally never perform this cast.

So short answer is: you can't reliably retrieve an Activity from a Context in a View. Pass the Activity to the view by calling a method on it which takes the Activity as parameter.

how to set length of an column in hibernate with maximum length

@Column(name = Columns.COLUMN_NAME, columnDefinition = "NVARCHAR(MAX)")

max indicates that the maximum storage size is 2^31-1 bytes (2 GB)

How can I exit from a javascript function?

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

How to upload images into MySQL database using PHP code

Just few more details:

  • Add mysql field

`image` blob

  • Get data from image

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

  • Insert image data into db

$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";

  • Show image to the web

<img src="data:image/png;base64,'.base64_encode($row['image']).'">

  • End

convert a char* to std::string

I've just been struggling with MSVC2005 to use the std::string(char*) constructor just like the top-rated answer. As I see this variant listed as #4 on always-trusted http://en.cppreference.com/w/cpp/string/basic_string/basic_string , I figure even an old compiler offers this.

It has taken me so long to realize that this constructor absolute refuses to match with (unsigned char*) as an argument ! I got these incomprehensible error messages about failure to match with std::string argument type, which was definitely not what I was aiming for. Just casting the argument with std::string((char*)ucharPtr) solved my problem... duh !

What is the difference between encode/decode?

The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.

javascript unexpected identifier

It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

Create a date from day month and year with T-SQL

You can also use

select DATEFROMPARTS(year, month, day) as ColDate, Col2, Col3 
From MyTable Where DATEFROMPARTS(year, month, day) Between @DateIni and @DateEnd

Works in SQL since ver.2012 and AzureSQL

Difference between subprocess.Popen and os.system

subprocess.Popen() is strict super-set of os.system().

MySQL Multiple Where Clause

May be using this query you don't get any result or empty result. You need to use OR instead of AND in your query like below.

$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');

Try out this query.

How do I reference a cell within excel named range?

"Do you know if there's a way to make this work with relative selections, so that the formula can be "dragged down"/applied across several cells in the same column?"

To make such selection relative simply use ROW formula for a row number in INDEX formula and COLUMN formula for column number in INDEX formula. To make this clearer here is the example:

=INDEX(named_range,ROW(A1),COLUMN(A1))

Assuming the named range starts at A1 this formula simply indexes that range by row and column number of referenced cell and since that reference is relative it changes when you drag the the cell down or to the side, which makes it possible to create whole array of cells easily.

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

Link to add to Google calendar

Here's an example link you can use to see the format:

https://www.google.com/calendar/render?action=TEMPLATE&text=Your+Event+Name&dates=20140127T224000Z/20140320T221500Z&details=For+details,+link+here:+http://www.example.com&location=Waldorf+Astoria,+301+Park+Ave+,+New+York,+NY+10022&sf=true&output=xml

Note the key query parameters:

text
dates
details
location

Here's another example (taken from http://wordpress.org/support/topic/direct-link-to-add-specific-google-calendar-event):

<a href="http://www.google.com/calendar/render?
action=TEMPLATE
&text=[event-title]
&dates=[start-custom format='Ymd\\THi00\\Z']/[end-custom format='Ymd\\THi00\\Z']
&details=[description]
&location=[location]
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>

Here's a form which will help you construct such a link if you want (mentioned in earlier answers):

https://support.google.com/calendar/answer/3033039 Edit: This link no longer gives you a form you can use

Set QLineEdit to accept only numbers

The Regex Validator

So far, the other answers provide solutions for only a relatively finite number of digits. However, if you're concerned with an arbitrary or a variable number of digits you can use a QRegExpValidator, passing a regex that only accepts digits (as noted by user2962533's comment). Here's a minimal, complete example:

#include <QApplication>
#include <QLineEdit>
#include <QRegExpValidator>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QLineEdit le;
    le.setValidator(new QRegExpValidator(QRegExp("[0-9]*"), &le));
    le.show();

    return app.exec();
}

The QRegExpValidator has its merits (and that's only an understatement). It allows for a bunch of other useful validations:

QRegExp("[1-9][0-9]*")    //  leading digit must be 1 to 9 (prevents leading zeroes).
QRegExp("\\d*")           //  allows matching for unicode digits (e.g. for 
                          //    Arabic-Indic numerals such as ???).
QRegExp("[0-9]+")         //  input must have at least 1 digit.
QRegExp("[0-9]{8,32}")    //  input must be between 8 to 32 digits (e.g. for some basic
                          //    password/special-code checks).
QRegExp("[0-1]{,4}")      //  matches at most four 0s and 1s.
QRegExp("0x[0-9a-fA-F]")  //  matches a hexadecimal number with one hex digit.
QRegExp("[0-9]{13}")      //  matches exactly 13 digits (e.g. perhaps for ISBN?).
QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")
                          //  matches a format similar to an ip address.
                          //    N.B. invalid addresses can still be entered: "999.999.999.999".     

More On Line-edit Behaviour

According to documentation:

Note that if there is a validator set on the line edit, the returnPressed()/editingFinished() signals will only be emitted if the validator returns QValidator::Acceptable.

Thus, the line-edit will allow the user to input digits even if the minimum amount has not yet been reached. For example, even if the user hasn't inputted any text against the regex "[0-9]{3,}" (which requires at least 3 digits), the line-edit still allows the user to type input to reach that minimum requirement. However, if the user finishes editing without satsifying the requirement of "at least 3 digits", the input would be invalid; the signals returnPressed() and editingFinished() won't be emitted.

If the regex had a maximum-bound (e.g. "[0-1]{,4}"), then the line-edit will stop any input past 4 characters. Additionally, for character sets (i.e. [0-9], [0-1], [0-9A-F], etc.) the line-edit only allows characters from that particular set to be inputted.

Note that I've only tested this with Qt 5.11 on a macOS, not on other Qt versions or operating systems. But given Qt's cross-platform schema...

Demo: Regex Validators Showcase

How do I check if a file exists in Java?

I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.

The following snippet

if(Files.isRegularFile(Paths.get(pathToFile))) {
    // do something
}

is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).

Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.

From Java Oracle documentation

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

The best option is to use the original LESS version of bootstrap (get it from github).

Open variables.less and look for // Media queries breakpoints

Find this code and change the breakpoint value:

// Large screen / wide desktop
@screen-lg:                  1200px; // change this
@screen-lg-desktop:          @screen-lg;

Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container

How to fill Dataset with multiple tables?

Filling a DataSet with multiple tables can be done by sending multiple requests to the database, or in a faster way: Multiple SELECT statements can be sent to the database server in a single request. The problem here is that the tables generated from the queries have automatic names Table and Table1. However, the generated table names can be mapped to names that should be used in the DataSet.

SqlDataAdapter adapter = new SqlDataAdapter(
      "SELECT * FROM Customers; SELECT * FROM Orders", connection);
adapter.TableMappings.Add("Table", "Customer");
adapter.TableMappings.Add("Table1", "Order");

adapter.Fill(ds);

How to make MySQL handle UTF-8 properly

SET NAMES UTF8

This is does the trick

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

ImportError: Couldn't import Django

I think the best way to use django is with virtualenv it's safe and you can install many apps in virtualenv which does not affect any outer space of the system vitualenv uses the default version of python which is same as in your system to install virtualenv

sudo pip install virtualenv

or for python3

sudo pip3 install virtualenv

and then in your dir

mkdir ~/newproject

cd ~/newproject

Now, create a virtual environment within the project directory by typing

virtualenv newenv

To install packages into the isolated environment, you must activate it by typing:

source newenv/bin/activate

now install here with

pip install django

You can verify the installation by typing:

django-admin --version

To leave your virtual environment, you need to issue the deactivate command from anywhere on the system:

deactivate

Why don’t my SVG images scale using the CSS "width" property?

I had to figure it out myself but some svgs your need to match the viewBox & width+height in.

E.g. if it already has width="x" height="y" then =>

add <svg ... viewBox="0 0 [width] [height]">

and the opposite.

After that it will scale with <svg ... style="width: xxx; height: yyy;">

How to check if String value is Boolean type in Java?

Yes, but, didn't you parse "false"? If you parse "true", then they return true.

Maybe there's a misunderstanding: the methods don't test, if the String content represents a boolean value, they evaluate the String content to boolean.

JavaScript array to CSV

I created this code for creating a nice, readable csv files:

var objectToCSVRow = function(dataObject) {
    var dataArray = new Array;
    for (var o in dataObject) {
        var innerValue = dataObject[o]===null?'':dataObject[o].toString();
        var result = innerValue.replace(/"/g, '""');
        result = '"' + result + '"';
        dataArray.push(result);
    }
    return dataArray.join(' ') + '\r\n';
}

var exportToCSV = function(arrayOfObjects) {

    if (!arrayOfObjects.length) {
        return;
    }

    var csvContent = "data:text/csv;charset=utf-8,";

    // headers
    csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));

    arrayOfObjects.forEach(function(item){
        csvContent += objectToCSVRow(item);
    }); 

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "customers.csv");
    document.body.appendChild(link); // Required for FF
    link.click();
    document.body.removeChild(link); 
}

In your case, since you use arrays in array instead of objects in array, You will skip the header part, but you could add the column names yourself by putting this instead of that part:

// headers
csvContent += '"Column name 1" "Column name 2" "Column name 3"\n';

The secret is that a space separates the columns in the csv file, and we put the column values in the double quotes to allow spaces, and escape any double quotes in the values themselves.

Also note that I replace null values with empty string, because that suited my needs, but you can change that and replace it with anything you like.

How to show an alert box in PHP?

change your output from

 echo '<script language="javascript>';

to

 echo '<script type="text/javascript">';

you forgot double quotes... and use the type tag

Using CSS td width absolute, position

You're better off using table-layout: fixed

Auto is the default value and with large tables can cause a bit of client side lag as the browser iterates through it to check all the sizes fit.

Fixed is far better and renders quicker to the page. The structure of the table is dependent on the tables overall width and the width of each of the columns.

Here it is applied to the original example: JSFIDDLE, You'll note that the remaining columns are crushed and overlapping their content. We can fix that with some more CSS (all I've had to do is add a class to the first TR):

    table {
        width: 100%;
        table-layout: fixed;
    }

    .header-row > td {
        width: 100px;
    }

    td.rhead {
        width: 300px
    }

Seen in action here: JSFIDDLE

Initialize empty vector in structure - c++

Like this:

#include <string>
#include <vector>

struct user
{
    std::string username;
    std::vector<unsigned char> userpassword;
};

int main()
{
    user r;   // r.username is "" and r.userpassword is empty
    // ...
}

Find and copy files

The reason for that error is that you are trying to copy a folder which requires -r option also to cp Thanks

How to call loading function with React useEffect only once

we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:

import { useFetching } from "react-concurrent";

const app = () => {
  const { data, isLoading, error , refetch } = useFetching(() =>
    fetch("http://example.com"),
  );
};

You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent

Why is the use of alloca() not considered good practice?

A place where alloca() is especially dangerous than malloc() is the kernel - kernel of a typical operating system has a fixed sized stack space hard-coded into one of its header; it is not as flexible as the stack of an application. Making a call to alloca() with an unwarranted size may cause the kernel to crash. Certain compilers warn usage of alloca() (and even VLAs for that matter) under certain options that ought to be turned on while compiling a kernel code - here, it is better to allocate memory in the heap that is not fixed by a hard-coded limit.

Pandas: sum DataFrame rows for given columns

Following syntax helped me when I have columns in sequence

awards_frame.values[:,1:4].sum(axis =1)

Writing an input integer into a cell

When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.

  1. The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
  2. The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
  3. The user does not type anything in but clicks OK regardless. The return value is a zero-length string.

If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.

    Dim returnVal As Variant

    returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")

    'if the user clicked Cancel, Close or Esc the False
    'is translated to the variant as a vbNullString
    Select Case True
        Case Len(returnVal) = 0
            'no value but user clicked OK - clear the target cell
            Range("A2").ClearContents
        Case Else
            'returned a value with OK, save it
            Range("A2") = returnVal
    End Select

¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.

How do I use a C# Class Library in a project?

You need to add a reference to your class library from your project. Right click on the references folder and click add reference. You can either browse for the DLL or, if your class libaray is a project in your solution you can add a project reference.

What are valid values for the id attribute in HTML?

No spaces, must begin with at least a char from a to z and 0 to 9.

Android Studio doesn't see device

Be sure that you have downloaded the correct API for the version you device is using. After updating your device's Android version or switching to a different device you may not have the correct API downloaded on Android Studio. To do this:

  1. Check your devices Android OS version by going to Settings>About Phone>Android Version

  2. Make sure you have the correct API installed in Android Studio in the SDK Manager

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

Bootstrap 4 navbar color

Update 2019

Remember that whatever CSS overrides you define must be the same CSS specificity or greater in order to properly override Bootstrap's CSS.

Bootstrap 4.1+

The Navbar is transparent by default. If you only want to change the background color, it can be done simply by applying the color to the <navbar class="bg-custom">, but remember that won't change the other colors such as the links, hover and dropdown menu colors.

Here's CSS that will change any relevant Navbar colors in Bootstrap 4...

/* change the background color */
.navbar-custom {
    background-color: #ff5500;
}
/* change the brand and text color */
.navbar-custom .navbar-brand,
.navbar-custom .navbar-text {
    color: rgba(255,255,255,.8);
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
    color: rgba(255,255,255,.5);
}
/* change the color of active or hovered links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:focus .nav-link,
.navbar-custom .nav-item:hover .nav-link {
    color: #ffffff;
}

Demo: http://www.codeply.com/go/U9I2byZ3tS


Override Navbar Light or Dark

If you're using the Bootstrap 4 Navbar navbar-light or navbar-dark classes, then use this in the overrides. For example, changing the Navbar link colors...

.navbar-light .nav-item.active .nav-link,
.navbar-light .nav-item:focus .nav-link,
.navbar-light .nav-item:hover .nav-link {
        color: #ffffff;
}

When making any Bootstrap customizations, you need to understand CSS Specificity. Overrides in your custom CSS need to use selectors that are as specific as the bootstrap.css. Read more


Transparent Navbar

Notice that the Bootstrap 4 Navbar is transparent by default. Use navbar-dark for dark/bold background colors, and use navbar-light if the navbar is a lighter color. This will effect the color of the text and color of the toggler icon as explained here.

Related: https://stackoverflow.com/a/18530995/171456

how to start stop tomcat server using CMD?

This is what I used to start and stop tomcat 7.0.29, using ant 1.8.2. Works fine for me, but leaves the control in the started server window. I have not tried it yet, but I think if I change the "/K" in the startup sequence to "/C", it may not even do that.

<target name="tomcat-stop">
    <exec dir="${appserver.home}/bin" executable="cmd">
        <arg line="/C start cmd.exe /C shutdown.bat"/>
    </exec>
</target>



<target name="tomcat-start" depends="tomcat-stop" >
    <exec dir="${appserver.home}/bin" executable="cmd">
        <arg line="/K start cmd.exe /C startup.bat"/>
    </exec>

</target>

Working with huge files in VIM

Old thread. But nevertheless( pun :) ).

 $less filename

less works efficiently if you don't want to edit and just look around which is the case for examining huge log files.

Search in less works like vi

Best part, it's available by default on most distros. So won't be problem for production environment as well.

How to update a claim in ASP.NET Identity?

I am using a .net core 2.2 app and used the following solution: in my statup.cs

public void ConfigureServices(IServiceCollection services)
        {
        ...
           services.AddIdentity<IdentityUser, IdentityRole>(options =>
               {
                  ...
               })
               .AddEntityFrameworkStores<AdminDbContext>()
               .AddDefaultTokenProviders()
               .AddSignInManager();

usage

  private readonly SignInManager<IdentityUser> _signInManager;


        public YourController(
                                    ...,
SignInManager<IdentityUser> signInManager)
        {
           ...
            _signInManager = signInManager;
        }

 public async Task<IActionResult> YourMethod() // <-NOTE IT IS ASYNC
        {
                var user = _userManager.FindByNameAsync(User.Identity.Name).Result;
                var claimToUse = ClaimsHelpers.CreateClaim(ClaimTypes.ActiveCompany, JsonConvert.SerializeObject(cc));
                var claimToRemove = _userManager.GetClaimsAsync(user).Result
                    .FirstOrDefault(x => x.Type == ClaimTypes.ActiveCompany.ToString());
                if (claimToRemove != null)
                {
                    var result = _userManager.ReplaceClaimAsync(user, claimToRemove, claimToUse).Result;
                    await _signInManager.RefreshSignInAsync(user); //<--- THIS
                }
                else ...
              

VSCode single to double quote automatic replace

It looks like it is a bug open for this issue: Prettier Bug

None of above solution worked for me. The only thing that worked was, adding this line of code in package.json:

"prettier": {
    "singleQuote": true
  },

How to get a parent element to appear above child

Some of these answers do work, but setting position: absolute; and z-index: 10; seemed pretty strong just to achieve the required effect. I found the following was all that was required, though unfortunately, I've not been able to reduce it any further.

HTML:

<div class="wrapper">
    <div class="parent">
        <div class="child">
            ...
        </div>
    </div>
</div>

CSS:

.wrapper {
    position: relative;
    z-index: 0;
}

.child {
    position: relative;
    z-index: -1;
}

I used this technique to achieve a bordered hover effect for image links. There's a bit more code here but it uses the concept above to show the border over the top of the image.

http://jsfiddle.net/g7nP5/

Can you change a path without reloading the controller in AngularJS?

Add following inside head tag

  <script type="text/javascript">
    angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
  </script>

This will prevent the reload.

How can I specify my .keystore file with Spring Boot and Tomcat?

Starting with Spring Boot 1.2, you can configure SSL using application.properties or application.yml. Here's an example for application.properties:

server.port = 8443
server.ssl.key-store = classpath:keystore.jks
server.ssl.key-store-password = secret
server.ssl.key-password = another-secret

Same thing with application.yml:

server:
  port: 8443
  ssl:
    key-store: classpath:keystore.jks
    key-store-password: secret
    key-password: another-secret

Here's a link to the current reference documentation.

Python strftime - date without leading 0?

Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero.

For example %Y/%-m/%-d.

This only works on Unix (Linux, OS X), not Windows (including Cygwin). On Windows, you would use #, e.g. %Y/%#m/%#d.

Intel's HAXM equivalent for AMD on Windows OS

Posting a new answer since it is 2019.

TLDR: AMD is now supported on both Windows and Linux via WHPX and yes, Genymotion is faster as it is using x86 architecture virtualization.

From the Android docs (January 2019):

Though we recommend using HAXM on Windows, it is possible to use Windows Hypervisor Platform (WHPX) with the emulator. You should use WHPX with the emulator if you are using an AMD CPU or if you need to use Hyper-V at the same time.

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings:

Intel CPU: VT-x must be enabled. AMD CPU: Virtualization or SVM must be enabled.

Diff from 2016:

Virtualization extension requirements

Before attempting to use acceleration, you should first determine if your CPU supports one of the following virtualization extensions technologies:

  1. Intel Virtualization Technology (VT, VT-x, vmx) extensions
  2. AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

Most modern computers do. If you use an older computer and you're not sure, consult the specifications from the manufacturer of your CPU to determine if it supports virtualization extensions. If your CPU doesn't support one of these virtualization technologies, then you can't use VM acceleration.

Virtualization extensions are typically enabled through your computer BIOS and are frequently turned off by default. Check the documentation for your motherboard to find out how to enable virtualization extensions.

How does strcmp() work?

I found this on web.

http://www.opensource.apple.com/source/Libc/Libc-262/ppc/gen/strcmp.c

int strcmp(const char *s1, const char *s2)
{
    for ( ; *s1 == *s2; s1++, s2++)
        if (*s1 == '\0')
            return 0;
    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}

No newline after div?

Have you considered using span instead of div? It is the in-line version of div.

Get Month name from month number

This should return month text (January - December) from the month index (1-12)

int monthNumber = 1; //1-12  
string monthName = new DateTimeFormatInfo().GetMonthName(monthNumber);

How to perform grep operation on all files in a directory?

In Linux, I normally use this command to recursively grep for a particular text within a dir

grep -rni "string" *

where,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

How to get the caller class in Java

To get caller/called class name use below code, it works fine for me.

String callerClassName = new Exception().getStackTrace()[1].getClassName();
String calleeClassName = new Exception().getStackTrace()[0].getClassName();

Press Enter to move to next control

private void txt_invoice_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_date.Focus();
    }

    private void txt_date_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_patientname.Focus();
    }

}

How to find memory leak in a C++ code/project?

  1. Download Debugging Tools for Windows.
  2. Use the gflags utility to turn on user-mode stack traces.
  3. Use UMDH to take multiple snapshots of your program's memory. Take a snapshot before memory gets allocated, and take a second snapshot after a point at which you believe that your program has leaked memory. You might want to add pauses or prompts in your program to give you a chance to run UMDH and take the snapshots.
  4. Run UMDH again, this time in its mode that does a diff between the two snapshots. It will then generate a report containing the call stacks of suspected memory leaks.
  5. Restore your previous gflags settings when you're done.

UMDH will give you more information than the CRT debug heap because it is watching memory allocations across your entire process; it can even tell you if third-party components are leaking.

input type="submit" Vs button tag are they interchangeable?

I don't know if this is a bug or a feature, but there is very important (for some cases at least) difference I found: <input type="submit"> creates key value pair in your request and <button type="submit"> doesn't. Tested in Chrome and Safari.

So when you have multiple submit buttons in your form and want to know which one was clicked - do not use button, use input type="submit" instead.

Django DB Settings 'Improperly Configured' Error

In your python shell/ipython do:

from django.conf import settings

settings.configure()

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Change size of text in text input tag?

<input style="font-size:25px;" type="text"/>

The above code changes the font size to 25 pixels.

How can I scale an entire web page with CSS?

This is a rather late answer, but you can use

body {
   transform: scale(1.1);
   transform-origin: 0 0;
   // add prefixed versions too.
}

to zoom the page by 110%. Although the zoom style is there, Firefox still does not support it sadly.

Also, this is slightly different than your zoom. The css transform works like an image zoom, so it will enlarge your page but not cause reflow, etc.


Edit updated the transform origin.

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

How do I change an HTML selected option using JavaScript?

I believe that the blog post JavaScript Beginners – Select a dropdown option by value might help you.

<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a>

function selectItemByValue(elmnt, value){

  for(var i=0; i < elmnt.options.length; i++)
  {
    if(elmnt.options[i].value === value) {
      elmnt.selectedIndex = i;
      break;
    }
  }
}

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

Using grep and sed to find and replace a string

If you are to replace a fixed string or some pattern, I would also like to add the bash builtin pattern string replacement variable substitution construct. Instead of describing it myself, I am quoting the section from the bash manual:

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in pathname expansion. parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

How to change UINavigationBar background color from the AppDelegate

For doing this in iOS 7:

[[UINavigationBar appearance] setBarTintColor:myColor];