Programs & Examples On #Date formatting

Date formatting is the process of displaying, handling or converting a calendar date to a specific format.

Get String in YYYYMMDD format from JS date object?

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code
    }

How to format a duration in java? (e.g format H:MM:SS)

If you don't want to drag in libraries, it's simple enough to do yourself using a Formatter, or related shortcut eg. given integer number of seconds s:

  String.format("%d:%02d:%02d", s / 3600, (s % 3600) / 60, (s % 60));

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.

Date.prototype.getISOTimezoneOffset = function () {
    const offset = this.getTimezoneOffset();
    return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}

Date.prototype.toISOLocaleString = function () {
    return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
        this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
        this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
        this.getMilliseconds().leftPad(3);
}

Number.prototype.leftPad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) {
        s = "0" + s;
    }
    return s;
}

Example usage:

var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"

I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.

(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

from now, unix timestamp param,

function timeSince(ts){
    now = new Date();
    ts = new Date(ts*1000);
    var delta = now.getTime() - ts.getTime();

    delta = delta/1000; //us to s

    var ps, pm, ph, pd, min, hou, sec, days;

    if(delta<=59){
        ps = (delta>1) ? "s": "";
        return delta+" second"+ps
    }

    if(delta>=60 && delta<=3599){
        min = Math.floor(delta/60);
        sec = delta-(min*60);
        pm = (min>1) ? "s": "";
        ps = (sec>1) ? "s": "";
        return min+" minute"+pm+" "+sec+" second"+ps;
    }

    if(delta>=3600 && delta<=86399){
        hou = Math.floor(delta/3600);
        min = Math.floor((delta-(hou*3600))/60);
        ph = (hou>1) ? "s": "";
        pm = (min>1) ? "s": "";
        return hou+" hour"+ph+" "+min+" minute"+pm;
    } 

    if(delta>=86400){
        days = Math.floor(delta/86400);
        hou =  Math.floor((delta-(days*86400))/60/60);
        pd = (days>1) ? "s": "";
        ph = (hou>1) ? "s": "";
        return days+" day"+pd+" "+hou+" hour"+ph;
    }

}

Convert timestamp to date in MySQL query

Try:

SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name

It will format timestamp in milliseconds to yyyy-mm-dd string.

How do I format a date as ISO 8601 in moment.js?

Also possible with vanilla JS

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

Is there a date format to display the day of the week in java?

Yep - 'E' does the trick

http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-E");
System.out.println(df.format(date));

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

How to format a JavaScript date

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

Oracle's default date format is YYYY-MM-DD, WHY?

Oracle has both the Date and the Timestamp data types.

According to Oracle documentation, there are differences in data size between Date and Timestamp, so when the intention is to have a Date only field it makes sense to show the Date formatting. Also, "It does not have fractional seconds or a time zone." - so it is not the best choice when timestamp information is required.

The Date field can be easily formatted to show the time component in the Oracle SQL Developer - Date query ran in PL/SQL Developer shows time, but does not show in Oracle SQL Developer. But it won't show the fractional seconds or the time zone - for this you need Timestamp data type.

Return date as ddmmyyyy in SQL Server

SELECT REPLACE(CONVERT(VARCHAR(10), THEDATE, 103), '/', '') AS [DDMMYYYY]

As seen here: http://www.sql-server-helper.com/tips/date-formats.aspx

How to convert date in to yyyy-MM-dd Format?

String s;
Format formatter;
Date date = new Date();

// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);

Date formatting in WPF datagrid

I know the accepted answer is quite old, but there is a way to control formatting with AutoGeneratColumns :

First create a function that will trigger when a column is generated :

<DataGrid x:Name="dataGrid" AutoGeneratedColumns="dataGrid_AutoGeneratedColumns" Margin="116,62,10,10"/>

Then check if the type of the column generated is a DateTime and just change its String format to "d" to remove the time part :

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if(YourColumn == typeof(DateTime))
            {
                e.Column.ClipboardContentBinding.StringFormat = "d";
            }
        }

How do I get the current date in JavaScript?

If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out momentjs. Terrific library - and only 5KB. http://momentjs.com/

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

you can use this method just pass your date to it

-(NSString *)getDateFromString:(NSString *)string
{

    NSString * dateString = [NSString stringWithFormat: @"%@",string];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"your current date format"];
    NSDate* myDate = [dateFormatter dateFromString:dateString];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"your desired format"];
    NSString *stringFromDate = [formatter stringFromDate:myDate];

    NSLog(@"%@", stringFromDate);
    return stringFromDate;
}

Should a RESTful 'PUT' operation return something

seems ok... though I'd think a rudimentary indication of success/failure/time posted/# bytes received/etc. would be preferable.

edit: I was thinking along the lines of data integrity and/or record-keeping; metadata such as an MD5 hash or timestamp for time received may be helpful for large datafiles.

pandas convert some columns into rows

UPDATE
From v0.20, melt is a first order function, you can now use

df.melt(id_vars=["location", "name"], 
        var_name="Date", 
        value_name="Value")

  location    name        Date  Value
0        A  "test"    Jan-2010     12
1        B   "foo"    Jan-2010     18
2        A  "test"    Feb-2010     20
3        B   "foo"    Feb-2010     20
4        A  "test"  March-2010     30
5        B   "foo"  March-2010     25

OLD(ER) VERSIONS: <0.20

You can use pd.melt to get most of the way there, and then sort:

>>> df
  location  name  Jan-2010  Feb-2010  March-2010
0        A  test        12        20          30
1        B   foo        18        20          25
>>> df2 = pd.melt(df, id_vars=["location", "name"], 
                  var_name="Date", value_name="Value")
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
1        B   foo    Jan-2010     18
2        A  test    Feb-2010     20
3        B   foo    Feb-2010     20
4        A  test  March-2010     30
5        B   foo  March-2010     25
>>> df2 = df2.sort(["location", "name"])
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
2        A  test    Feb-2010     20
4        A  test  March-2010     30
1        B   foo    Jan-2010     18
3        B   foo    Feb-2010     20
5        B   foo  March-2010     25

(Might want to throw in a .reset_index(drop=True), just to keep the output clean.)

Note: pd.DataFrame.sort has been deprecated in favour of pd.DataFrame.sort_values.

How to set multiple commands in one yaml file with Kubernetes?

I am not sure if the question is still active but due to the fact that I did not find the solution in the above answers I decided to write it down.

I use the following approach:

readinessProbe:
  exec:
    command:
    - sh
    - -c
    - |
      command1
      command2 && command3

I know my example is related to readinessProbe, livenessProbe, etc. but suspect the same case is for the container commands. This provides flexibility as it mirrors a standard script writing in Bash.

Collapsing Sidebar with Bootstrap

Bootstrap 3

Yes, it's possible. This "off-canvas" example should help to get you started.

https://codeply.com/p/esYgHWB2zJ

Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.

/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
  }
  .row-offcanvas-right
  .sidebar-offcanvas {
    right: -41.6%;
  }

  .row-offcanvas-left
  .sidebar-offcanvas {
    left: -41.6%;
  }
  .row-offcanvas-right.active {
    right: 41.6%;
  }
  .row-offcanvas-left.active {
    left: 41.6%;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 41.6%;
  }
  #sidebar {
    padding-top:0;
  }
}

Also, there are several more Bootstrap sidebar examples here


Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?

How to access JSON decoded array in PHP

As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:

$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..

If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:

echo $myArray[0]->id;

Counting number of characters in a file through shell script

I would have thought that it would be better to use stat to find the size of a file, since the filesystem knows it already, rather than causing the whole file to have to be read with awk or wc - especially if it is a multi-GB file or one that may be non-resident in the file-system on an HSM.

stat -c%s file

Yes, I concede it doesn't account for multi-byte characters, but would add that the OP has never clarified whether that is/was an issue.

Getting a map() to return a list in Python 3.x

Converting my old comment for better visibility: For a "better way to do this" without map entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it's still faster). For example, in ipython microbenchmarks converting 45 inputs:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it's still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).

HTTP GET in VB.NET

You should try the HttpWebRequest class.

How to reload a page using Angularjs?

$scope.rtGo = function(){
            $window.sessionStorage.removeItem('message');
            $window.sessionStorage.removeItem('status');
        }

Filter data.frame rows by a logical condition

Sometimes the column you want to filter may appear in a different position than column index 2 or have a variable name.

In this case, you can simply refer the column name you want to filter as:

columnNameToFilter = "cell_type"
expr[expr[[columnNameToFilter]] == "hesc", ]

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Here is part of a line in my code that brought the warning up in NetBeans:

$page = (!empty($_GET['p'])) 

After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:

$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))

What is the difference between . (dot) and $ (dollar sign)?

The short and sweet version:

  • ($) calls the function which is its left-hand argument on the value which is its right-hand argument.
  • (.) composes the function which is its left-hand argument on the function which is its right-hand argument.

How to concatenate two strings in SQL Server 2005

To concatenate two strings in 2008 or prior:

SELECT ISNULL(FirstName, '') + ' ' + ISNULL(SurName, '')

good to use ISNULL because "String + NULL" will give you a NULL only

One more thing: Make sure you are concatenating strings otherwise use a CAST operator:

SELECT 2 + 3 

Will give 5

SELECT '2' + '3'

Will give 23

Flutter: Run method on Widget build complete

Try SchedulerBinding,

 SchedulerBinding.instance
                .addPostFrameCallback((_) => setState(() {
              isDataFetched = true;
            }));

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

How to do a LIKE query with linq?

You can use contains:

string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2

Visual Studio 2017: Display method references

CodeLens is not available in the Community editions. You need Professional or higher to switch it on.

In VS2015, one way to "get" CodeLens was to install the SQL Server Developer Tools (SSDT) but I believe this has been rectified in VS2017.

Still you can get all method reference by right clicking on the method and "Find All references"

enter image description here

How to use range-based for() loop with std::map?

In C++17 this is called structured bindings, which allows for the following:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
  std::cout << k << "=" << v << "\n";
}

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

In my scenario the build service was not using the same user account that I imported the key with using sn.exe.

After changing the account to my administrator account, everything is working just fine.

Max size of an iOS application

4GB's is the maximum size your iOS app can be.

As of January 26, 2017

App Size for iOS (& tvOS) only

Your app’s total uncompressed size must be less than 4GB. Each Mach-O executable file (for example, app_name.app/app_name) must not exceed these limits:

  • For apps whose MinimumOSVersion is less than 7.0: maximum of 80 MB for the total of all __TEXT sections in the binary.
  • For apps whose MinimumOSVersion is 7.x through 8.x: maximum of 60 MB per slice for the __TEXT section of each architecture slice in the binary.
  • For apps whose MinimumOSVersion is 9.0 or greater: maximum of 500 MB for the total of all __TEXT sections in the binary.

However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found at iTunes Connect Developer Guide: Submitting the App to App Review.


As of February 12, 2015

(iOS only) App Size

iOS App binary files can be as large as 4 GB, but each executable file (app_name.app/app_name) must not exceed 60 MB. Additionally, the total uncompressed size of the app must be less than 4 billion bytes. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found on page 77 of the iTunes Connect Developer Guide.


As of December 12, 2013

(iOS only) App Size

iOS App binary files can be as large as 2 GB, but the executable file (app_name.app/app_name) cannot exceed 60MB. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found on page 58 of the iTunes Connect Developer Guide.


As of June 6, 2013

The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 237 of the guide.


As of January 10, 2013

The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 208 of the guide.


As of October 31, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 206 of the guide. Thanks to comment from Ozair Kafray.


As of July 19, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 214 of the guide. Thanks to comment from marsbear. In addition, the document has moved here:

http://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/iTunesConnect_Guide.pdf


As of July 13, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.


As of March 29, 2012 (version 7.4)

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.


As of January 23, 2012 (version 7.3)

The above information is still the same, however, it can be found on page 172 of the guide.


As of October 17, 2011 (version 7.2)

The above information is still the same, however, it can be found on page 180 of the guide. Thanks to comment from Luke for the update.


As of September 22, 2011 (version 7.1)

The above information is still the same, however, it can be found on page 179 of the guide. Thanks to comment from Saxon Druce for the update.

How to avoid warning when introducing NAs by coercion

I have slightly modified the jangorecki function for the case where we may have a variety of values that cannot be converted to a number. In my function, a template search is performed and if the template is not found, FALSE is returned.! before gperl, it means that we need those vector elements that do not match the template. The rest is similar to the as.num function. Example:

as.num.pattern <- function(x, pattern){
  stopifnot(is.character(x))
  na = !grepl(pattern, x)
  x[na] = -Inf
  x = as.numeric(x)
  x[na] = NA_real_
  x
}

as.num.pattern(c('1', '2', '3.43', 'char1', 'test2', 'other3', '23/40', '23, 54 cm.'))

[1] 1.00 2.00 3.43   NA   NA   NA   NA   NA

CMake output/build directory

It sounds like you want an out of source build. There are a couple of ways you can create an out of source build.

  1. Do what you were doing, run

    cd /path/to/my/build/folder
    cmake /path/to/my/source/folder
    

    which will cause cmake to generate a build tree in /path/to/my/build/folder for the source tree in /path/to/my/source/folder.

    Once you've created it, cmake remembers where the source folder is - so you can rerun cmake on the build tree with

    cmake /path/to/my/build/folder
    

    or even

    cmake .
    

    if your current directory is already the build folder.

  2. For CMake 3.13 or later, use these options to set the source and build folders

    cmake -B/path/to/my/build/folder -S/path/to/my/source/folder
    
  3. For older CMake, use some undocumented options to set the source and build folders:

    cmake -B/path/to/my/build/folder -H/path/to/my/source/folder
    

    which will do exactly the same thing as (1), but without the reliance on the current working directory.

CMake puts all of its outputs in the build tree by default, so unless you are liberally using ${CMAKE_SOURCE_DIR} or ${CMAKE_CURRENT_SOURCE_DIR} in your cmake files, it shouldn't touch your source tree.

The biggest thing that can go wrong is if you have previously generated a build tree in your source tree (i.e. you have an in source build). Once you've done this the second part of (1) above kicks in, and cmake doesn't make any changes to the source or build locations. Thus, you cannot create an out-of-source build for a source directory with an in-source build. You can fix this fairly easily by removing (at a minimum) CMakeCache.txt from the source directory. There are a few other files (mostly in the CMakeFiles directory) that CMake generates that you should remove as well, but these won't cause cmake to treat the source tree as a build tree.

Since out-of-source builds are often more desirable than in-source builds, you might want to modify your cmake to require out of source builds:

# Ensures that we do an out of source build

MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${CMAKE_BINARY_DIR}" insource)
     GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${PARENTDIR}" insourcesubdir)
    IF(insource OR insourcesubdir)
        MESSAGE(FATAL_ERROR "${MSG}")
    ENDIF(insource OR insourcesubdir)
ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD)

MACRO_ENSURE_OUT_OF_SOURCE_BUILD(
    "${CMAKE_PROJECT_NAME} requires an out of source build."
)

The above macro comes from a commonly used module called MacroOutOfSourceBuild. There are numerous sources for MacroOutOfSourceBuild.cmake on google but I can't seem to find the original and it's short enough to include here in full.

Unfortunately cmake has usually written a few files by the time the macro is invoked, so although it will stop you from actually performing the build you will still need to delete CMakeCache.txt and CMakeFiles.

You may find it useful to set the paths that binaries, shared and static libraries are written to - in which case see how do I make cmake output into a 'bin' dir? (disclaimer, I have the top voted answer on that question...but that's how I know about it).

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

Line break in HTML with '\n'

Using white-space: pre-line allows you to input the text directly in the HTML with line breaks without having to use \n

If you use the innerText property of the element via JavaScript on a non-pre element e.g. a <div>, the \n values will be replaced with <br> in the DOM by default

  • innerText: replaces \n with <br>
  • innerHTML, textContent: require the use of styling white-space

It depends on how your applying the text, but there are a number of options

const node = document.createElement('div');
node.innerText = '\n Test \n One '

Update TextView Every Second

If you want to show time on textview then better use Chronometer or TextClock

Using Chronometer:This was added in API 1. It has lot of option to customize it.

Your xml

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp" />

Your activity

Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();

Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.

Your xml

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="44sp"
    android:textStyle="bold" />

Thats it, you are done.

You can use any of these two widgets. This will make your life easy.

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

Difference between private, public, and protected inheritance

It has to do with how the public members of the base class are exposed from the derived class.

  • public -> base class's public members will be public (usually the default)
  • protected -> base class's public members will be protected
  • private -> base class's public members will be private

As litb points out, public inheritance is traditional inheritance that you'll see in most programming languages. That is it models an "IS-A" relationship. Private inheritance, something AFAIK peculiar to C++, is an "IMPLEMENTED IN TERMS OF" relationship. That is you want to use the public interface in the derived class, but don't want the user of the derived class to have access to that interface. Many argue that in this case you should aggregate the base class, that is instead of having the base class as a private base, make in a member of derived in order to reuse base class's functionality.

Setting a system environment variable from a Windows batch file?

Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/~vefatica. Not exactly recent ('98) but still working on Windows 7 x64.

How to output in CLI during execution of PHP Unit tests?

In short, phpunit supresses STDOUT. It writes to STDERR by default, unless you add --verbose or --debug . You can do one of those things:

  • print your debug output to STDERR instead
  • var_dump your debug as usual but add --verbose to the phpunit command line
  • var_dump your debug as usual but add a line ob_flush(); beneath it
  • use the correct commands in phpunit for testing exactly what you're trying to test here

Obviously, the last thing is the Good Thing to do, and the rest are quick temporary hacks.

How to design RESTful search/filtering?

Don't fret too much if your initial API is fully RESTful or not (specially when you are just in the alpha stages). Get the back-end plumbing to work first. You can always do some sort of URL transformation/re-writing to map things out, refining iteratively until you get something stable enough for widespread testing ("beta").

You can define URIs whose parameters are encoded by position and convention on the URIs themselves, prefixed by a path you know you'll always map to something. I don't know PHP, but I would assume that such a facility exists (as it exists in other languages with web frameworks):

.ie. Do a "user" type of search with param[i]=value[i] for i=1..4 on store #1 (with value1,value2,value3,... as a shorthand for URI query parameters):

1) GET /store1/search/user/value1,value2,value3,value4

or

2) GET /store1/search/user,value1,value2,value3,value4

or as follows (though I would not recommend it, more on that later)

3) GET /search/store1,user,value1,value2,value3,value4

With option 1, you map all URIs prefixed with /store1/search/user to the search handler (or whichever the PHP designation) defaulting to do searches for resources under store1 (equivalent to /search?location=store1&type=user.

By convention documented and enforced by the API, parameters values 1 through 4 are separated by commas and presented in that order.

Option 2 adds the search type (in this case user) as positional parameter #1. Either option is just a cosmetic choice.

Option 3 is also possible, but I don't think I would like it. I think the ability of search within certain resources should be presented in the URI itself preceding the search itself (as if indicating clearly in the URI that the search is specific within the resource.)

The advantage of this over passing parameters on the URI is that the search is part of the URI (thus treating a search as a resource, a resource whose contents can - and will - change over time.) The disadvantage is that parameter order is mandatory.

Once you do something like this, you can use GET, and it would be a read-only resource (since you can't POST or PUT to it - it gets updated when it's GET'ed). It would also be a resource that only comes to exist when it is invoked.

One could also add more semantics to it by caching the results for a period of time or with a DELETE causing the cache to be deleted. This, however, might run counter to what people typically use DELETE for (and because people typically control caching with caching headers.)

How you go about it would be a design decision, but this would be the way I'd go about. It is not perfect, and I'm sure there will be cases where doing this is not the best thing to do (specially for very complex search criteria).

runOnUiThread in fragment

Use a Kotlin extension function

fun Fragment?.runOnUiThread(action: () -> Unit) {
    this ?: return
    if (!isAdded) return // Fragment not attached to an Activity
    activity?.runOnUiThread(action)
}

Then, in any Fragment you can just call runOnUiThread. This keeps calls consistent across activities and fragments.

runOnUiThread {
    // Call your code here
}

NOTE: If Fragment is no longer attached to an Activity, callback will not be called and no exception will be thrown

If you want to access this style from anywhere, you can add a common object and import the method:

object ThreadUtil {
    private val handler = Handler(Looper.getMainLooper())

    fun runOnUiThread(action: () -> Unit) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            handler.post(action)
        } else {
            action.invoke()
        }
    }
}

How to prevent Google Colab from disconnecting?

the following LATEST solution works for me:

function ClickConnect(){
  colab.config
  console.log("Connnect Clicked - Start"); 
  document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click();
  console.log("Connnect Clicked - End");
};
setInterval(ClickConnect, 60000)

CURRENT_TIMESTAMP in milliseconds

Easiest way I found to receive current time in milliseconds in MySql:

SELECT (UNIX_TIMESTAMP(NOW(3)) * 1000)

Since MySql 5.6.

Kill all processes for a given user

Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!

pkill -9 -u `id -u username`

Note: if you want to be nice remove -9, but it will not kill all kinds of processes.

Python 2: AttributeError: 'list' object has no attribute 'strip'

strip() is a method for strings, you are calling it on a list, hence the error.

>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False

To do what you want, just do

>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]

Since, you want the elements to be in a single list (and not a list of lists), you have two options.

  1. Create an empty list and append elements to it.
  2. Flatten the list.

To do the first, follow the code:

>>> l1 = []
>>> for elem in l:
        l1.extend(elem.strip().split(';'))  
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

To do the second, use itertools.chain

>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

How Do I Uninstall Yarn

Didn't see the answer that worked for me, so here it is: On my OSX system I found yarn at ~/.yarn/bin/yarn. rm -rf ~/.yarn took care of it.

Which characters need to be escaped when using Bash?

I noticed that bash automatically escapes some characters when using auto-complete.

For example, if you have a directory named dir:A, bash will auto-complete to dir\:A

Using this, I runned some experiments using characters of the ASCII table and derived the following lists:

Characters that bash escapes on auto-complete: (includes space)

 !"$&'()*,:;<=>?@[\]^`{|}

Characters that bash does not escape:

#%+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~

(I excluded /, as it cannot be used in directory names)

Execution failed app:processDebugResources Android Studio

In my case, I changed the android section in build.gradle and the problem faded away:

android {
compileSdkVersion 28

lintOptions {
    disable 'InvalidPackage'
}

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "app.ozel"
    minSdkVersion 16
    targetSdkVersion 28
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug
    }
}

}

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Validating input using java.util.Scanner

One idea:

try {
    int i = Integer.parseInt(myString);
    if (i < 0) {
        // Error, negative input
    }
} catch (NumberFormatException e) {
    // Error, not a number.
}

There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...

Limiting the number of characters in a string, and chopping off the rest

Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.

Pyspark: display a spark data frame in a table format

Let's say we have the following Spark DataFrame:

df = sqlContext.createDataFrame(
    [
        (1, "Mark", "Brown"), 
        (2, "Tom", "Anderson"), 
        (3, "Joshua", "Peterson")
    ], 
    ('id', 'firstName', 'lastName')
)

There are typically three different ways you can use to print the content of the dataframe:

Print Spark DataFrame

The most common way is to use show() function:

>>> df.show()
+---+---------+--------+
| id|firstName|lastName|
+---+---------+--------+
|  1|     Mark|   Brown|
|  2|      Tom|Anderson|
|  3|   Joshua|Peterson|
+---+---------+--------+

Print Spark DataFrame vertically

Say that you have a fairly large number of columns and your dataframe doesn't fit in the screen. You can print the rows vertically - For example, the following command will print the top two rows, vertically, without any truncation.

>>> df.show(n=2, truncate=False, vertical=True)
-RECORD 0-------------
 id        | 1        
 firstName | Mark     
 lastName  | Brown    
-RECORD 1-------------
 id        | 2        
 firstName | Tom      
 lastName  | Anderson 
only showing top 2 rows

Convert to Pandas and print Pandas DataFrame

Alternatively, you can convert your Spark DataFrame into a Pandas DataFrame using .toPandas() and finally print() it.

>>> df_pd = df.toPandas()
>>> print(df_pd)
   id firstName  lastName
0   1      Mark     Brown
1   2       Tom  Anderson
2   3    Joshua  Peterson

Note that this is not recommended when you have to deal with fairly large dataframes, as Pandas needs to load all the data into memory. If this is the case, the following configuration will help when converting a large spark dataframe to a pandas one:

spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")

For more details you can refer to my blog post Speeding up the conversion between PySpark and Pandas DataFrames

Can I position an element fixed relative to parent?

It's an old post but i'll leave here my javascript solution just in case someone need it.


_x000D_
_x000D_
// you only need this function_x000D_
function sticky( _el ){_x000D_
  _el.parentElement.addEventListener("scroll", function(){_x000D_
    _el.style.transform = "translateY("+this.scrollTop+"px)";_x000D_
  });_x000D_
}_x000D_
_x000D_
_x000D_
// how to make it work:_x000D_
// get the element you want to be sticky_x000D_
var el = document.querySelector("#blbl > div");_x000D_
// give the element as argument, done._x000D_
sticky(el);
_x000D_
#blbl{_x000D_
  position:relative;_x000D_
  height:200px;  _x000D_
  overflow: auto;_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
#blbl > div{_x000D_
  position:absolute; _x000D_
  padding:50px; _x000D_
  top:10px; _x000D_
  left:10px; _x000D_
  background: #f00_x000D_
}
_x000D_
<div id="blbl" >_x000D_
    <div><!-- sticky div --></div> _x000D_
_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
    <br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Notes

  1. I used transform: translateY(@px) because it should be lightweight to compute, high-performance-animations

  2. I only tried this function with modern browsers, it won't work for old browsers where vendors are required (and IE of course)

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Python: Converting from ISO-8859-1/latin1 to UTF-8

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

MD5 is 128 bits but why is it 32 characters?

That's 32 hex characters - 1 hex character is 4 bits.

Finding all the subsets of a set

You dont have to mess with recursion and other complex algorithms. You can find all subsets using bit patterns (decimal to binary) of all numbers between 0 and 2^(N-1). Here N is cardinality or number-of-items in that set. The technique is explained here with an implementation and demo.

http://codeding.com/?article=12

Why Doesn't C# Allow Static Methods to Implement an Interface?

FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.

Android, How can I Convert String to Date?

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

Javascript to check whether a checkbox is being checked or unchecked

function CHeck(){
    var ChkBox = document.getElementById("CheckBox1");
    alert(ChkBox.Checked);
}

<asp:CheckBox ID="CheckBox1" runat="server" onclick="CHeck()" />

python pip: force install ignoring dependencies

When I were trying install librosa package with pip (pip install librosa), this error were appeared:

ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

I tried to remove llvmlite, but pip uninstall could not remove it. So, I used capability of ignore of pip by this code:

pip install librosa --ignore-installed llvmlite

Indeed, you can use this rule for ignoring a package you don't want to consider:

pip install {package you want to install} --ignore-installed {installed package you don't want to consider}

I lose my data when the container exits

None of the answers address the point of this design choice. I think docker works this way to prevent these 2 errors:

  • Repeated restart
  • Partial error

How to replace innerHTML of a div using jQuery?

The html() function can take strings of HTML, and will effectively modify the .innerHTML property.

$('#regTitle').html('Hello World');

However, the text() function will change the (text) value of the specified element, but keep the html structure.

$('#regTitle').text('Hello world'); 

How to call two methods on button's onclick method in HTML or JavaScript?

Hi,

You can also do as like below... In this way, your both functions should call and if both functions return true then it will return true else return false.

<input type="button" 
     onclick="var valFunc1 = func1(); var valFunc2 = func2(); if(valFunc1 == true && valFunc2 ==true) {return true;} else{return false;}" 
     value="Call2Functions" />

Thank you, Vishal Patel

Razor View Without Layout

Use:

@{
    Layout = null;
 }

to get rid of the layout specified in _ViewStart.

Bootstrap Modal before form Submit

You can use browser default prompt window. Instead of basic <input type="submit" (...) > try:

<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>

Hexadecimal To Decimal in Shell Script

Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.

One more that's not on his list:

[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816

But if all you want to do is subtract, why bother changing the input to base 10?

[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$ 

The dc command is "desk calc". It will also take input from stdin, like bc, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.

In the commands above we've got the following:

  • 16i -- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.
  • BFCA3000 -- your initial number
  • 17FF -- a random hex number I picked to subtract from your initial number
  • - -- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stack
  • p -- print the last item on the stack. This doesn't change the stack, so...
  • 10o -- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".
  • p -- print the last item on the stack again ... this time in hex.

You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.

how to Call super constructor in Lombok

Lombok does not support that also indicated by making any @Value annotated class final (as you know by using @NonFinal).

The only workaround I found is to declare all members final yourself and use the @Data annotation instead. Those subclasses need to be annotated by @EqualsAndHashCode and need an explicit all args constructor as Lombok doesn't know how to create one using the all args one of the super class:

@Data
public class A {
    private final int x;
    private final int y;
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }
}

Especially the constructors of the subclasses make the solution a little untidy for superclasses with many members, sorry.

How to keep the console window open in Visual C++?

Another option is to use

#include <process.h>
system("pause");

Though this is not very portable because it will only work on Windows, but it will automatically print

Press any key to continue...

Escaping HTML strings with jQuery

All solutions are useless if you dont prevent re-escape, e.g. most solutions would keep escaping & to &amp;.

escapeHtml = function (s) {
    return s ? s.replace(
        /[&<>'"]/g,
        function (c, offset, str) {
            if (c === "&") {
                var substr = str.substring(offset, offset + 6);
                if (/&(amp|lt|gt|apos|quot);/.test(substr)) {
                    // already escaped, do not re-escape
                    return c;
                }
            }
            return "&" + {
                "&": "amp",
                "<": "lt",
                ">": "gt",
                "'": "apos",
                '"': "quot"
            }[c] + ";";
        }
    ) : "";
};

How do I load a file into the python console?

If you're using IPython, you can simply run:

%load path/to/your/file.py

See http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html

Is there a command for formatting HTML in the Atom editor?

You can add atom beauty package for formatting text in atom..

file --> setting --> Install

then you type atom-beautify in search area.

then click Package button.. select atom beuty and install it.

next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents

Hex transparency in colors

Using python to calculate this, for example(written in python 3), 50% transparency :

hex(round(256*0.50))

:)

How do I get the value of a registry key and ONLY the value using powershell

Not sure at what version this capability arrived, but you can use something like this to return all the properties of multiple child registry entries in an array:

$InstalledSoftware = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach-Object {Get-ItemProperty "Registry::$_"}

Only adding this as Google brought me here for a relevant reason and I eventually came up with the above one-liner for dredging the registry.

How to find the mysql data directory from command line in windows

You can issue the following query from the command line:

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name LIKE "%dir"'

Output (on Linux):

+---------------------------+----------------------------+
| Variable_name             | Value                      |
+---------------------------+----------------------------+
| basedir                   | /usr                       |
| character_sets_dir        | /usr/share/mysql/charsets/ |
| datadir                   | /var/lib/mysql/            |
| innodb_data_home_dir      |                            |
| innodb_log_group_home_dir | ./                         |
| lc_messages_dir           | /usr/share/mysql/          |
| plugin_dir                | /usr/lib/mysql/plugin/     |
| slave_load_tmpdir         | /tmp                       |
| tmpdir                    | /tmp                       |
+---------------------------+----------------------------+

Output (on macOS Sierra):

+---------------------------+-----------------------------------------------------------+
| Variable_name             | Value                                                     |
+---------------------------+-----------------------------------------------------------+
| basedir                   | /usr/local/mysql-5.7.17-macos10.12-x86_64/                |
| character_sets_dir        | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/charsets/ |
| datadir                   | /usr/local/mysql/data/                                    |
| innodb_data_home_dir      |                                                           |
| innodb_log_group_home_dir | ./                                                        |
| innodb_tmpdir             |                                                           |
| lc_messages_dir           | /usr/local/mysql-5.7.17-macos10.12-x86_64/share/          |
| plugin_dir                | /usr/local/mysql/lib/plugin/                              |
| slave_load_tmpdir         | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/         |
| tmpdir                    | /var/folders/zz/zyxvpxvq6csfxvn_n000009800002_/T/         |
+---------------------------+-----------------------------------------------------------+

Or if you want only the data dir use:

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'

These commands work on Windows too, but you need to invert the single and double quotes.

Btw, when executing which mysql in Linux as you told, you'll not get the installation directory on Linux. You'll only get the binary path, which is /usr/bin on Linux, but you see the mysql installation is using multiple folders to store files.


If you need the value of datadir as output, and only that, without column headers etc, but you don't have a GNU environment (awk|grep|sed ...) then use the following command line:

mysql -s -N -uUSER -p information_schema -e 'SELECT Variable_Value FROM GLOBAL_VARIABLES WHERE Variable_Name = "datadir"'

The command will select the value only from mysql's internal information_schema database and disables the tabular output and column headers.

Output on Linux:

/var/lib/mysql

Add Auto-Increment ID to existing table?

If you run the following command :

ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT PRIMARY KEY;

This will show you the error :

ERROR 1060 (42S21): Duplicate column name 'id'

This is because this command will try to add the new column named id to the existing table.

To modify the existing column you have to use the following command :

ALTER TABLE users MODIFY id int NOT NULL AUTO_INCREMENT PRIMARY KEY;

This should work for changing the existing column constraint....!

What's the best way to calculate the size of a directory in .NET?

this solution works very well. it's collecting all the sub folders:

Directory.GetFiles(@"MainFolderPath", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length));

Reading output of a command into an array in Bash

The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *, ?, [...].

To get the output of a command in an array, with one line per element, there are essentially 3 ways:

  1. With Bash=4 use mapfile—it's the most efficient:

    mapfile -t my_array < <( my_command )
    
  2. Otherwise, a loop reading the output (slower, but safe):

    my_array=()
    while IFS= read -r line; do
        my_array+=( "$line" )
    done < <( my_command )
    
  3. As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:

    IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
    

    Please make sure you use exactly this form, i.e., make sure you have the following:

    • IFS=$'\n' on the same line as the read statement: this will only set the environment variable IFS for the read statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read to break the stream at the EOL character \n.
    • -r: this is important. It tells read to not interpret the backslashes as escape sequences.
    • -d '': please note the space between the -d option and its argument ''. If you don't leave a space here, the '' will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read to stop reading at the nil byte. Some people write it as -d $'\0', but it is not really necessary. -d '' is better.
    • -a my_array tells read to populate the array my_array while reading the stream.
    • You must use the printf '\0' statement after my_command, so that read returns 0; it's actually not a big deal if you don't (you'll just get an return code 1, which is okay if you don't use set -e – which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf '', which doesn't output anything. printf '\0' prints a null byte, needed by read to happily stop reading there (remember the -d '' option?).

If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.

If you want to use read, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]} in the example I gave).

Note that mapfile provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile and the options -C and -c therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).


Now I'm going to tell you why the following method:

my_array=( $( my_command) )

is broken when there are spaces:

$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!

Then some people will then recommend using IFS=$'\n' to fix it:

$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!

But now let's use another command, with globs:

$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?

That's because I have a file called t in the current directory… and this filename is matched by the glob [three four]… at this point some people would recommend using set -f to disable globbing: but look at it: you have to change IFS and use set -f to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.

$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'

here we're working with the shell!

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

The ORA-2270 error is a straightforward logical error: it happens when the columns we list in the foreign key do not match a primary key or unique constraint on the parent table. Common reasons for this are

  • the parent lacks a PRIMARY KEY or UNIQUE constraint altogether
  • the foreign key clause references the wrong column in the parent table
  • the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.

Neither appears to be the case in your posted code. But that's a red herring, because your code does not run as you have posted it. Judging from the previous edits I presume you are not posting your actual code but some simplified example. Unfortunately in the process of simplification you have eradicated whatever is causing the ORA-2270 error.

SQL> CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   NUMBER,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );  2    3    4    5    6  

Table created.

SQL> CREATE TABLE USER
 (
   ID       NUMBER NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );  2    3    4    5  
CREATE TABLE USER
             *
ERROR at line 1:
ORA-00903: invalid table name


SQL> 

That statement failed because USER is a reserved keyword so we cannot name a table USER. Let's fix that:

SQL> 1
  1* CREATE TABLE USER
SQL> a s
  1* CREATE TABLE USERs
SQL> l
  1  CREATE TABLE USERs
  2   (
  3     ID       NUMBER NOT NULL ,
  4     CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
  5*  )
SQL> r
  1  CREATE TABLE USERs
  2   (
  3     ID       NUMBER NOT NULL ,
  4     CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
  5*  )

Table created.

SQL> Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USERS(ID);   

Table altered.

SQL> 

And lo! No ORA-2270 error.

Alas, there's not much we can do here to help you further. You have a bug in your code. You can post your code here and one of us can spot your mistake. Or you can check your own code and discover it for yourself.


Note: an earlier version of the code defined HOB.USERID as VARCHAR2(20). Because USER.ID is defined as a NUMBER the attempt to create a foreign key would have hurl a different error:

ORA-02267: column type incompatible with referenced column type

An easy way to avoid mismatches is to use foreign key syntax to default the datatype of the column:

CREATE TABLE USERs
 (
   ID    number NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );

CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   constraint FK_USERID references users,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );

Send multipart/form-data files with angular using $http

In Angular 6, you can do this:

In your service file:

 function_name(data) {
    const url = `the_URL`;
    let input = new FormData();
    input.append('url', data);   // "url" as the key and "data" as value
    return this.http.post(url, input).pipe(map((resp: any) => resp));
  }

In component.ts file: in any function say xyz,

xyz(){
this.Your_service_alias.function_name(data).subscribe(d => {   // "data" can be your file or image in base64 or other encoding
      console.log(d);
    });
}

How to convert NSDate into unix timestamp iphone sdk?

- (void)GetCurrentTimeStamp
    {
        NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
        [objDateformat setDateFormat:@"yyyy-MM-dd"];
        NSString    *strTime = [objDateformat stringFromDate:[NSDate date]];
        NSString    *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
        NSDate *objUTCDate  = [objDateformat dateFromString:strUTCTime];
        long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);

        NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
        NSLog(@"The Timestamp is = %@",strTimestamp);
    }

 - (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate  *objDate    = [dateFormatter dateFromString:IN_strLocalTime];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *strDateTime   = [dateFormatter stringFromDate:objDate];
        return strDateTime;
    }

NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.

How does the "view" method work in PyTorch?

Let's do some examples, from simpler to more difficult.

  1. The view method returns a tensor with the same data as the self tensor (which means that the returned tensor has the same number of elements), but with a different shape. For example:

    a = torch.arange(1, 17)  # a's shape is (16,)
    
    a.view(4, 4) # output below
      1   2   3   4
      5   6   7   8
      9  10  11  12
     13  14  15  16
    [torch.FloatTensor of size 4x4]
    
    a.view(2, 2, 4) # output below
    (0 ,.,.) = 
    1   2   3   4
    5   6   7   8
    
    (1 ,.,.) = 
     9  10  11  12
    13  14  15  16
    [torch.FloatTensor of size 2x2x4]
    
  2. Assuming that -1 is not one of the parameters, when you multiply them together, the result must be equal to the number of elements in the tensor. If you do: a.view(3, 3), it will raise a RuntimeError because shape (3 x 3) is invalid for input with 16 elements. In other words: 3 x 3 does not equal 16 but 9.

  3. You can use -1 as one of the parameters that you pass to the function, but only once. All that happens is that the method will do the math for you on how to fill that dimension. For example a.view(2, -1, 4) is equivalent to a.view(2, 2, 4). [16 / (2 x 4) = 2]

  4. Notice that the returned tensor shares the same data. If you make a change in the "view" you are changing the original tensor's data:

    b = a.view(4, 4)
    b[0, 2] = 2
    a[2] == 3.0
    False
    
  5. Now, for a more complex use case. The documentation says that each new view dimension must either be a subspace of an original dimension, or only span d, d + 1, ..., d + k that satisfy the following contiguity-like condition that for all i = 0, ..., k - 1, stride[i] = stride[i + 1] x size[i + 1]. Otherwise, contiguous() needs to be called before the tensor can be viewed. For example:

    a = torch.rand(5, 4, 3, 2) # size (5, 4, 3, 2)
    a_t = a.permute(0, 2, 3, 1) # size (5, 3, 2, 4)
    
    # The commented line below will raise a RuntimeError, because one dimension
    # spans across two contiguous subspaces
    # a_t.view(-1, 4)
    
    # instead do:
    a_t.contiguous().view(-1, 4)
    
    # To see why the first one does not work and the second does,
    # compare a.stride() and a_t.stride()
    a.stride() # (24, 6, 2, 1)
    a_t.stride() # (24, 2, 1, 6)
    

    Notice that for a_t, stride[0] != stride[1] x size[1] since 24 != 2 x 3

Any implementation of Ordered Set in Java?

If we are talking about inexpensive implementation of the skip-list, I wonder in term of big O, what the cost of this operation is:

YourType[] array = someSet.toArray(new YourType[yourSet.size()]);

I mean it is always get stuck into a whole array creation, so it is O(n):

java.util.Arrays#copyOf

Check list of words in another string

Easiest and Simplest method of solving this problem is using re

import re

search_list = ['one', 'two', 'there']
long_string = 'some one long two phrase three'
if re.compile('|'.join(search_list),re.IGNORECASE).search(long_string): #re.IGNORECASE is used to ignore case
    # Do Something if word is present
else:
    # Do Something else if word is not present

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

Chrome - ERR_CACHE_MISS

If you are using WebView in Android developing the problem is that you didn't add uses permission

<uses-permission android:name="android.permission.INTERNET" />

Android Reading from an Input stream efficiently

What about this. Seems to give better performance.

byte[] bytes = new byte[1000];

StringBuilder x = new StringBuilder();

int numRead = 0;
while ((numRead = is.read(bytes)) >= 0) {
    x.append(new String(bytes, 0, numRead));
}

Edit: Actually this sort of encompasses both steelbytes and Maurice Perry's

Remove an onclick listener

    /**
 * Remove an onclick listener
 *
 * @param view
 * @author [email protected]
 * @website https://github.com/androidmalin
 * @data 2016-05-16
 */
public static void unBingListener(View view) {
    if (view != null) {
        try {
            if (view.hasOnClickListeners()) {
                view.setOnClickListener(null);

            }

            if (view.getOnFocusChangeListener() != null) {
                view.setOnFocusChangeListener(null);

            }

            if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
                ViewGroup viewGroup = (ViewGroup) view;
                int viewGroupChildCount = viewGroup.getChildCount();
                for (int i = 0; i < viewGroupChildCount; i++) {
                    unBingListener(viewGroup.getChildAt(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

just remove and reDownload wrapper gradle.

Mac Home/.gradle/wrapper/dists/

remove gradle version and sync gradle in project and run project.

enter image description here

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You could create your own class of type Quiz and then deserialize with strong type:

Example:

quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
                 new JsonSerializerSettings
                 {
                     Error = delegate(object sender1, ErrorEventArgs args1)
                     {
                         errors.Add(args1.ErrorContext.Error.Message);
                         args1.ErrorContext.Handled = true;
                     }
                 });

And you could also apply a schema validation.

http://james.newtonking.com/projects/json/help/index.html

What does "Table does not support optimize, doing recreate + analyze instead" mean?

OPTIMIZE TABLE works fine with InnoDB engine according to the official support article : http://dev.mysql.com/doc/refman/5.5/en/optimize-table.html

You'll notice that optimize InnoDB tables will rebuild table structure and update index statistics (something like ALTER TABLE).

Keep in mind that this message could be an informational mention only and the very important information is the status of your query : just OK !

mysql> OPTIMIZE TABLE foo;
+----------+----------+----------+-------------------------------------------------------------------+
| Table    | Op       | Msg_type | Msg_text                                                          |
+----------+----------+----------+-------------------------------------------------------------------+
| test.foo | optimize | note     | Table does not support optimize, doing recreate + analyze instead |
| test.foo | optimize | status   | OK                                                                |
+----------+----------+----------+-------------------------------------------------------------------+

Most efficient way to get table row count

Next to the information_schema suggestion, this:

SELECT id FROM table ORDER BY id DESC LIMIT 1

should also be very fast, provided there's an index on the id field (which I believe must be the case with auto_increment)

jQuery selectors on custom data attributes using HTML5

jsFiddle Demo

jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.

The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not).

In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.

var group = $('ul[data-group="Companies"]');

Next, we can look for companies in this set who start with G

var google = $('[data-company^="G"]',group);//google

Or perhaps companies which contain the word soft

var microsoft = $('[data-company*="soft"]',group);//microsoft

It is also possible to get elements whose data attribute's ending matches

var facebook = $('[data-company$="book"]',group);//facebook

_x000D_
_x000D_
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
  <li data-company="Microsoft">Microsoft</li>_x000D_
  <li data-company="Google">Google</li>_x000D_
  <li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Converting XML to JSON using Python?

To anyone that may still need this. Here's a newer, simple code to do this conversion.

from xml.etree import ElementTree as ET

xml    = ET.parse('FILE_NAME.xml')
parsed = parseXmlToJson(xml)


def parseXmlToJson(xml):
  response = {}

  for child in list(xml):
    if len(list(child)) > 0:
      response[child.tag] = parseXmlToJson(child)
    else:
      response[child.tag] = child.text or ''

    # one-liner equivalent
    # response[child.tag] = parseXmlToJson(child) if len(list(child)) > 0 else child.text or ''

  return response

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

How to check if a variable is an integer in JavaScript?

if(Number.isInteger(Number(data))){
    //-----
}

How do I create/edit a Manifest file?

In Visual Studio 2019 WinForm Projects, it is available under

Project Properties -> Application -> View Windows Settings (button)

enter image description here

Permission denied on CopyFile in VBS

I've only ever seen CopyFile fail with a "permission denied" error in one of these 3 scenarios:

  • An actual permission problem with either source or destination.
  • Destination path is a folder, but does not have a trailing backslash.
  • Source file is locked by an application.

Wait for a process to finish

Rauno Palosaari's solution for Timeout in Seconds Darwin, is an excellent workaround for a UNIX-like OS that does not have GNU tail (it is not specific to Darwin). But, depending on the age of the UNIX-like operating system, the command-line offered is more complex than necessary, and can fail:

lsof -p $pid +r 1m%s -t | grep -qm1 $(date -v+${timeout}S +%s 2>/dev/null || echo INF)

On at least one old UNIX, the lsof argument +r 1m%s fails (even for a superuser):

lsof: can't read kernel name list.

The m%s is an output format specification. A simpler post-processor does not require it. For example, the following command waits on PID 5959 for up to five seconds:

lsof -p 5959 +r 1 | awk '/^=/ { if (T++ >= 5) { exit 1 } }'

In this example, if PID 5959 exits of its own accord before the five seconds elapses, ${?} is 0. If not ${?} returns 1 after five seconds.

It may be worth expressly noting that in +r 1, the 1 is the poll interval (in seconds), so it may be changed to suit the situation.

JSON - Iterate through JSONArray

for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

Hope this helps someone

Capture the Screen into a Bitmap

If using the .NET 2.0 (or later) framework you can use the CopyFromScreen() method detailed here:

http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html

//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                               Screen.PrimaryScreen.Bounds.Height,
                               PixelFormat.Format32bppArgb);

// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                            Screen.PrimaryScreen.Bounds.Y,
                            0,
                            0,
                            Screen.PrimaryScreen.Bounds.Size,
                            CopyPixelOperation.SourceCopy);

// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);

Android "elevation" not showing a shadow

In my case fonts were the problem.

1) Without fontFamily I needed to set android:background to some value.

<TextView
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@android:color/white"
    android:elevation="3dp"
    android:gravity="center"
    android:text="@string/fr_etalons_your_tickets"
    android:textAllCaps="true"
    android:textColor="@color/blue_4" />

2) with fontFamily I had to add android:outlineProvider="bounds" setting:

<TextView
    android:fontFamily="@font/gilroy_bold"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@android:color/white"
    android:elevation="3dp"
    android:gravity="center"
    android:outlineProvider="bounds"
    android:text="@string/fr_etalons_your_tickets"
    android:textAllCaps="true"
    android:textColor="@color/blue_4" />

How to check version of a CocoaPods framework

You can figure out version of Cocoapods by using below command :

pod —-version

o/p : 1.2.1

Now if you want detailed version of Gems and Cocoapods then use below command :

gem which cocoapods (without sudo)

o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb

sudo gem which cocoapods (with sudo)

o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb

Screenshot 1

Now if you want to get specific version of Pod present in Podfile then simply use command pod install in terminal. This will show list of pod being used in project along with version.

Screenshot 2

Fit cell width to content

For me, this is the best autofit and autoresize for table and its columns (use css !important ... only if you can't without)

.myclass table {
    table-layout: auto !important;
}

.myclass th, .myclass td, .myclass thead th, .myclass tbody td, .myclass tfoot td, .myclass tfoot th {
    width: auto !important;
}

Don't specify css width for table or for table columns. If table content is larger it will go over screen size to.

AngularJS - pass function to directive

use dash and lower case for attribute name ( like other answers said ) :

 <test color1="color1" update-fn="updateFn()"></test>

And use "=" instead of "&" in directive scope:

 scope: { updateFn: '='}

Then you can use updateFn like any other function:

 <button ng-click='updateFn()'>Click</button>

There you go!

Take the content of a list and append it to another list

You probably want

list2.extend(list1)

instead of

list2.append(list1)

Here's the difference:

>>> a = range(5)
>>> b = range(3)
>>> c = range(2)
>>> b.append(a)
>>> b
[0, 1, 2, [0, 1, 2, 3, 4]]
>>> c.extend(a)
>>> c
[0, 1, 0, 1, 2, 3, 4]

Since list.extend() accepts an arbitrary iterable, you can also replace

for line in mylog:
    list1.append(line)

by

list1.extend(mylog)

HTML5 Form Input Pattern Currency Format

If you want to allow a comma delimiter which will pass the following test cases:

0,00  => true
0.00  => true
01,00 => true
01.00 => true
0.000 => false
0-01  => false

then use this:

^\d+(\.|\,)\d{2}$

How do I get the latest version of my code?

If you are using Git GUI, first fetch then merge.

Fetch via Remote menu >> Fetch >> Origin. Merge via Merge menu >> Merge Local.

The following dialog appears.

enter image description here

Select the tracking branch radio button (also by default selected), leave the yellow box empty and press merge and this should update the files.

I had already reverted some local changes before doing these steps since I wanted to discard those anyways so I don't have to eliminate via merge later.

Easy way of running the same junit test over and over?

I build a module that allows do this kind of tests. But it is focused not only in repeat. But in guarantee that some piece of code is Thread safe.

https://github.com/anderson-marques/concurrent-testing

Maven dependency:

<dependency>
    <groupId>org.lite</groupId>
    <artifactId>concurrent-testing</artifactId>
    <version>1.0.0</version>
</dependency>

Example of use:

package org.lite.concurrent.testing;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import ConcurrentTest;
import ConcurrentTestsRule;

/**
 * Concurrent tests examples
 */
public class ExampleTest {

    /**
     * Create a new TestRule that will be applied to all tests
     */
    @Rule
    public ConcurrentTestsRule ct = ConcurrentTestsRule.silentTests();

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 20, threads = 10)
    public void testConcurrentExecutionSuccess(){
        Assert.assertTrue(true);
    }

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 200, threads = 10, timeoutMillis = 100)
    public void testConcurrentExecutionSuccessWaitOnly100Millissecond(){
    }

    @Test(expected = RuntimeException.class)
    @ConcurrentTest(requests = 3)
    public void testConcurrentExecutionFail(){
        throw new RuntimeException("Fail");
    }
}

This is a open source project. Feel free to improve.

How to unnest a nested list

Use itertools.chain:

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

The output is:

[1, 2, 3, 4]
[1, 2, 3, 4]

"unexpected token import" in Nodejs5 and babel?

I have done the following to overcome the problem (ex.js script)

problem

$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");

$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:152:10)
    at Module._compile (module.js:624:28)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:194:16)
    at bootstrap_node.js:618:3

solution

# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections

# .babelrc setup
$ cat .babelrc
{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported

# or execution with babel-node
$ babel-node ex.js
Successfully Imported

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

If source file not found xcopy returns error code 4 also.

How to find the type of an object in Go?

To get a string representation:

From http://golang.org/pkg/fmt/

%T a Go-syntax representation of the type of the value

package main
import "fmt"
func main(){
    types := []interface{} {"a",6,6.0,true}
    for _,v := range types{
        fmt.Printf("%T\n",v)
    }
}

Outputs:

string
int
float64
bool

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

Specify foreign key for the details tables which references to the primary key of master and set Delete rule = Cascade .

Now when u delete a record from the master table all other details table record based on the deleting rows primary key value, will be deleted automatically.

So in that case a single delete query of master table can delete master tables data as well as child tables data.

Execute PHP function with onclick

In javascript, make an ajax function,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

<a href="" onclick="myAjax()" class="deletebtn">Delete</a>

And in your ajax.php,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}

Check if element found in array c++

You can do it in a beginners style by using control statements and loops..

#include <iostream>
using namespace std;
int main(){
    int arr[] = {10,20,30,40,50}, toFind= 10, notFound = -1;
    for(int i = 0; i<=sizeof(arr); i++){
        if(arr[i] == toFind){   
            cout<< "Element is found at " <<i <<" index" <<endl;
            return 0;
        }   
    }
    cout<<notFound<<endl;
}

Removing empty lines in Notepad++

CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines as suggested above works.

But if lines contains some space, then move the cursor to that line and do a CTRL + H. The "Find what:" sec will show the blank space and in the "Replace with" section, leave it blank. Now all the spaces are removed and now try CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines

Error: "an object reference is required for the non-static field, method or property..."

Create a class and put all your code in there and call an instance of this class from the Main :

static void Main(string[] args)
{

    MyClass cls  = new MyClass();
    Console.Write("Write a number: ");
    long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
    long av = cls.volteado(a);
    bool isTrue = cls.siprimo(a);
    ......etc

}

jQuery Call to WebService returns "No Transport" error

Add this: jQuery.support.cors = true;

It enables cross-site scripting in jQuery (introduced after 1.4x, I believe).

We were using a really old version of jQuery (1.3.2) and swapped it out for 1.6.1. Everything was working, except .ajax() calls. Adding the above line fixed the problem.

In MS DOS copying several files to one file

filenames must sort correctly to combine correctly!

file1.bin file2.bin ... file10.bin wont work properly

file01.bin file02.bin ... file10.bin will work properly

c:>for %i in (file*.bin) do type %i >> onebinary.bin

Works for ascii or binary files.

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

How to dynamically build a JSON object with Python?

You can create the Python dictionary and serialize it to JSON in one line and it's not even ugly.

my_json_string = json.dumps({'key1': val1, 'key2': val2})

libaio.so.1: cannot open shared object file

It looks like a 32/64 bit mismatch. The ldd output shows that mainly libraries from /lib64 are chosen. That would indicate that you have installed a 64 bit version of the Oracle client and have created a 64 bit executable. But libaio.so is probably a 32 bit library and cannot be used for your application.

So you either need a 64 bit version of libaio or you create a 32 bit version of your application.

select and echo a single field from mysql db using PHP

Try this:

echo mysql_result($result, 0);

This is enough because you are only fetching one field of one row.

Javascript change color of text and background to input value

Depending on which event you actually want to use (textbox change, or button click), you can try this:

HTML:

<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>

JS:

function changeBackground(obj) {
    document.getElementById("coltext").style.color = obj.value;
}

DEMO: http://jsfiddle.net/6pLUh/

One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange allows you to change the color based on the input.

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

How do I install ASP.NET MVC 5 in Visual Studio 2012?

There are a few installs you may need to apply for ASP.NET MVC 5 support in Visual Studio 2012. Update 4 seems to include the Web Tools update now.

You don't have to install the full Windows 8.1 SDK if you are just looking for the option to build web applications, just the .NET Framework 4.5.1 option in the installer. The full install is about 1.1 GB, but just the .NET installer is only 72 MB.

How do I get the name of a Ruby class?

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

If you use Rails (ActiveSupport):

result.class.name.demodulize

If you use POR (plain-ol-Ruby):

result.class.name.split('::').last

Difference between Return and Break statements

break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.

return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).

So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.


Consider the following example. The value of x inside the while-loop will determine if the code below the loop will be executed or not:

void f()
{
   int x = -1;
   while(true)
   {
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1
     ...
   }

   code that will be executed on break (but not with return).
   ....
}

Create new XML file and write data to it?

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'Root' );
    $ele->nodeValue = 'Hello XML World';
    $doc->appendChild( $ele );
    $doc->save('MyXmlFile.xml');
?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.

How can you float: right in React Native?

You are not supposed to use floats in React Native. React Native leverages the flexbox to handle all that stuff.

In your case, you will probably want the container to have an attribute

justifyContent: 'flex-end'

And about the text taking the whole space, again, you need to take a look at your container.

Here is a link to really great guide on flexbox: A Complete Guide to Flexbox

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

mongoError: Topology was destroyed

In my case, this error was caused by an identical server instance already running background.

The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.

What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.

All in all, kill all the node processes may solve this problem directly.

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Great answers, but you could just open the command prompt and type in

 SET PATH=C:\Program Files\Nodejs;%PATH%

How to find out which JavaScript events fired?

Looks like Firebug (Firefox add-on) has the answer:

  • open Firebug
  • right click the element in HTML tab
  • click Log Events
  • enable Console tab
  • click Persist in Console tab (otherwise Console tab will clear after the page is reloaded)
  • select Closed (manually)
  • there will be something like this in Console tab:

    ...
    mousemove clientX=1097, clientY=292
    popupshowing
    mousedown clientX=1097, clientY=292
    focus
    mouseup clientX=1097, clientY=292
    click clientX=1097, clientY=292
    mousemove clientX=1096, clientY=293
    ...
    

Source: Firebug Tip: Log Events

Python Socket Receive Large Amount of Data

You can use it as: data = recvall(sock)

def recvall(sock):
    BUFF_SIZE = 4096 # 4 KiB
    data = b''
    while True:
        part = sock.recv(BUFF_SIZE)
        data += part
        if len(part) < BUFF_SIZE:
            # either 0 or end of data
            break
    return data

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

How to save traceback / sys.exc_info() values in a variable?

The object can be used as a parameter in Exception.with_traceback() function:

except Exception as e:
    tb = sys.exc_info()
    print(e.with_traceback(tb[2]))

PostgreSQL: How to change PostgreSQL user password?

To change password using Linux command line, use:

sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"

How to get name of calling function/method in PHP?

As of php 5.4 you can use

        $dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
        $caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;

This will not waste memory as it ignores arguments and returns only the last 2 backtrace stack entries, and will not generate notices as other answers here.

How to give Jenkins more heap space when it´s started as a service under Windows?

You need to modify the jenkins.xml file. Specifically you need to change

   <arguments>-Xrs -Xmx256m 
    -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
    -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>

to

    <arguments>-Xrs -Xmx2048m -XX:MaxPermSize=512m 
    -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
    -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>

You can also verify the Java options that Jenkins is using by installing the Jenkins monitor plugin via Manage Jenkins / Manage Plugins and then navigating to Managing Jenkins / Monitoring of Hudson / Jenkins master to use monitoring to determine how much memory is available to Jenkins.

If you are getting an out of memory error when Jenkins calls Maven, it may be necessary to set MAVEN_OPTS via Manage Jenkins / Configure System e.g. if you are running on a version of Java prior to JDK 1.8 (the values are suggestions):

-Xmx2048m  -XX:MaxPermSize=512m

If you are using JDK 1.8:

-Xmx2048m

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

How to check if an object implements an interface?

For an instance

Character.Gorgon gor = new Character.Gorgon();

Then do

gor instanceof Monster

For a Class instance do

Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);

Eclipse Build Path Nesting Errors

I had the same problem even when I created a fresh project. I was creating the Java project within Eclipse, then mavenize it, then going into java build path properties removing src/ and adding src/main/java and src/test/java. When I run Maven update it used to give nested path error.
Then I finally realized -because I had not seen that entry before- there is a <sourceDirectory>src</sourceDirectory> line in pom file written when I mavenize it. It was resolved after removing it.

Set the value of a variable with the result of a command in a Windows batch file

To do what Jesse describes, from a Windows batch file you will need to write:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.

Run PHP function on html button click

It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.

jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/

How to remove text from a string?

str.split('Yes').join('No'); 

This will replace all the occurrences of that specific string from original string.

Remove property for all objects in array

I will suggest to use Object.assign within a forEach() loop so that the objects are copied and does not affect the original array of objects

var res = [];
array.forEach(function(item) { 
    var tempItem = Object.assign({}, item);
    delete tempItem.bad; 
    res.push(tempItem);
});
console.log(res);

Anaconda-Navigator - Ubuntu16.04

Try this:

First go to the anaconda3 binaries directory by running

 cd anaconda3/bin

and now use this following command to open the anaconda-navigator

./anaconda-navigator

Tooltip with HTML content without JavaScript

This is my solution for this:

https://gist.github.com/BryanMoslo/808f7acb1dafcd049a1aebbeef8c2755

The element recibes a "tooltip-title" attribute with the tooltip text and it is displayed with CSS on hover, I prefer this solution because I don't have to include the tooltip text as a HTML element!

#HTML
<button class="tooltip" tooltip-title="Save">Hover over me</button>

#CSS

body{
    padding: 50px;
}
.tooltip {
    position: relative;
}

.tooltip:before {
    content: attr(tooltip-title);
    min-width: 54px;
    background-color: #999999;
    color: #fff;
    font-size: 12px;
    border-radius: 4px;
    padding: 9px 0;
    position: absolute;
    top: -42px;
    left: 50%;
    margin-left: -27px;
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.3s;
}

.tooltip:after {
    content: "";
    position: absolute;
    top: -9px;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #999999 transparent transparent;
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.3s;
}

.tooltip:hover:before,
.tooltip:hover:after{
    visibility: visible;
    opacity: 1;
}

Best way to access a control on another form in Windows Forms?

I agree with using events for this. Since I suspect that you're building an MDI-application (since you create many child forms) and creates windows dynamically and might not know when to unsubscribe from events, I would recommend that you take a look at Weak Event Patterns. Alas, this is only available for framework 3.0 and 3.5 but something similar can be implemented fairly easy with weak references.

However, if you want to find a control in a form based on the form's reference, it's not enough to simply look at the form's control collection. Since every control have it's own control collection, you will have to recurse through them all to find a specific control. You can do this with these two methods (which can be improved).

public static Control FindControl(Form form, string name)
{
    foreach (Control control in form.Controls)
    {
        Control result = FindControl(form, control, name);

        if (result != null)
            return result;
    }

    return null;
}

private static Control FindControl(Form form, Control control, string name)
{
    if (control.Name == name) {
        return control;
    }

    foreach (Control subControl in control.Controls)
    {
        Control result = FindControl(form, subControl, name);

        if (result != null)
            return result;
    }

    return null;
}

Change visibility of ASP.NET label with JavaScript

Make sure the Visible property is set to true or the control won't render to the page. Then you can use script to manipulate it.

Setting HTTP headers

Set a proper golang middleware, so you can reuse on any endpoint.

Helper Type and Function

type Adapter func(http.Handler) http.Handler
// Adapt h with all specified adapters.
func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
    for _, adapter := range adapters {
        h = adapter(h)
    }
    return h
}

Actual middleware

func EnableCORS() Adapter {
    return func(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

            if origin := r.Header.Get("Origin"); origin != "" {
                w.Header().Set("Access-Control-Allow-Origin", origin)
                w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
                w.Header().Set("Access-Control-Allow-Headers",
                    "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
            }
            // Stop here if its Preflighted OPTIONS request
            if r.Method == "OPTIONS" {
                return
            }
            h.ServeHTTP(w, r)
        })
    }
}

Endpoint

REMEBER! Middlewares get applyed on reverse order( ExpectGET() gets fires first)

mux.Handle("/watcher/{action}/{device}",Adapt(api.SerialHandler(mux),
    api.EnableCORS(),
    api.ExpectGET(),
))

java SSL and cert keystore

SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

The specific keys you have to set are below:

javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

  1. $JAVA_HOME/lib/security/jssecacerts
  2. $JAVA_HOME/lib/security/cacerts

javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

convert month from name to number

$monthname = date("F", strtotime($month));

F means full month name

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Fixed positioned div within a relative parent div

Sample solution. Check, if this is what you need.

<div class="container">
   <div class="relative">      
      <div class="absolute"></div>      
      <div class="content">
        <p>
          Content here
        </p>
      </div>
    </div>
 </div>

And for CSS

.relative { 
  position: relative;
}

.absolute {
  position: absolute;
  top: 15px;
  left: 25px;   
}

See it on codepen https://codepen.io/FelySpring/pen/jXENXY

instanceof Vs getClass( )

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be? you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

Java balanced expressions check {[()]}

A slightly different approach I took to solve this problem, I have observed two key points in this problem.

  1. Open braces should be accompanied always with corresponding closed braces.
  2. Different Open braces are allowed together but not different closed braces.

So I converted these points into easy-to-implement and understandable format.

  1. I represented different braces with different numbers
  2. Gave positive sign to open braces and negative sign for closed braces.

For Example : "{ } ( ) [ ]" will be "1 -1 2 -2 3 -3" is valid parenthesis. For a balanced parenthesis, positives can be adjacent where as a negative number should be of positive number in top of the stack.

Below is code:

import java.util.Stack;

public class Main {
    public static void main (String [] args)
    {
        String value = "()(){}{}{()}";
        System.out.println(Main.balancedParanthesis(value));
       
    }

public static boolean balancedParanthesis(String s) {
        
        
        
        char[] charArray=s.toCharArray();
        
        int[] integerArray=new int[charArray.length];
        
        
        // creating braces with equivalent numeric values
        for(int i=0;i<charArray.length;i++) {
            
            if(charArray[i]=='{') {
                integerArray[i]=1;
            }
            else if(charArray[i]=='}') {
                integerArray[i]=-1;
            }
            else if(charArray[i]=='[') {
                integerArray[i]=2;
            }
            else if(charArray[i]==']') {
                integerArray[i]=-2;
            }
            else if(charArray[i]=='(') {
                integerArray[i]=3;
            }
            else  {
                integerArray[i]=-3;
            }
        }
        
        Stack<Integer> stack=new Stack<Integer>();
        
        for(int i=0;i<charArray.length;i++) {
            
            if(stack.isEmpty()) {
                if(integerArray[i]<0) {
                    stack.push(integerArray[i]);
                    break;
            }
                    stack.push(integerArray[i]);
            }
            else{
                if(integerArray[i]>0) {
                    stack.push(integerArray[i]);
                }
                else {
                    if(stack.peek()==-(integerArray[i])) {
                        stack.pop();
                    }
                    else {
                        break;
                    }
                }
            }
        }
        return stack.isEmpty();
    }
}

Transparent background on winforms?

I had drawn a splash screen (32bpp BGRA) with "transparent" background color in VS2013 and put a pictureBox in a form for display. For me a combination of above answers worked:

public Form1()
{
    InitializeComponent();

    SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    this.BackColor = this.pictureBox1.BackColor;
    this.TransparencyKey = this.pictureBox1.BackColor;
}

So make sure you use the same BackColor everywhere and set that color as the TransparencyKey.

Where is the WPF Numeric UpDown control?

Go to NugetPackage manager of you project-> Browse and search for mahApps.Metro -> install package into you project. You will see Reference added: MahApps.Metro. Then in you XAML code add:

"xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"

Where you want to use your object add:

<mah:NumericUpDown x:Name="NumericUpDown" ... /> 

Enjoy the full extensibility of the object (Bindings, triggers and so on...).

How to get response body using HttpURLConnection, when code other than 2xx is returned?

This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
               System.out.println(strCurrentLine);
        }
}

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

How to create a HTTP server in Android?

If you are using kotlin,consider these library. It's build for kotlin language.

AndroidHttpServer is a simple demo using ServerSocket to handle http request

https://github.com/weeChanc/AndroidHttpServer

https://github.com/ktorio/ktor

AndroidHttpServer is very small , but the feature is less as well.

Ktor is a very nice library,and the usage is simple too

Rotating videos with FFmpeg

I came across this page while searching for the same answer. It is now six months since this was originally asked and the builds have been updated many times since then. However, I wanted to add an answer for anyone else that comes across here looking for this information.

I am using Debian Squeeze and FFmpeg version from those repositories.

The MAN page for ffmpeg states the following use

ffmpeg -i inputfile.mpg -vf "transpose=1" outputfile.mpg

The key being that you are not to use a degree variable, but a predefined setting variable from the MAN page.

0=90CounterCLockwise and Vertical Flip  (default) 
1=90Clockwise 
2=90CounterClockwise 
3=90Clockwise and Vertical Flip

Definitive way to trigger keypress events with jQuery

In case you need to take into account the current cursor and text selection...

This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

There is a simple trick for this. After you constructed the frame with all it buttons do this:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
        System.out.println("Hello");

        JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
    }

}

UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

Is there a difference between using a dict literal and a dict constructor?

Also consider the fact that tokens that match for operators can't be used in the constructor syntax, i.e. dasherized keys.

>>> dict(foo-bar=1)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression

>>> {'foo-bar': 1}
{'foo-bar': 1}

How to use XPath contains() here?

You are only looking at the first li child in the query you have instead of looking for any li child element that may contain the text, 'Model'. What you need is a query like the following:

//ul[@class='featureList' and ./li[contains(.,'Model')]]

This query will give you the elements that have a class of featureList with one or more li children that contain the text, 'Model'.

How can I remove or replace SVG content?

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();

Sorting data based on second column of a file

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54

jQuery get the id/value of <li> element after click function

$("#myid li").click(function() {
    alert(this.id); // id of clicked li by directly accessing DOMElement property
    alert($(this).attr('id')); // jQuery's .attr() method, same but more verbose
    alert($(this).html()); // gets innerHTML of clicked li
    alert($(this).text()); // gets text contents of clicked li
});

If you are talking about replacing the ID with something:

$("#myid li").click(function() {
    this.id = 'newId';

    // longer method using .attr()
    $(this).attr('id', 'newId');
});

Demo here. And to be fair, you should have first tried reading the documentation:

How to fade changing background image

This may help

HTML

<div id="textcontainer">        
    <span id="sometext">This is some information </span>
    <div id="container">

    </div>
</div>

CSS

#textcontainer{
    position:relative;
    border:1px solid #000;
    width :300px;
    height:300px;
}
#container{
    background-image :url("http://dcooper.org/gallery/cf_appicon.jpg");
    width :100%;
    height:100%;
}
#sometext{
    position:absolute;
    top:50%;
    left:50%;
}

Js

$('#container').css('opacity','.1');

Getting only response header from HTTP POST using curl

The other answers require the response body to be downloaded. But there's a way to make a POST request that will only fetch the header:

curl -s -I -X POST http://www.google.com

An -I by itself performs a HEAD request which can be overridden by -X POST to perform a POST (or any other) request and still only get the header data.

Tensorflow import error: No module named 'tensorflow'

In Windows 64, if you did this sequence correctly:

Anaconda prompt:

conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow

Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:

conda install spyder

This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.

Always prefer to install these libraries with "conda install" instead of "pip".

Setting the default Java character encoding

Not clear on what you do and don't have control over at this point. If you can interpose a different OutputStream class on the destination file, you could use a subtype of OutputStream which converts Strings to bytes under a charset you define, say UTF-8 by default. If modified UTF-8 is suffcient for your needs, you can use DataOutputStream.writeUTF(String):

byte inbytes[] = new byte[1024];
FileInputStream fis = new FileInputStream("response.txt");
fis.read(inbytes);
String in = new String(inbytes, "UTF8");
DataOutputStream out = new DataOutputStream(new FileOutputStream("response-2.txt"));
out.writeUTF(in); // no getBytes() here

If this approach is not feasible, it may help if you clarify here exactly what you can and can't control in terms of data flow and execution environment (though I know that's sometimes easier said than determined). Good luck.

How do I stretch a background image to cover the entire HTML element?

The following code I use mostly for achieving the asked effect:

body {
    background-image: url('../images/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
}

Android: keep Service running when app is killed

The reason for this is that you are trying to use an IntentService. Here is the line from the API Docs

The IntentService does the following:

Stops the service after all start requests have been handled, so you never have to call stopSelf().

Thus if you want your service to run indefinitely i suggest you extend the Service class instead. However this does not guarantee your service will run indefinitely. Your service will still have a chance of being killed by the kernel in a state of low memory if it is low priority.So you have two options:
1)Keep it running in the foreground by calling the startForeground() method.
2)Restart the service if it gets killed. Here is a part of the example from the docs where they talk about restarting the service after it is killed

 public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the 
      // start ID so we know which request we're stopping when we finish the job 
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);

      // If we get killed, after returning from here, restart 
      return START_STICKY;
  }  

Get file from project folder java

This sounds like the file is embedded within your application.

You should be using getClass().getResource("/path/to/your/resource.txt"), which returns an URL or getClass().getResourceAsStream("/path/to/your/resource.txt");

If it's not an embedded resource, then you need to know the relative path from your application's execution context to where your file exists

What is the purpose of the var keyword and when should I use it (or omit it)?

As someeone trying to learn this this is how I see it. The above examples were maybe a bit overly complicated for a beginner.

If you run this code:

var local = true;
var global = true;


function test(){
  var local = false;
  var global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output will read as: false, false, true, true

Because it sees the variables in the function as seperate from those outside of it, hence the term local variable and this was because we used var in the assignment. If you take away the var in the function so it now reads like this:

var local = true;
var global = true;


function test(){
  local = false;
  global = false;
  console.log(local)
  console.log(global)
}

test();

console.log(local);
console.log(global);

The output is false, false, false, false

This is because rather than creating a new variable in the local scope or function it simply uses the global variables and reassigns them to false.

How to Create simple drag and Drop in angularjs

adapt-strap has very light weight module for this. here is the fiddle. Here are some attributes that are supported. There are more.

ad-drag="true"
ad-drag-data="car"
ad-drag-begin="onDragStart($data, $dragElement, $event);"
ad-drag-end="onDataEnd($data, $dragElement, $event);"

How can I increment a char?

Check this: USING FOR LOOP

for a in range(5):
    x='A'
    val=chr(ord(x) + a)
    print(val)

LOOP OUTPUT: A B C D E

How can I format a number into a string with leading zeros?

Since nobody has yet mentioned this, if you are using C# version 6 or above (i.e. Visual Studio 2015) then you can use string interpolation to simplify your code. So instead of using string.Format(...), you can just do this:

Key = $"{i:D2}";

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

How to make an image center (vertically & horizontally) inside a bigger div

another way is to create a table with valign, of course. This would work regardless of you knowing the div's height or not.

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

but you should always stick to just css whenever possible.

Access denied for user 'test'@'localhost' (using password: YES) except root user

For annoying searching getting here after searching for this error message:

Access denied for user 'someuser@somewhere' (using password: YES)

The issue for me was not enclosing the password in quotes. eg. I needed to use -p'password' instead of -ppassword

Prevent scroll-bar from adding-up to the Width of page on Chrome

Probably

html {
    width: 100vw;
}

is just what you want.

Facebook API: Get fans of / people who like a page

Use this.

https://www.facebook.com/browse/?type=page_fans&page_id=<your page id>

It will return up to 500 of the most recent likes.

http://www.facebook.com/browse/?type=page_fans&page_id=<your page id>&start=400

Each page will give you 100 fans. Change start value to (0, 100, 200, 300, 400) to get the first 500. If start is >= 401, the page will be blank :(

VMware Workstation and Device/Credential Guard are not compatible

For those who might be encountering this issue with recent changes to your computer involving Hyper-V, you'll need to disable it while using VMWare or VirtualBox. They don't work together. Windows Sandbox and WSL 2 need the Hyper-V Hypervisor on, which currently breaks VMWare. Basically, you'll need to run the following commands to enable/disable Hyper-V services on next reboot.

To disable Hyper-V and get VMWare working, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype off

To re-enable Hyper-V and break VMWare for now, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype auto

You'll need to reboot after that. I've written a PowerShell script that will toggle this for you and confirm it with dialog boxes. It even self-elevates to Administrator using this technique so that you can just right click and run the script to quickly change your Hyper-V mode. It could easily be modified to reboot for you as well, but I personally didn't want that to happen. Save this as hypervisor.ps1 and make sure you've run Set-ExecutionPolicy RemoteSigned so that you can run PowerShell scripts.

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
    $newProcess.Arguments = "-windowstyle hidden & '" + $script:MyInvocation.MyCommand.Path + "'"

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

Add-Type -AssemblyName System.Windows.Forms


$state = bcdedit /enum | Select-String -Pattern 'hypervisorlaunchtype\s*(\w+)\s*'


if ($state.matches.groups[1].ToString() -eq "Off"){

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Enable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype auto
        [System.Windows.Forms.MessageBox]::Show("Enabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

} else {

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Disable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype off
        [System.Windows.Forms.MessageBox]::Show("Disabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

}

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

Summary:

I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

how to put image in center of html page?

Hey now you can give to body background image

and set the background-position:center center;

as like this

body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}

PHP Fatal error: Class 'PDO' not found

I had the same problem on GoDaddy. I added the extension=pdo.so to php.ini, still didn't work. And then only one thing came to my mind: Permissions

Before uploading the file, kill all PHP processes(cPanel->PHP Processes).

The problem was that with the file permissions, it was set to 0644 and was not executable . You need to set the file permission at least 0755.

Permissions

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

3 column layout HTML/CSS

.container{
height:100px;
width:500px;
border:2px dotted #F00;
border-left:none;
border-right:none;
text-align:center;
}
.container div{
display: inline-block;
border-left: 2px dotted #ccc;
vertical-align: middle;
line-height: 100px;
} 
 .column-left{ float: left; width: 32%;  height:100px;}
.column-right{ float: right; width: 32%;  height:100px; border-right: 2px dotted #ccc;}
.column-center{ display: inline-block; width: 33%; height:100px;}

 <div class="container">
   <div class="column-left">Column left</div>
   <div class="column-center">Column center</div>
   <div class="column-right">Column right</div>
</div> 

See this link http://jsfiddle.net/bipin_kumar/XD8RW/2/

Byte[] to ASCII

You can use:

System.Text.Encoding.ASCII.GetString(buf);

But sometimes you will get a weird number instead of the string you want. In that case, your original string may have some hexadecimal character when you see it. If it's the case, you may want to try this:

System.Text.Encoding.UTF8.GetString(buf);

Or as a last resort:

System.Text.Encoding.Default.GetString(bytearray);

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

This can happen if you sign your application with a different certificate. You can always use

adb install -r myapk.apk

to overwrite an existing apk on your device, but you will still get the error if you signed the new apk with a different certificate that of the installed apk.

In that scenario you would need to uninstall the apk from your device before attempting an install. However, this can also impact your application since your original signing may be tied to certain Developor API's, so you may need to update the console with your new credentials.

Looping each row in datagridview

I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.

foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
    File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}

How to get File Created Date and Modified Date

You could use below code:

DateTime creation = File.GetCreationTime(@"C:\test.txt");
DateTime modification = File.GetLastWriteTime(@"C:\test.txt");

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

Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

/var/log/php-fpm# cat www-error.log | grep mycode.php

And I have the output:

[04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458

This helps me find the line where I have the typo.

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']