Programs & Examples On #Bankers rounding

How do you round a number to two decimal places in C#?

This is for rounding to 2 decimal places in C#:

label8.Text = valor_cuota .ToString("N2") ;

In VB.NET:

 Imports System.Math
 round(label8.text,2)

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

convert datetime to date format dd/mm/yyyy

As everyone else said, but remember CultureInfo.InvariantCulture!

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

OR escape the '/'.

Converting from signed char to unsigned char and back again?

There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.

Assuming you mean the latter, the formally correct way is

signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;

which at least gcc properly recognizes as a no-op.

"unrecognized import path" with go get

I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.

The first step was to purge existing go:

sudo apt-get purge golang*

Which outputs following warnings:

dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing golang-go.tools, directory '/usr/lib/go' not empty so not removed

It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.

All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)

# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go golang-go.tools

What is the difference between Jupyter Notebook and JupyterLab?

At this time (mid 2019), with JupyterLab 1.0 release, as a user, I think we should adopt JupyterLab for daily use. And from the JupyterLab official documentation:

The current release of JupyterLab is suitable for general daily use.

and

JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab.


Note that JupyterLab has a extensible modular architecture. So in the old days, there is just one Jupyter Notebook, and now with JupyterLab (and in the future), Notebook is just one of the core applications in JupyterLab (along with others like code Console, command-line Terminal, and a Text Editor).

Sleeping in a batch file

There are lots of ways to accomplish a 'sleep' in cmd/batch:

My favourite one:

TIMEOUT /NOBREAK 5 >NUL 2>NUL

This will stop the console for 5 seconds, without any output.

Most used:

ping localhost -n 5 >NUL 2>NUL

This will try to make a connection to localhost 5 times. Since it is hosted on your computer, it will always reach the host, so every second it will try the new every second. The -n flag indicates how many times the script will try the connection. In this case is 5, so it will last 5 seconds.

Variants of the last one:

ping 1.1.1.1 -n 5 >nul

In this script there are some differences comparing it with the last one. This will not try to call localhost. Instead, it will try to connect to 1.1.1.1, a very fast website. The action will last 5 seconds only if you have an active internet connection. Else it will last approximately 15 to complete the action. I do not recommend using this method.

ping 127.0.0.1 -n 5 >nul

This is exactly the same as example 2 (most used). Also, you can also use:

ping [::1] -n 5 >nul

This instead, uses IPv6's localhost version.

There are lots of methods to perform this action. However, I prefer method 1 for Windows Vista and later versions and the most used method (method 2) for earlier versions of the OS.

Why do I keep getting Delete 'cr' [prettier/prettier]?

All the answers above are correct, but when I use windows and disable the Prettier ESLint extension rvest.vs-code-prettier-eslint the issue will be fixed.

How to bind to a PasswordBox in MVVM

I have done like:

XAML:

<PasswordBox x:Name="NewPassword" PasswordChanged="NewPassword_PasswordChanged"/>
<!--change tablenameViewSource: yours!-->
<Grid DataContext="{StaticResource tablenameViewSource}" Visibility="Hidden">
        <TextBox x:Name="Password" Text="{Binding password, Mode=TwoWay}"/>
</Grid>

C#:

private void NewPassword_PasswordChanged(object sender, RoutedEventArgs e)
    {
        try
        {
           //change tablenameDataTable: yours! and tablenameViewSource: yours!
           tablenameDataTable.Rows[tablenameViewSource.View.CurrentPosition]["password"] = NewPassword.Password;
        }
        catch
        {
            this.Password.Text = this.NewPassword.Password;
        }
    }

It works for me!

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

Use CSS3 transitions with gradient backgrounds

I wanted to have a div appear like a 3D sphere and transition through colors. I discovered that gradient background colors don't transition (yet). I placed a radial gradient background in front of the element (using z-index) with a transitioning solid background.

/* overlay */
z-index : 1;
background : radial-gradient( ellipse at 25% 25%, rgba( 255, 255, 255, 0 ) 0%, rgba( 0, 0, 0, 1 ) 100% );

then the div.ball underneath:

transition : all 1s cubic-bezier(0.25, 0.46, 0.45, 0.94);

then changed the background color of the div.ball and voila!

https://codepen.io/keldon/pen/dzPxZP

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a distributed version control system. It usually runs at the command line of your local machine. It keeps track of your files and modifications to those files in a "repository" (or "repo"), but only when you tell it to do so. (In other words, you decide which files to track and when to take a "snapshot" of any modifications.)

    In contrast, GitHub is a website that allows you to publish your Git repositories online, which can be useful for many reasons (see #3).

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    Git is known as a "distributed" (rather than "centralized") version control system because you can run it locally and disconnected from the Internet, and then "push" your changes to a remote system (such as GitHub) whenever you like. Thus, repo changes only appear on GitHub when you manually tell Git to push those changes.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, you can use Git without GitHub. Git is the "workhorse" program that actually tracks your changes, whereas GitHub is simply hosting your repositories (and provides additional functionality not available in Git). Here are some of the benefits of using GitHub:

    • It provides a backup of your files.
    • It gives you a visual interface for navigating your repos.
    • It gives other people a way to navigate your repos.
    • It makes repo collaboration easy (e.g., multiple people contributing to the same project).
    • It provides a lightweight issue tracking system.
  4. How does Git compare to a backup system such as Time Machine?

    Git does backup your files, though it gives you much more granular control than a traditional backup system over what and when you backup. Specifically, you "commit" every time you want to take a snapshot of changes, and that commit includes both a description of your changes and the line-by-line details of those changes. This is optimal for source code because you can easily see the change history for any given file at a line-by-line level.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, this is a manual process.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • Git employs a powerful branching system that allows you to work on multiple, independent lines of development simultaneously and then merge those branches together as needed.
    • Git allows you to view the line-by-line differences between different versions of your files, which makes troubleshooting easier.
    • Git forces you to describe each of your commits, which makes it significantly easier to track down a specific previous version of a given file (and potentially revert to that previous version).
    • If you ever need help with your code, having it tracked by Git and hosted on GitHub makes it much easier for someone else to look at your code.

For getting started with Git, I recommend the online book Pro Git as well as GitRef as a handy reference guide. For getting started with GitHub, I like the GitHub's Bootcamp and their GitHub Guides. Finally, I created a short videos series to introduce Git and GitHub to beginners.

How to create empty constructor for data class in Kotlin Android

If you give default values to all the fields - empty constructor is generated automatically by Kotlin.

data class User(var id: Long = -1,
                var uniqueIdentifier: String? = null)

and you can simply call:

val user = User()

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

How to get the URL without any parameters in JavaScript?

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

How to give a user only select permission on a database

You could add the user to the Database Level Role db_datareader.

Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.

See Books Online for reference:

http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx

You can add a database user to a database role using the following query:

EXEC sp_addrolemember N'db_datareader', N'userName'

Effects of the extern keyword on C functions

The extern keyword takes on different forms depending on the environment. If a declaration is available, the extern keyword takes the linkage as that specified earlier in the translation unit. In the absence of any such declaration, extern specifies external linkage.

static int g();
extern int g(); /* g has internal linkage */

extern int j(); /* j has tentative external linkage */

extern int h();
static int h(); /* error */

Here are the relevant paragraphs from the C99 draft (n1256):

6.2.2 Linkages of identifiers

[...]

4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

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

Microsoft has provided for you on their MSDN blogs: MVC 5 for VS2012. From that blog:

We have released ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This release brings a ton of great improvements, and include some fantastic enhancements to ASP.NET MVC 5, Web API 2, Scaffolding and Entity Framework to users of Visual Studio 2012 and Visual Studio 2012 Express for Web.

You can download and start using these features now.

The download link is to a Web Platform Installer that will allow you to start a new MVC5 project from VS2012.

Git error on git pull (unable to update local ref)

rm .git/refs/remotes/origin/master

It works to me!

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

ng-repeat :filter by single field

If you were to do the following:

<li class="active-item" ng-repeat="item in mc.pageData.items | filter: { itemTypeId: 2, itemStatus: 1 } | orderBy : 'listIndex'"
                id="{{item.id}}">
    <span class="item-title">{{preference.itemTitle}}</span>
</li>

...you would not only get items of itemTypeId 2 and itemStatus 1, but you would also get items with itemType 20, 22, 202, 123 and itemStatus 10, 11, 101, 123. This is because the filter: {...} syntax works like a string contains query.

However, if you were to add the : true condition, it would do filter by exact match:

<li class="active-item" ng-repeat="item in mc.pageData.items | filter: { itemTypeId: 2, itemStatus: 1 } : true | orderBy : 'listIndex'"
                id="{{item.id}}">
    <span class="item-title">{{preference.itemTitle}}</span>
</li>

Sleep for milliseconds

Select call is a way of having more precision (sleep time can be specified in nanoseconds).

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

How to display 3 buttons on the same line in css

The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:

<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc. 

The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.

pandas get rows which are NOT in other dataframe

As already hinted at, isin requires columns and indices to be the same for a match. If match should only be on row contents, one way to get the mask for filtering the rows present is to convert the rows to a (Multi)Index:

In [77]: df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5, 3], 'col2' : [10, 11, 12, 13, 14, 10]})
In [78]: df2 = pandas.DataFrame(data = {'col1' : [1, 3, 4], 'col2' : [10, 12, 13]})
In [79]: df1.loc[~df1.set_index(list(df1.columns)).index.isin(df2.set_index(list(df2.columns)).index)]
Out[79]:
   col1  col2
1     2    11
4     5    14
5     3    10

If index should be taken into account, set_index has keyword argument append to append columns to existing index. If columns do not line up, list(df.columns) can be replaced with column specifications to align the data.

pandas.MultiIndex.from_tuples(df<N>.to_records(index = False).tolist())

could alternatively be used to create the indices, though I doubt this is more efficient.

How to view an HTML file in the browser with Visual Studio Code

If you would like to have live reload you can use gulp-webserver, which will watch for your file changes and reload page, this way you don't have to press F5 every time on your page:

Here is how to do it:

  • Open command prompt (cmd) and type

    npm install --save-dev gulp-webserver

  • Enter Ctrl+Shift+P in VS Code and type Configure Task Runner. Select it and press enter. It will open tasks.json file for you. Remove everything from it end enter just following code

tasks.json

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "args": [
        "--no-color"
    ],
    "tasks": [
        {
            "taskName": "webserver",
            "isBuildCommand": true,
            "showOutput": "always"
        }
    ]
}
  • In the root directory of your project add gulpfile.js and enter following code:

gulpfile.js

var gulp = require('gulp'),
    webserver = require('gulp-webserver');

gulp.task('webserver', function () {
    gulp.src('app')
        .pipe(webserver({
            livereload: true,
            open: true
        }));
});
  • Now in VS Code enter Ctrl+Shift+P and type "Run Task" when you enter it you will see your task "webserver" selected and press enter.

Your webserver now will open your page in your default browser. Now any changes that you will do to your HTML or CSS pages will be automatically reloaded.

Here is an information on how to configure 'gulp-webserver' for instance port, and what page to load, ...

You can also run your task just by entering Ctrl+P and type task webserver

Ansible playbook shell output

The debug module could really use some love, but at the moment the best you can do is use this:

- hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
      register: ps

    - debug: var=ps.stdout_lines

It gives an output like this:

ok: [host1] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 1.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@notty ",
        " 0.2 root     java",
        " 0.0 root     sort -r -k1"
    ]
}
ok: [host2] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 4.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@notty ",
        " 0.1 root     java",
        " 0.0 root     sort -r -k1"
    ]
}

What are NDF Files?

An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

CSS background image in :after element

A couple things

(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.

(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:

.button:after {
    content: "";
    width: 30px;
    height: 30px;
    background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
    top: 10px;
    right: 5px;
    position: absolute;
    display: inline-block;
}

I updated your jsFiddle to this and it showed the image.

Keras, how do I predict after I trained a model?

Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.

For example:

new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])

How to save and load cookies using Python + Selenium WebDriver

This is code I used in Windows. It works.

for item in COOKIES.split(';'):
    name,value = item.split('=', 1)
    name=name.replace(' ', '').replace('\r', '').replace('\n', '')
    value = value.replace(' ', '').replace('\r', '').replace('\n', '')
    cookie_dict={
            'name':name,
            'value':value,
            "domain": "",  # Google Chrome
            "expires": "",
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
    self.driver_.add_cookie(cookie_dict)

Test if remote TCP port is open from a shell script

check ports using bash

Example

$ ./test_port_bash.sh 192.168.7.7 22

the port 22 is open

Code

HOST=$1
PORT=$2
exec 3> /dev/tcp/${HOST}/${PORT}
if [ $? -eq 0 ];then echo "the port $2 is open";else echo "the port $2 is closed";fi

jQuery removing '-' character from string

$mylabel.text( $mylabel.text().replace('-', '') );

Since text() gets the value, and text( "someValue" ) sets the value, you just place one inside the other.

Would be the equivalent of doing:

var newValue = $mylabel.text().replace('-', '');
$mylabel.text( newValue );

EDIT:

I hope I understood the question correctly. I'm assuming $mylabel is referencing a DOM element in a jQuery object, and the string is in the content of the element.

If the string is in some other variable not part of the DOM, then you would likely want to call the .replace() function against that variable before you insert it into the DOM.

Like this:

var someVariable = "-123456";
$mylabel.text( someVariable.replace('-', '') );

or a more verbose version:

var someVariable = "-123456";
someVariable = someVariable.replace('-', '');
$mylabel.text( someVariable );

Generic deep diff between two objects

Here is a JavaScript library which you can use for finding diff between two JavaScript objects:

Github URL: https://github.com/cosmicanant/recursive-diff

Npmjs url: https://www.npmjs.com/package/recursive-diff

You can use recursive-diff library in browser as well as Node.js. For browser, do the following:

<script type="text" src="https://unpkg.com/recursive-diff@latest/dist/recursive-diff.min.js"/>
<script type="text/javascript">
     const ob1 = {a:1, b: [2,3]};
     const ob2 = {a:2, b: [3,3,1]};
     const delta = recursiveDiff.getDiff(ob1,ob2); 
     /* console.log(delta) will dump following data 
     [
         {path: ['a'], op: 'update', val: 2}
         {path: ['b', '0'], op: 'update',val: 3},
         {path: ['b',2], op: 'add', val: 1 },
     ]
      */
     const ob3 = recursiveDiff.applyDiff(ob1, delta); //expect ob3 is deep equal to ob2
 </script>

Whereas in node.js you can require 'recursive-diff' module and use it like below:

const diff = require('recursive-diff');
const ob1 = {a: 1}, ob2: {b:2};
const diff = diff.getDiff(ob1, ob2);

How do I add a reference to the MySQL connector for .NET?

As mysql official documentation:

Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

Online Documentation:

MySQL Connector/Net Installation Instructions

Jquery href click - how can I fire up an event?

You are binding the click event to anchors with an href attribute with value sign_new.

Either bind anchors with class sign_new or bind anchors with href value #sign_up. I would prefer the former.

jQuery animate margin top

use 'marginTop' instead of MarginTop

$(this).find('.info').animate({ 'marginTop': '-50px', opacity: 0.5 }, 1000);

Function names in C++: Capitalize or not?

There isn't a 'correct way'. They're all syntactically correct, though there are some conventions. You could follow the Google style guide, although there are others out there.

From said guide:

Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable().

In Bootstrap open Enlarge image in modal

I know your question is tagged as boostrap-modal (althought you didn't mentioned Bootstrap explicity neither), but I loved to see the simple way W3.CSS solved this and I think is good to share it.

  <img src="/myImage.png" style="width:30%;cursor:zoom-in"
  onclick="document.getElementById('modal01').style.display='block'">

  <div id="modal01" class="w3-modal" onclick="this.style.display='none'">
    <div class="w3-modal-content w3-animate-zoom">
      <img src="/myImage.png" style="width:100%">
    </div>
  </div>

I let you a link to the W3School modal image example to see the headers to make W3.CSS work.

How do I add target="_blank" to a link within a specified div?

Inline:

$('#link_other').find('a').attr('target','_blank');

Can I create view with parameter in MySQL?

Actually if you create func:

create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;

and view:

create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;

Then you can call a view with a parameter:

select s.* from (select @p1:=12 p) parm , h_parm s;

I hope it helps.

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

Flutter does not find android sdk

I assume this is this known issue https://github.com/flutter/flutter/issues/13750

You need to fix the path to the SDK manually until this is fixed in the file

my_flutter_project/android/local.properties

update

Add $ANDROID_HOME\sdk\tools and $ANDROID_HOME\sdk\platform-tools to the PATH environment variable.

What's the advantage of a Java enum versus a class with public static final fields?

There are many good answers here, but none mentiones that there are highly optimized implementations of the Collection API classes/interfaces specifically for enums:

These enum specific classes only accept Enum instances (the EnumMap only accept Enums only as keys), and whenever possible, they revert to compact representation and bit manipulation in their implementation.

What does this mean?

If our Enum type has no more that 64 elements (most of real-life Enum examples will qualify for this), the implementations store the elements in a single long value, each Enum instance in question will be associated with a bit of this 64-bit long long. Adding an element to an EnumSet is simply just setting the proper bit to 1, removing it is just setting that bit to 0. Testing if an element is in the Set is just one bitmask test! Now you gotta love Enums for this!

CSS smooth bounce animation

Here is code not using the percentage in the keyframes. Because you used percentages the animation does nothing a long time.

  • 0% translate 0px
  • 20% translate 0px
  • etc.

How does this example work:

  1. We set an animation. This is a short hand for animation properties.
  2. We immediately start the animation since we use from and to in the keyframes. from is = 0% and to is = 100%
  3. We can now control how fast it will bounce by setting the animation time: animation: bounce 1s infinite alternate; the 1s is how long the animation will last.

_x000D_
_x000D_
.ball {_x000D_
  margin-top: 50px;_x000D_
  border-radius: 50%;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background-color: cornflowerblue;_x000D_
  border: 2px solid #999;_x000D_
  animation: bounce 1s infinite alternate;_x000D_
  -webkit-animation: bounce 1s infinite alternate;_x000D_
}_x000D_
@keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}
_x000D_
<div class="ball"></div>
_x000D_
_x000D_
_x000D_

Dynamically access object property using variable

Following is an ES6 example of how you can access the property of an object using a property name that has been dynamically generated by concatenating two strings.

var suffix = " name";

var person = {
    ["first" + suffix]: "Nicholas",
    ["last" + suffix]: "Zakas"
};

console.log(person["first name"]);      // "Nicholas"
console.log(person["last name"]);       // "Zakas"

This is called computed property names

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

Java Switch Statement - Is "or"/"and" possible?

The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.

// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
  // handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
  // handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
  // handle digit case
} else {
  // handle consonant case, assuming other characters are not possible
}

Of course, if this gets any more complicated, I'd recommend a regex matcher.

Winforms TableLayoutPanel adding rows programmatically

I just did this last week. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns, then your code should work:

// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);

Here is some working code that seems similar to what you are doing:

    private Int32 tlpRowCount = 0;

    private void BindAddress()
    {
        Addlabel(Addresses.Street);
        if (!String.IsNullOrEmpty(Addresses.Street2))
        {
            Addlabel(Addresses.Street2);
        }
        Addlabel(Addresses.CityStateZip);
        if (!String.IsNullOrEmpty(Account.Country))
        {
            Addlabel(Address.Country);
        }
        Addlabel(String.Empty); // Notice the empty label...
    }

    private void Addlabel(String text)
    {            
        label = new Label();
        label.Dock = DockStyle.Fill;
        label.Text = text;
        label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        tlpAddress.Controls.Add(label, 1, tlpRowCount);
        tlpRowCount++;
    }

The TableLayoutPanel always gives me fits with size. In my example above, I'm filing an address card that might grow or shrink depending on the account having an address line two, or a country. Because the last row, or column, of the table layout panel will stretch, I throw the empty label in there to force a new empty row, then everything lines up nicely.

Here is the designer code so you can see the table I start with:

        //
        // tlpAddress
        // 
        this.tlpAddress.AutoSize = true;
        this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
        this.tlpAddress.ColumnCount = 2;
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
        this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tlpAddress.Location = new System.Drawing.Point(0, 0);
        this.tlpAddress.Name = "tlpAddress";
        this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
        this.tlpAddress.RowCount = 2;
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.Size = new System.Drawing.Size(220, 95);
        this.tlpAddress.TabIndex = 0;

How can I get Eclipse to show .* files?

1. From Package Explorer open the Filters... dialog:

enter image description here

2. Then uncheck .* resources option:

enter image description here

How to set JAVA_HOME in Mac permanently?

I was facing the same issue in MAC Catalina, If I edit .bash_profile i found export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home But When I run terminal echo $JAVA_HOME it was returning empty, Later I found that the file .zshrc was missing I created this file with

touch .zshrc 

Then edit it by nano .zshrc and wrote

source ~/.bash_profile

Which solves my issue permanently

Set markers for individual points on a line in Matplotlib

Hello There is an example:

import numpy as np
import matplotlib.pyplot as ptl

def grafica_seno_coseno():
    x = np.arange(-4,2*np.pi, 0.3)
    y = 2*np.sin(x)
    y2 = 3*np.cos(x)
    ptl.plot(x, y,  '-gD')
    ptl.plot(x, y2, '-rD')
    for xitem,yitem in np.nditer([x,y]):
        etiqueta = "{:.1f}".format(xitem)
        ptl.annotate(etiqueta, (xitem,yitem), textcoords="offset points",xytext=(0,10),ha="center")
    for xitem,y2item in np.nditer([x,y2]):
        etiqueta2 = "{:.1f}".format(xitem)
        ptl.annotate(etiqueta2, (xitem,y2item), textcoords="offset points",xytext=(0,10),ha="center")
    ptl.grid(True)
    return ptl.show()

How to get the Mongo database specified in connection string in C#

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

First of all: I'm the author of the The Single Page Interface Manifesto cited by raganwald

As raganwald has explained very well, the most important aspect of the Single Page Interface (SPI) approach used in FaceBook and Twitter is the use of hash # in URLs

The character ! is added only for Google purposes, this notation is a Google "standard" for crawling web sites intensive on AJAX (in the extreme Single Page Interface web sites). When Google's crawler finds an URL with #! it knows that an alternative conventional URL exists providing the same page "state" but in this case on load time.

In spite of #! combination is very interesting for SEO, is only supported by Google (as far I know), with some JavaScript tricks you can build SPI web sites SEO compatible for any web crawler (Yahoo, Bing...).

The SPI Manifesto and demos do not use Google's format of ! in hashes, this notation could be easily added and SPI crawling could be even easier (UPDATE: now ! notation is used and remains compatible with other search engines).

Take a look to this tutorial, is an example of a simple ItsNat SPI site but you can pick some ideas for other frameworks, this example is SEO compatible for any web crawler.

The hard problem is to generate any (or selected) "AJAX page state" as plain HTML for SEO, in ItsNat is very easy and automatic, the same site is in the same time SPI or page based for SEO (or when JavaScript is disabled for accessibility). With other web frameworks you can ever follow the double site approach, one site is SPI based and another page based for SEO, for instance Twitter uses this "double site" technique.

Node.js throws "btoa is not defined" error

The solutions posted here don't work in non-ascii characters (i.e. if you plan to exchange base64 between Node.js and a browser). In order to make it work you have to mark the input text as 'binary'.

Buffer.from('Hélló wórld!!', 'binary').toString('base64')

This gives you SOlsbPMgd/NybGQhIQ==. If you make atob('SOlsbPMgd/NybGQhIQ==') in a browser it will decode it in the right way. It will do it right also in Node.js via:

Buffer.from('SOlsbPMgd/NybGQhIQ==', 'base64').toString('binary')

If you don't do the "binary part", you will decode wrongly the special chars.

I got it from the implementation of the btoa npm package:

What are "named tuples" in Python?

namedtuple is a factory function for making a tuple class. With that class we can create tuples that are callable by name also.

import collections

#Create a namedtuple class with names "a" "b" "c"
Row = collections.namedtuple("Row", ["a", "b", "c"])   

row = Row(a=1,b=2,c=3) #Make a namedtuple from the Row class we created

print row    #Prints: Row(a=1, b=2, c=3)
print row.a  #Prints: 1
print row[0] #Prints: 1

row = Row._make([2, 3, 4]) #Make a namedtuple from a list of values

print row   #Prints: Row(a=2, b=3, c=4)

Redirecting output to $null in PowerShell, but ensuring the variable remains set

using a function:

function run_command ($command)
{
    invoke-expression "$command *>$null"
    return $_
}

if (!(run_command "dir *.txt"))
{
    if (!(run_command "dir *.doc"))
    {
        run_command "dir *.*"
    }
}

or if you like one-liners:

function run_command ($command) { invoke-expression "$command  "|out-null; return $_ }

if (!(run_command "dir *.txt")) { if (!(run_command "dir *.doc")) { run_command "dir *.*" } }

Predicate Delegates in C#

If you're in VB 9 (VS2008), a predicate can be a complex function:

Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(AddressOf GreaterThanTwo)
...
Function GreaterThanTwo(ByVal item As Integer) As Boolean
    'do some work'
    Return item > 2
End Function

Or you can write your predicate as a lambda, as long as it's only one expression:

Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(Function(item) item > 2)

Get protocol + host name from URL

>>> import urlparse
>>> url = 'http://stackoverflow.com/questions/1234567/blah-blah-blah-blah'
>>> urlparse.urljoin(url, '/')
'http://stackoverflow.com/'

Getting all types in a namespace via reflection

//a simple combined code snippet 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MustHaveAttributes
{
  class Program
  {
    static void Main ( string[] args )
    {
      Console.WriteLine ( " START " );

      // what is in the assembly
      Assembly a = Assembly.Load ( "MustHaveAttributes" );
      Type[] types = a.GetTypes ();
      foreach (Type t in types)
      {

        Console.WriteLine ( "Type is {0}", t );
      }
      Console.WriteLine (
         "{0} types found", types.Length );

      #region Linq
      //#region Action


      //string @namespace = "MustHaveAttributes";

      //var q = from t in Assembly.GetExecutingAssembly ().GetTypes ()
      //        where t.IsClass && t.Namespace == @namespace
      //        select t;
      //q.ToList ().ForEach ( t => Console.WriteLine ( t.Name ) );


      //#endregion Action  
      #endregion

      Console.ReadLine ();
      Console.WriteLine ( " HIT A KEY TO EXIT " );
      Console.WriteLine ( " END " );
    }
  } //eof Program


  class ClassOne
  {

  } //eof class 

  class ClassTwo
  {

  } //eof class


  [System.AttributeUsage ( System.AttributeTargets.Class |
    System.AttributeTargets.Struct, AllowMultiple = true )]
  public class AttributeClass : System.Attribute
  {

    public string MustHaveDescription { get; set; }
    public string MusHaveVersion { get; set; }


    public AttributeClass ( string mustHaveDescription, string mustHaveVersion )
    {
      MustHaveDescription = mustHaveDescription;
      MusHaveVersion = mustHaveVersion;
    }

  } //eof class 

} //eof namespace 

CSS: Position loading indicator in the center of the screen

You can use this OnLoad or during fetch infos from DB

In HTML Add following code:

<div id="divLoading">
<p id="loading">
    <img src="~/images/spinner.gif">
</p>

In CSS add following Code:

#divLoading {
  margin: 0px;
  display: none;
  padding: 0px;
  position: absolute;
  right: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background-color: rgb(255, 255, 255);
  z-index: 30001;
  opacity: 0.8;}

#loading {
   position: absolute;
   color: White;
  top: 50%;
  left: 45%;}

if you want to show and hide from JS:

  document.getElementById('divLoading').style.display = 'none'; //Not Visible
  document.getElementById('divLoading').style.display = 'block';//Visible

urlencode vs rawurlencode?

The difference is in the return values, i.e:

urlencode():

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 1738 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

rawurlencode():

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 1738 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

The two are very similar, but the latter (rawurlencode) will replace spaces with a '%' and two hex digits, which is suitable for encoding passwords or such, where a '+' is not e.g.:

echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt">';
//Outputs <a href="ftp://user:foo%20%40%2B%25%[email protected]/x.txt">

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

The most easiest way is to make deliberate mistake. For example, I want to see the full SQL query of the following relation:

 public function jobs()
        {
            return $this->belongsToMany(Job::class, 'eqtype_jobs')
                   ->withPivot(['created_at','updated_at','id'])
                   ->orderBy('pivot_created_at','desc');
        }

I just to make a column to be not found, here I choose created_at and I changed it to created_ats by adding trailing s to be:

public function jobs()
            {
                return $this->belongsToMany(Job::class, 'eqtype_jobs')
                       ->withPivot(['created_ats','updated_at','id'])
                       ->orderBy('pivot_created_at','desc');
            }

So, the debuger will return the following error:

(4/4) ErrorException SQLSTATE[42S22]: Column not found: 1054 Unknown column 'eqtype_jobs.created_ats' in 'field list' (SQL: select jobs.*, eqtype_jobs.set_id as pivot_set_id, eqtype_jobs.job_id as pivot_job_id, eqtype_jobs.created_ats as pivot_created_ats, eqtype_jobs.updated_at as pivot_updated_at, eqtype_jobs.id as pivot_id from jobs inner join eqtype_jobs on jobs.id = eqtype_jobs.job_id where eqtype_jobs.set_id = 56 order by pivot_created_at desc limit 20 offset 0) (View: /home/said/www/factory/resources/views/set/show.blade.php)

The above error message returns the full SQL query with the mistake

SQL: select  jobs.*, eqtype_jobs.set_id as pivot_set_id,  eqtype_jobs.job_id as pivot_job_id, eqtype_jobs.created_ats as pivot_created_ats, eqtype_jobs.updated_at as  pivot_updated_at, eqtype_jobs.id as pivot_id from jobs inner join eqtype_jobs on jobs.id = eqtype_jobs.job_id where  eqtype_jobs.set_id = 56 order by pivot_created_at desc limit 20 offset 0

Now, just remove the extra s from created_at and test this SQL as you like in any SQL editor such as phpMyAdmin SQL editor!

Notice:

The solution has been tested with Laravel 5.4.

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

check null,empty or undefined angularjs

You can do

if($scope.test == null || $scope.test === ""){
  // null == undefined
}

if false, 0 and NaN can also be considered as false values you can just do

if($scope.test){
 //not any of the above
}

Compiling problems: cannot find crt1.o

Ran into this on CentOs 5.4. Noticed that lib64 contained the crt*.o files, but lib did not. Installed glibc-devel through yum which installed the i386 bits and this resolved my issue.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];

[self presentMoviePlayerViewControllerAnimated:playerv];

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

Array to String PHP?

json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array

WHY JSON : You can use it with most of the programming languages, string created by serialize() function of php is readable in PHP only, and you will not like to store such things in your databases specially if database is shared among applications written in different programming languages

How do I combine two dataframes?

Thought to add this here in case someone finds it useful. @ostrokach already mentioned how you can merge the data frames across rows which is

df_row_merged = pd.concat([df_a, df_b], ignore_index=True)

To merge across columns, you can use the following syntax:

df_col_merged = pd.concat([df_a, df_b], axis=1)

What parameters should I use in a Google Maps URL to go to a lat-lon?

New Version queries have a different format

To reach a lat long by url use (e.g.)

https://www.google.com/maps/search/-15.924,-5.719

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Open SQL Server Configuration Manager

  1. Select SQL Server Services from right.
  2. Find your server from right and go to its properties (with right click)
  3. Change log on method to Local System.

enter image description here

enter image description here

How to get file name from file path in android

Old thread but thought I would update;

 File theFile = .......
 String theName = theFile.getName();  // Get the file name
 String thePath = theFile.getAbsolutePath(); // Get the full

More info can be found here; Android File Class

How can I commit files with git?

I don't know your system environment, but it seems, that you have typed:

git commit

And your default editor has been launched. In the worst case scenario (for you) it could have been vim :)

If you don't know how to quit vim, use :q.

If you have further problems, you could use

git commit -m 'Type your commit message here'

How do I use dataReceived event of the SerialPort Port Object in C#?

I think your issue is the line:**

sp.DataReceived += port_OnReceiveDatazz;

Shouldn't it be:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

I've also seen suggestions that you should turn the following options on for your serial port:

sp.DtrEnable = true;    // Data-terminal-ready
sp.RtsEnable = true;    // Request-to-send

You may also have to set the handshake to RequestToSend (via the handshake enumeration).


UPDATE:

Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

So instead of this:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();

Do this:

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

Let me know how that goes.

How to check if a radiobutton is checked in a radiogroup in Android?

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (mRadioButtonMale.isChecked()) {
                text = "male";
            } else {
                text = "female";
            }
        }
    });

OR

 mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            if (mRadioButtonMale.isChecked()) { text = "male"; }
            if(mRadioButtonFemale.isChecked()) { text = "female"; }
        }
    });

How to have an automatic timestamp in SQLite?

Just declare a default value for a field:

CREATE TABLE MyTable(
    ID INTEGER PRIMARY KEY,
    Name TEXT,
    Other STUFF,
    Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

How I redirect to an area is add it as a parameter

@Html.Action("Action", "Controller", new { area = "AreaName" })

for the href portion of a link I use

@Url.Action("Action", "Controller", new { area = "AreaName" })

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

How to change column datatype in SQL database without losing data

If it is a valid change.

you can change the property.

Tools --> Options --> Designers --> Table and Database designers --> Uncheck --> Prevent saving changes that required table re-creation.

Now you can easily change the column name without recreating the table or losing u r records.

Where do I mark a lambda expression async?

To mark a lambda async, simply prepend async before its argument list:

// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
    SQLiteUtils slu = new SQLiteUtils();
    await slu.DeleteGroupAsync(groupName);
}));

SQL Server database backup restore on lower version

You'd have to use the Import/Export wizards in SSMS to migrate everything

There is no "downgrade" possible using backup/restore or detach/attach. Therefore what you have to do is:

  1. Backup the database from the server running the new SSMS/SQL version.
  2. Import data from the generated .bak file, by expanding the "Tasks" menu(after right-clicking the target database) and selecting the "Import Data" option.

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

How to limit text width

Try this:

<style> 
p
{
    width:100px; 
    word-wrap:break-word;
}
</style>

<p>Loremipsumdolorsitamet,consecteturadipiscingelit.Fusce non nisl
non ante malesuada mollis quis ut ipsum. Cum sociis natoque penatibus et magnis dis 
parturient montes, nascetur ridiculus mus. Cras ut adipiscing dolor. Nunc congue, 
tellus vehicula mattis porttitor, justo nisi sollicitudin nulla, a rhoncus lectus lacus 
id turpis. Vivamus diam lacus, egestas nec bibendum eu, mattis eget risus</p>

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

How to convert local time string to UTC?

This thread seems to be missing an option available since Python 3.6: datetime.astimezone(tz=None) can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.

from datetime import datetime, timezone
s = "2008-09-17 14:02:00"

# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7

# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00

# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00

There is one caveat though, see astimezone(None) gives aware datetime, unaware of DST.

First char to upper case

public static String cap1stChar(String userIdea)
{
    char[] stringArray = userIdea.toCharArray();
    stringArray[0] = Character.toUpperCase(stringArray[0]);
    return userIdea = new String(stringArray);
}

Method has the same erasure as another method in type

Java generics uses type erasure. The bit in the angle brackets (<Integer> and <String>) gets removed, so you'd end up with two methods that have an identical signature (the add(Set) you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.

If Java ever gets reified generics, then you could do this, but that's probably unlikely now.

Location Services not working in iOS 8

I was pulling my hair out with the same problem. Xcode gives you the error:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

But even if you implement one of the above methods, it won't prompt the user unless there is an entry in the info.plist for NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription.

Add the following lines to your info.plist where the string values represent the reason you you need to access the users location

<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>

I think these entries may have been missing since I started this project in Xcode 5. I'm guessing Xcode 6 might add default entries for these keys but have not confirmed.

You can find more information on these two Settings here

Use YAML with variables

I had this same question, and after a lot of research, it looks like it's not possible.

The answer from cgat is on the right track, but you can't actually concatenate references like that.

Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):

Define a value and use an exact copy of it later:

default: &default_title This Post Has No Title
title: *default_title

{ or }

example_post: &example
  title: My mom likes roosters
  body: Seriously, she does. And I don't know when it started.
  date: 8/18/2012
first_post: *example
second_post:
  title: whatever, etc.

For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References

Define an object and use it with modifications later:

default: &DEFAULT
  URL:          stooges.com
  throw_pies?:  true  
  stooges:  &stooge_list
    larry:  first_stooge
    moe:    second_stooge
    curly:  third_stooge

development:
  <<: *DEFAULT
  URL:      stooges.local
  stooges: 
    shemp: fourth_stooge

test:
  <<: *DEFAULT
  URL:    test.stooges.qa
  stooges: 
    <<: *stooge_list
    shemp: fourth_stooge

This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804

What is the best way to determine a session variable is null or empty in C#?

Checking for nothing/Null is the way to do it.

Dealing with object types is not the way to go. Declare a strict type and try to cast the object to the correct type. (And use cast hint or Convert)

 private const string SESSION_VAR = "myString";
 string sSession;
 if (Session[SESSION_VAR] != null)
 {
     sSession = (string)Session[SESSION_VAR];
 }
 else
 {
     sSession = "set this";
     Session[SESSION_VAR] = sSession;
 }

Sorry for any syntax violations, I am a daily VB'er

Incrementing a date in JavaScript

None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)

The below AddDays javascript function accounts for daylight saving time:

function addDays(date, amount) {
  var tzOff = date.getTimezoneOffset() * 60 * 1000,
      t = date.getTime(),
      d = new Date(),
      tzOff2;

  t += (1000 * 60 * 60 * 24) * amount;
  d.setTime(t);

  tzOff2 = d.getTimezoneOffset() * 60 * 1000;
  if (tzOff != tzOff2) {
    var diff = tzOff2 - tzOff;
    t += diff;
    d.setTime(t);
  }

  return d;
}

Here are the tests I used to test the function:

    var d = new Date(2010,10,7);
    var d2 = AddDays(d, 1);
    document.write(d.toString() + "<br />" + d2.toString());

    d = new Date(2010,10,8);
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, 1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

    d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
    d2 = AddDays(d, -1)
    document.write("<hr /><br />" +  d.toString() + "<br />" + d2.toString());

How to suppress binary file matching results in grep

There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

grep -I -n -H 


-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

So this might be a way to run grep:

grep -InH your-word *

How to programmatically send SMS on the iPhone?

Follow this procedures

1 .Add MessageUI.Framework to projectenter image description here

2 . Import #import <MessageUI/MessageUI.h> in .h file.

3 . Copy this code for sending message

 if ([MFMessageComposeViewController canSendText]) {
    MFMessageComposeViewController *messageComposer =
    [[MFMessageComposeViewController alloc] init];
    NSString *message = @"Message!!!";
    [messageComposer setBody:message];
    messageComposer.messageComposeDelegate = self;
    [self presentViewController:messageComposer animated:YES completion:nil];
}

4 . Implement delegate method if you want to.

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{


   ///your stuff here 

    [self dismissViewControllerAnimated:YES completion:nil];
}

Run And GO!

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

I know of few packages that support "make uninstall" but many more that support make install DESTDIR=xxx" for staged installs.

You can use this to create a package which you install instead of installing directly from the source. I had no luck with checkinstall but fpm works very well.

This can also help you remove a package previously installed using make install. You simply force install your built package over the make installed one and then uninstall it.

For example, I used this recently to deal with protobuf-3.3.0. On RHEL7:

make install DESTDIR=dest
cd dest
fpm -f -s dir -t rpm -n protobuf -v 3.3.0 \
 --vendor "You Not RedHat" \
 --license "Google?" \
 --description "protocol buffers" \
 --rpm-dist el7 \
 -m [email protected] \
 --url "http:/somewhere/where/you/get/the/package/oritssource" \
 --rpm-autoreqprov \
 usr

 sudo rpm -i -f protobuf-3.3.0-1.el7.x86_64.rpm
 sudo rpm -e protobuf-3.3.0      

Prefer yum to rpm if you can.

On Debian9:

make install DESTDIR=dest
cd dest
fpm -f -s dir -t deb -n protobuf -v 3.3.0 \
-C `pwd` \
--prefix / \
--vendor "You Not Debian" \
--license "$(grep Copyright ../../LICENSE)" \
--description "$(cat README.adoc)" \
--deb-upstream-changelog ../../CHANGES.txt \
 --url "http:/somewhere/where/you/get/the/package/oritssource" \
 usr/local/bin \
 usr/local/lib \
 usr/local/include

 sudo apt install -f *.deb
 sudo apt-get remove protobuf

Prefer apt to dpkg where you can.

I've also posted answer this here

Trying to load local JSON file to show data in a html page using JQuery

You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.

index.html:

<html>
<head>
</head>
<body>
  <script src="data.js"></script>
</body>
</html>

data.js:

var data = {
  "start": {
    "count": "5",
    "title": "start",
    "priorities": [{
      "txt": "Work"
    }, {
      "txt": "Time Sense"
    }, {
      "txt": "Dicipline"
    }, {
      "txt": "Confidence"
    }, {
      "txt": "CrossFunctional"
    }]
  }
}

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Sounds like you want a simple imagemap, I'd recommend to not make it more complex than it needs to be. Here's an article on how to improve imagemaps with svg. It's very easy to do clickable regions in svg itself, just add some <a> elements around the shapes you want to have clickable.

A couple of options if you need something more advanced:

How to stop (and restart) the Rails Server?

Now in rails 5 yu can do:

rails restart

This print by rails --tasks

Restart app by touching tmp/restart.txt

I think that is usefully if you run rails as a demon

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

kenorb’s answer is very useful (and great!).
Among his solutions, maybe this is the most simple one: --trusted-host

For example, in this case you can do

pip install --trusted-host pypi.python.org linkchecker

The pem file(or anything else) is unnecessary.

Windows batch command(s) to read first line from text file

One liner, useful for stdout redirect with ">":

@for /f %%i in ('type yourfile.txt') do @echo %%i & exit

How do I remove the title bar from my app?

Go to styles.xml and change .DarkActionBar for .NoActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
</style>

becomes

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
</style>

if colors are irrelevant to your app, you can actually go for

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" />

JPA - Returning an auto generated id after persist()

This is how I did it:

EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();

Java TreeMap Comparator

You can not sort TreeMap on values.

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare on keys.

To provide sort on values you will need SortedSet. Use

SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
            new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Map.Entry<String, Double> e1,
                        Map.Entry<String, Double> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });

  sortedset.addAll(myMap.entrySet());

To give you an example

    SortedMap<String, Double> myMap = new TreeMap<String, Double>();
    myMap.put("a", 10.0);
    myMap.put("b", 9.0);
    myMap.put("c", 11.0);
    myMap.put("d", 2.0);
    sortedset.addAll(myMap.entrySet());
    System.out.println(sortedset);

Output:

  [d=2.0, b=9.0, a=10.0, c=11.0]

How does one generate a random number in Apple's Swift language?

I used this code:

var k: Int = random() % 10;

How do I detect IE 8 with jQuery?

You should also look at jQuery.support. Feature detection is a lot more reliable than browser detection for coding your functionality (unless you are just trying to log browser versions).

Visual Studio Code: How to show line endings

If you want to set it to LF as default, you can go to File->Preferences->Settings and under user settings you can paste this line in below your other user settings.

"files.eol": "\n"

For example.

"git.confirmSync": false,
"window.zoomLevel": -1,
"workbench.activityBar.visible": true,
"editor.wordWrap": true,
"workbench.iconTheme": "vscode-icons",
"window.menuBarVisibility": "default",
"vsicons.projectDetection.autoReload": true,
"files.eol": "\n"

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

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

pip freeze does it all finding packages however one can simply write the following command to list all paths where python packages are.

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

Add list to set?

Try using * unpack, like below:

>>> a=set('abcde')
>>> a
{'a', 'd', 'e', 'b', 'c'}
>>> l=['f','g']
>>> l
['f', 'g']
>>> {*l, *a}
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
>>> 

Non Editor version:

a=set('abcde')
l=['f', 'g']
print({*l, *a})

Output:

{'a', 'd', 'e', 'f', 'b', 'g', 'c'}

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

Class.forName()-->forName() is the static method of Class class it returns Class class object used for reflection not user class object so you can only call Class class methods on it like getMethods(), getConstructors() etc.

If you care about only running static block of your(Runtime given) class and only getting information of methods,constructors,Modifier etc of your class you can do with this object which you get using Class.forName()

But if you want to access or call your class method (class which you have given at runtime) then you need to have its object so newInstance method of Class class do it for you.It create new instance of the class and return it to you .You just need to type-cast it to your class.

ex-: suppose Employee is your class then

Class a=Class.forName(args[0]); 

//args[0]=cmd line argument to give class at  runtime. 

Employee ob1=a.newInstance();

a.newInstance() is similar to creating object using new Employee().

now you can access all your class visible fields and methods.

Display current date and time without punctuation

A simple example in shell script

#!/bin/bash

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S

C# Public Enums in Classes

Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
}

To Specify:

The name change from card_suits to CardSuit was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).

How long do browsers cache HTTP 301s?

On the latest Google Chrome Version 79, you can use the chrome://net-internals and select on DNS from the left panel, then tap the Clear host cache button

Screenshot of chrome opening the net-internals page

link_to method and click event in Rails

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

"Operation must use an updateable query" error in MS Access

There is no error in the code, but the error is thrown due to the following:

 - Please check whether you have given Read-write permission to MS-Access database file.
 - The Database file where it is stored (say in Folder1) is read-only..? 

suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in C:\Program files all most all c drive files been set read-only so changing this permission solves this Problem.

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

How to Troubleshoot Intermittent SQL Timeout Errors

You are on the right track with your tracing and profiling. what you need to do is look for what the queries that time-out have in common - it is likely they will all be hitting a small subset of tables or indexes. I suspect some application has a long-running update/insert that affects queries on tables that use indexes affected by the updates/inserts.

You have to work backwards a little - given the subset of tables you see timing out, see what indexes are on those tables. Look for other queries that are running at the smae time that touch those tables/indexes. I'm betting you will find a small set of updates/inserts doing this.

Then you have some decisions to make. One option is to changing the locking hints on the queries that are timing out. But that is geenrally bad practice because it will mask the real problem for a while. While you mgiht see the timeouts go away for a while, depending on the hint you choose you might end up with dirty reads and then bogus data coming back from those queries. That might turn out to be worse than the timeouts - hard to say.

Best bet is to figure out which of your applications are submitting the update/inserts you found and dig in to figure out why they take so long.

Difference between Destroy and Delete

A lot of answers already; wanted to jump on with a bit more.

docs:

For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

The delete verbage works differently for ActiveRecord::Association.has_many and ActiveRecord::Base. For the latter, delete will execute SQL DELETE and bypass all validations/callbacks. The former will be executed based on the :dependent option passed into the association. However, during testing, I found the following side effect where callbacks were only ran for delete and not delete_all

dependent: :destroy Example:

class Parent < ApplicationRecord
   has_many :children,
     before_remove: -> (_) { puts "before_remove callback" },
     dependent: :destroy
end

class Child < ApplicationRecord
   belongs_to :parent

   before_destroy -> { puts "before_destroy callback" }
end

> child.delete                            # Ran without callbacks
Child Destroy (99.6ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 21]]

> parent.children.delete(other_child)     # Ran with callbacks
before_remove callback
before_destroy callback
Child Destroy (0.4ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 22]]

> parent.children.delete_all              # Ran without callbacks
Child Destroy (1.0ms)  DELETE FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 1]]

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How to call function that takes an argument in a Django template?

if you have an object you can define it as @property so you can get results without a call, e.g.

class Item:
    @property
    def results(self):
        return something

then in the template:

<% for result in item.results %>
...
<% endfor %>

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Offline Speech Recognition In Android (JellyBean)

Google did quietly enable offline recognition in that Search update, but there is (as yet) no API or additional parameters available within the SpeechRecognizer class. {See Edit at the bottom of this post} The functionality is available with no additional coding, however the user’s device will need to be configured correctly for it to begin working and this is where the problem lies and I would imagine why a lot of developers assume they are ‘missing something’.

Also, Google have restricted certain Jelly Bean devices from using the offline recognition due to hardware constraints. Which devices this applies to is not documented, in fact, nothing is documented, so configuring the capabilities for the user has proved to be a matter of trial and error (for them). It works for some straight away – For those that it doesn't, this is the ‘guide’ I supply them with.

  1. Make sure the default Android Voice Recogniser is set to Google not Samsung/Vlingo
  2. Uninstall any offline recognition files you already have installed from the Google Voice Search Settings
  3. Go to your Android Application Settings and see if you can uninstall the updates for the Google Search and Google Voice Search applications.
  4. If you can't do the above, go to the Play Store see if you have the option there.
  5. Reboot (if you achieved 2, 3 or 4)
  6. Update Google Search and Google Voice Search from the Play Store (if you achieved 3 or 4 or if an update is available anyway).
  7. Reboot (if you achieved 6)
  8. Install English UK offline language files
  9. Reboot
  10. Use utter! with a connection
  11. Switch to aeroplane mode and give it a try
  12. Once it is working, the offline recognition of other languages, such as English US should start working too.

EDIT: Temporarily changing the device locale to English UK also seems to kickstart this to work for some.

Some users reported they still had to reboot a number of times before it would begin working, but they all get there eventually, often inexplicably to what was the trigger, the key to which are inside the Google Search APK, so not in the public domain or part of AOSP.

From what I can establish, Google tests the availability of a connection prior to deciding whether to use offline or online recognition. If a connection is available initially but is lost prior to the response, Google will supply a connection error, it won’t fall-back to offline. As a side note, if a request for the network synthesised voice has been made, there is no error supplied it if fails – You get silence.

The Google Search update enabled no additional features in Google Now and in fact if you try to use it with no internet connection, it will error. I mention this as I wondered if the ability would be withdrawn as quietly as it appeared and therefore shouldn't be relied upon in production.

If you intend to start using the SpeechRecognizer class, be warned, there is a pretty major bug associated with it, which require your own implementation to handle.

Not being able to specifically request offline = true, makes controlling this feature impossible without manipulating the data connection. Rubbish. You’ll get hundreds of user emails asking you why you haven’t enabled something so simple!

EDIT: Since API level 23 a new parameter has been added EXTRA_PREFER_OFFLINE which the Google recognition service does appear to adhere to.

Hope the above helps.

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

I will add my experience using saga in production system in addition to the library author's rather thorough answer.

Pro (using saga):

  • Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.

  • redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.

  • Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.

Con:

  • Generator syntax.

  • Lots of concepts to learn.

  • API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.

Jquery DatePicker Set default date

use defaultDate()

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current [[UI/Datepicker#option-dateFormat|dateFormat]], or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

try this

$("[name=trainingStartFromDate]").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true,defaultDate: new Date()});
$("[name=trainingStartToDate]").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true,defaultDate: +15}); 

how to check for null with a ng-if values in a view with angularjs?

Here is a simple example that I tried to explain.

<div>
    <div *ngIf="product">     <!--If "product" exists-->
      <h2>Product Details</h2><hr>
      <h4>Name: {{ product.name }}</h4>
      <h5>Price: {{ product.price | currency }}</h5>
      <p> Description: {{ product.description }}</p>
    </div>

    <div *ngIf="!product">     <!--If "product" not exists-->
       *Product not found
    </div>
</div>

How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

For example,

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

World mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

how to count length of the JSON array element

Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

pip install returning invalid syntax

Try running cmd as administrator (in the menu that pops up after right-clicking) and/or entering "pip" alone and then

How to get cookie expiration date / creation date from javascript?

Yes, It is possible. I've separated the code in two files:

index.php

<?php

    $time = time()+(60*60*24*10);
    $timeMemo = (string)$time;
    setcookie("cookie", "" . $timeMemo . "", $time);

?>
<html>
    <head>
        <title>
            Get cookie expiration date from JS
        </title>
        <script type="text/javascript">

            function cookieExpirationDate(){

                var infodiv = document.getElementById("info");

                var xmlhttp;
                if (window.XMLHttpRequest){ 
                    xmlhttp = new XMLHttpRequest;
                }else{
                    xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
                }

                xmlhttp.onreadystatechange = function (){
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        infodiv.innerHTML = xmlhttp.responseText;
                    }
                }

                xmlhttp.open("GET", "cookie.php", true);
                xmlhttp.send();

            }

        </script>
    </head>
    <body>
        <input type="button" onclick="javascript:cookieExpirationDate();" value="Get Cookie expire date" />
        <hr />
        <div id="info">
        </div>
    </body>
</html>

cookie.php

<?php

    function secToDays($sec){
        return ($sec / 60 / 60 / 24);
    }

    if(isset($_COOKIE['cookie'])){

        if(round(secToDays((intval($_COOKIE['cookie']) - time())),1) < 1){
            echo "Cookie will expire today";
        }else{
            echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['cookie']) - time())),1) . " day(s)";
        }
    }else{
        echo "Cookie not set...";
    }

?>

Now, index.php must be loaded once. The button "Get Cookie expire date", thru an AJAX request, will always get you an updated "time left" for cookie expiration, in this case in days.

Procedure expects parameter which was not supplied

I came across this error today when null values were passed to my stored procedure's parameters. I was able easily fix by altering the stored procedure by adding default value = null.

Read/Write 'Extended' file properties (C#)

For those of not crazy about VB, here it is in c#:

Note, you have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

python: iterate a specific range in a list

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple. The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need.

Elements in a list are numerated from 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2.

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

How to symbolicate crash log Xcode?

Make sure that your Xcode application name doesn't contain any spaces. This was the reason it didn't work for me. So /Applications/Xcode.app works, while /Applications/Xcode 6.1.1.app doesn't work.

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Java : Convert formatted xml file to one line string

Run it through an XSLT identity transform with <xsl:output indent="no"> and <xsl:strip-space elements="*"/>

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" />
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

It will remove any of the non-significant whitespace and produce the expected output that you posted.

Sum values in foreach loop php

In your case IF you want to go with foreach loop than

$sum = 0;
foreach($group as $key => $value) {
   $sum += $value; 
}
echo $sum;

But if you want to go with direct sum of array than look on below for your solution :

$total = array_sum($group);

for only sum of array looping is time wasting.

http://php.net/manual/en/function.array-sum.php

array_sum — Calculate the sum of values in an array

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9

How can I sort generic list DESC and ASC?

without linq, use Sort() and then Reverse() it.

What and where are the stack and heap?

OK, simply and in short words, they mean ordered and not ordered...!

Stack: In stack items, things get on the top of each-other, means gonna be faster and more efficient to be processed!...

So there is always an index to point the specific item, also processing gonna be faster, there is relationship between the items as well!...

Heap: No order, processing gonna be slower and values are messed up together with no specific order or index... there are random and there is no relationship between them... so execution and usage time could be vary...

I also create the image below to show how they may look like:

enter image description here

How do I assert equality on two classes without an equals method?

Compare field-by-field:

assertNotNull("Object 1 is null", obj1);
assertNotNull("Object 2 is null", obj2);
assertEquals("Field A differs", obj1.getFieldA(), obj2.getFieldA());
assertEquals("Field B differs", obj1.getFieldB(), obj2.getFieldB());
...
assertEquals("Objects are not equal.", obj1, obj2);

Strip first and last character from C string

Another option, again assuming that "edit" means you want to modify in place:

void topntail(char *str) {
    size_t len = strlen(str);
    assert(len >= 2); // or whatever you want to do with short strings
    memmove(str, str+1, len-2);
    str[len-2] = 0;
}

This modifies the string in place, without generating a new address as pmg's solution does. Not that there's anything wrong with pmg's answer, but in some cases it's not what you want.

UTF-8 all the way through

if you want a mysql solution, I had similar issues with 2 of my projects, after a server migration. After searching and trying a lot of solutions i came across with this one /nothing before this one worked):

mysqli_set_charset($con,"utf8");

After adding this line to my config file everything works fine!

I found this solution https://www.w3schools.com/PHP/func_mysqli_set_charset.asp when i was looking to solve a insert from html query

good luck!

Getting first and last day of the current month

var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);

That should give you what you need.

Find out where MySQL is installed on Mac OS X

Or use good old "find". For example in order to look for old mysql v5.7:

cd /
find . type -d -name "[email protected]"

Running a command in a new Mac OS X Terminal window

I've been trying to do this for a while. Here is a script that changes to the same working directory, runs the command, and closes the terminal window.

#!/bin/sh 
osascript <<END 
tell application "Terminal"
    do script "cd \"`pwd`\";$1;exit"
end tell
END

How to set menu to Toolbar in Android

private Toolbar toolbar;

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

    toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    *// here is where you set it to show on the toolbar*
    setSupportActionBar(toolbar);
}

Well, you need to set support action bar setSupportActionBar(); and pass your variable, like so: setSupportActionBar(toolbar);

pandas read_csv and filter columns with usecols

import csv first and use csv.DictReader its easy to process...

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

demo - http://jsfiddle.net/victor_007/ywevz8ra/

added border for better view (testing)

more info about white-space

table{
    width:100%;
}
table td{
    white-space: nowrap;  /** added **/
}
table td:last-child{
    width:100%;
}

_x000D_
_x000D_
    table {_x000D_
      width: 100%;_x000D_
    }_x000D_
    table td {_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    table td:last-child {_x000D_
      width: 100%;_x000D_
    }
_x000D_
<table border="1">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Is there a way to word-wrap long words in a div?

Reading the original comment, rutherford is looking for a cross-browser way to wrap unbroken text (inferred by his use of word-wrap for IE, designed to break unbroken strings).

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */
.wordwrap { 
   white-space: pre-wrap;      /* CSS3 */   
   white-space: -moz-pre-wrap; /* Firefox */    
   white-space: -pre-wrap;     /* Opera <7 */   
   white-space: -o-pre-wrap;   /* Opera 7 */    
   word-wrap: break-word;      /* IE */
}

I've used this class for a bit now, and works like a charm. (note: I've only tested in FireFox and IE)

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

If notepad is already started, you should write:

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

//...

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

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

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

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

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

remove space between paragraph and unordered list

This simple way worked fine for me:

<ul style="margin-top:-30px;">

What is PostgreSQL equivalent of SYSDATE from Oracle?

You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW() and CURRENT_TIMESTAMP give the timestamp when the transaction started.

More details in the manual

How can I list ALL grants a user received?

select distinct 'GRANT '||privilege||' ON '||OWNER||'.'||TABLE_NAME||' TO '||RP.GRANTEE
from DBA_ROLE_PRIVS RP join ROLE_TAB_PRIVS RTP 
on (RP.GRANTED_ROLE = RTP.role)  
where (OWNER in ('YOUR USER') --Change User Name
   OR RP.GRANTEE in ('YOUR USER')) --Change User Name
and RP.GRANTEE not in ('SYS', 'SYSTEM')
;

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

An alternative to adding LINQ would be to use this code instead:

List<Pax_Detail> paxList = new List<Pax_Detail>(pax);

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

How to remove numbers from a string?

You can use .match && join() methods. .match() returns an array and .join() makes a string

function digitsBeGone(str){
  return str.match(/\D/g).join('')
}

startsWith() and endsWith() functions in PHP

function startsWith($haystack, $needle, $case = true) {
    if ($case) {
        return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
    }
    return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}

function endsWith($haystack, $needle, $case = true) {
    if ($case) {
        return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
    }
    return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}

Credit To:

Check if a string ends with another string

Check if a string begins with another string

"/usr/bin/ld: cannot find -lz"

Another possible cause: You've passed --static to the linker, but you only have a dynamic version of libz (libz.so), but not a version that can be statically linked (libz.a).

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

Get a file name from a path

For long time I was looking for a function able to properly decompose file path. For me this code is working perfectly for both Linux and Windows.

void decomposePath(const char *filePath, char *fileDir, char *fileName, char *fileExt)
{
    #if defined _WIN32
        const char *lastSeparator = strrchr(filePath, '\\');
    #else
        const char *lastSeparator = strrchr(filePath, '/');
    #endif

    const char *lastDot = strrchr(filePath, '.');
    const char *endOfPath = filePath + strlen(filePath);
    const char *startOfName = lastSeparator ? lastSeparator + 1 : filePath;
    const char *startOfExt = lastDot > startOfName ? lastDot : endOfPath;

    if(fileDir)
        _snprintf(fileDir, MAX_PATH, "%.*s", startOfName - filePath, filePath);

    if(fileName)
        _snprintf(fileName, MAX_PATH, "%.*s", startOfExt - startOfName, startOfName);

    if(fileExt)
        _snprintf(fileExt, MAX_PATH, "%s", startOfExt);
}

Example results are:

[]
  fileDir:  ''
  fileName: ''
  fileExt:  ''

[.htaccess]
  fileDir:  ''
  fileName: '.htaccess'
  fileExt:  ''

[a.exe]
  fileDir:  ''
  fileName: 'a'
  fileExt:  '.exe'

[a\b.c]
  fileDir:  'a\'
  fileName: 'b'
  fileExt:  '.c'

[git-archive]
  fileDir:  ''
  fileName: 'git-archive'
  fileExt:  ''

[git-archive.exe]
  fileDir:  ''
  fileName: 'git-archive'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git-core\.htaccess]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: '.htaccess'
  fileExt:  ''

[D:\Git\mingw64\libexec\git-core\a.exe]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: 'a'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git-core\git-archive.exe]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: 'git-archive'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git.core\git-archive.exe]
  fileDir:  'D:\Git\mingw64\libexec\git.core\'
  fileName: 'git-archive'
  fileExt:  '.exe'

[D:\Git\mingw64\libexec\git-core\git-archiveexe]
  fileDir:  'D:\Git\mingw64\libexec\git-core\'
  fileName: 'git-archiveexe'
  fileExt:  ''

[D:\Git\mingw64\libexec\git.core\git-archiveexe]
  fileDir:  'D:\Git\mingw64\libexec\git.core\'
  fileName: 'git-archiveexe'
  fileExt:  ''

I hope this helps you also :)

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

What is the use of hashCode in Java?

hashCode

Whenever you override equals(), you are also expected to override hashCode(). The hash code is used when storing the object as a key in a map.

A hash code is a number that puts instances of a class into a finite number of categories. Imagine that I gave you a deck of cards, and I told you that I was going to ask you for specific cards and I want to get the right card back quickly. You have as long as you want to prepare, but I’m in a big hurry when I start asking for cards. You might make 13 piles of cards: All of the aces in one pile, all the twos in another pile, and so forth. That way, when I ask for the five of hearts, you can just pull the right card out of the four cards in the pile with fives. It is certainly faster than going through the whole deck of 52 cards! You could even make 52 piles if you had enough space on the table.

reference : OCP Oracle Certified Professional Java SE 8 Programmer II

What does the servlet <load-on-startup> value signify

Servlet Life Cycle

The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container:

    a. Loads the servlet class

    b. Creates an instance of the servlet class

    c. Initializes the servlet instance by calling the init method (initialization is covered in Creating and Initializing a Servlet)

  2. The container invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

A 0 value on load-on-startup means that point 1 is executed when a request comes to that servlet. Other values means that point 1 is executed at container startup.

How to resolve "local edit, incoming delete upon update" message

You can force to revert your local directory to svn.

 svn revert -R your_local_path

Copy table to a different database on a different SQL Server

Microsoft SQL Server Database Publishing Wizard will generate all the necessary insert statements, and optionally schema information as well if you need that:

http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A

How to set a JavaScript breakpoint from code in Chrome?

debugger is a reserved keyword by EcmaScript and given optional semantics since ES5

As a result, it can be used not only in Chrome, but also Firefox and Node.js via node debug myscript.js.

The standard says:

Syntax

DebuggerStatement :
    debugger ;

Semantics

Evaluating the DebuggerStatement production may allow an implementation to cause a breakpoint when run under a debugger. If a debugger is not present or active this statement has no observable effect.

The production DebuggerStatement : debugger ; is evaluated as follows:

  1. If an implementation defined debugging facility is available and enabled, then
    1. Perform an implementation defined debugging action.
    2. Let result be an implementation defined Completion value.
  2. Else
    1. Let result be (normal, empty, empty).
  3. Return result.

No changes in ES6.

Find the PID of a process that uses a port on Windows

Command:

netstat -aon | findstr 4723

Output:

TCP    0.0.0.0:4723           0.0.0.0:0                LISTENING       10396

Now cut the process ID, "10396", using the for command in Windows.

Command:

for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

10396

If you want to cut the 4th number of the value means "LISTENING" then command in Windows.

Command:

for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

LISTENING

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

adb shell su works but adb root does not

In some developer-friendly ROMs you could just enable Root Access in Settings > Developer option > Root access. After that adb root becomes available. Unfortunately it does not work for most stock ROMs on the market.

Trying to merge 2 dataframes but get ValueError

It happens when common column in both table are of different data type.

Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.

key_load_public: invalid format

It seems that ssh cannot read your public key. But that doesn't matter.

You upload your public key to github, but you authenticate using your private key. See e.g. the FILES section in ssh(1).

How to convert list of key-value tuples into dictionary?

Another way using dictionary comprehensions,

>>> t = [('A', 1), ('B', 2), ('C', 3)]
>>> d = { i:j for i,j in t }
>>> d
{'A': 1, 'B': 2, 'C': 3}

R Markdown - changing font size and font type in html output

I think fontsize: command in YAML only works for LaTeX / pdf. Apart, in standard latex classes (article, book, and report) only three font sizes are accepted (10pt, 11pt, and 12pt).

Regarding appearance (different font types and colors), you can specify a theme:. See Appearance and Style.

I guess, what you are looking for is your own css. Make a file called style.css, save it in the same folder as your .Rmd and include it in the YAML header:

---
output:
  html_document:
    css: style.css
---

In the css-file you define your font-type and size:

/* Whole document: */
body{
  font-family: Helvetica;
  font-size: 16pt;
}
/* Headers */
h1,h2,h3,h4,h5,h6{
  font-size: 24pt;
}

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How can I remove a key from a Python dictionary?

Using the "del" keyword:

del dict[key]

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

How do I get the current mouse screen coordinates in WPF?

If you're looking for a 1 liner, this does well.

new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)

The + mWindow.Left and + mWindow.Top makes sure the position is in the right place even when the user drags the window around.

change Oracle user account status from EXPIRE(GRACE) to OPEN

set long 9999999
set lin 400
select DBMS_METADATA.GET_DDL('USER','YOUR_USER_NAME') from dual;

This will output something like this:

SQL> select DBMS_METADATA.GET_DDL('USER','WILIAM') from dual;

DBMS_METADATA.GET_DDL('USER','WILIAM')
--------------------------------------------------------------------------------

   CREATE USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F'
      DEFAULT TABLESPACE "USER"
      TEMPORARY TABLESPACE "TEMP"
      PASSWORD EXPIRE

Just use the first piece of that with alter user instead:

ALTER USER "WILIAM" IDENTIFIED BY VALUES 'S:6680C1468F5F3B36B726CE7620F
FD9657F0E0E49AE56AAACE847BA368CEB;120F24A4C2554B4F';

This will put the account back in to OPEN status without changing the password (as long as you cut and paste correctly the hash value from the output of DBMS_METADATA.GET_DDL) and you don't even need to know what the password is.

What is a loop invariant?

Invariant in this case means a condition that must be true at a certain point in every loop iteration.

In contract programming, an invariant is a condition that must be true (by contract) before and after any public method is called.

Copy a file in a sane, safe and efficient way

Qt has a method for copying files:

#include <QFile>
QFile::copy("originalFile.example","copiedFile.example");

Note that to use this you have to install Qt (instructions here) and include it in your project (if you're using Windows and you're not an administrator, you can download Qt here instead). Also see this answer.

fatal: early EOF fatal: index-pack failed

In my case, I simply upgraded my version of OpenSSL. The older versions of OpenSSL have vulnerabilities and also do not have the latest algorithms which may be needed. As of today, the command openssl version shows OpenSSL 1.1.1f 31 Mar 2020.

Error in strings.xml file in Android

The best answer of simply escaping the ' with \' works but I do not like the solution because when using replace all with ' to \', it only works once. The second time you'll be left with \\'.

Therefore, use: \u0027.

How do I bind to list of checkbox values with AngularJS?

If you have multiple checkboxes on the same form

The controller code

vm.doYouHaveCheckBox = ['aaa', 'ccc', 'bbb'];
vm.desiredRoutesCheckBox = ['ddd', 'ccc', 'Default'];
vm.doYouHaveCBSelection = [];
vm.desiredRoutesCBSelection = [];

View code

<div ng-repeat="doYouHaveOption in vm.doYouHaveCheckBox">
    <div class="action-checkbox">
        <input id="{{doYouHaveOption}}" type="checkbox" value="{{doYouHaveOption}}" ng-checked="vm.doYouHaveCBSelection.indexOf(doYouHaveOption) > -1" ng-click="vm.toggleSelection(doYouHaveOption,vm.doYouHaveCBSelection)" />
        <label for="{{doYouHaveOption}}"></label>
        {{doYouHaveOption}}
    </div>
</div>

<div ng-repeat="desiredRoutesOption in vm.desiredRoutesCheckBox">
     <div class="action-checkbox">
          <input id="{{desiredRoutesOption}}" type="checkbox" value="{{desiredRoutesOption}}" ng-checked="vm.desiredRoutesCBSelection.indexOf(desiredRoutesOption) > -1" ng-click="vm.toggleSelection(desiredRoutesOption,vm.desiredRoutesCBSelection)" />
          <label for="{{desiredRoutesOption}}"></label>
          {{desiredRoutesOption}}
     </div>
</div>        

Haversine Formula in Python (Bearing and Distance between two GPS points)

Here's a numpy vectorized implementation of the Haversine Formula given by @Michael Dunn, gives a 10-50 times improvement over large vectors.

from numpy import radians, cos, sin, arcsin, sqrt

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """

    #Convert decimal degrees to Radians:
    lon1 = np.radians(lon1.values)
    lat1 = np.radians(lat1.values)
    lon2 = np.radians(lon2.values)
    lat2 = np.radians(lat2.values)

    #Implementing Haversine Formula: 
    dlon = np.subtract(lon2, lon1)
    dlat = np.subtract(lat2, lat1)

    a = np.add(np.power(np.sin(np.divide(dlat, 2)), 2),  
                          np.multiply(np.cos(lat1), 
                                      np.multiply(np.cos(lat2), 
                                                  np.power(np.sin(np.divide(dlon, 2)), 2))))
    c = np.multiply(2, np.arcsin(np.sqrt(a)))
    r = 6371

    return c*r

How to include external Python code to use in other files?

If you use:

import Math

then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.

If you want to import a module's functions without having to prefix them, you must explicitly name them, like:

from Math import Calculate, Add, Subtract

Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

from Math import *

However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

Git command to display HEAD commit id?

You can use

git log -g branchname

to see git reflog information formatted like the git log output

Send private messages to friends

You cannot. Facebook API has read_mailbox but no write_mailbox extended permission. I'm guessing this is done to prevent spammy apps from flooding friend's inboxes.

Check if EditText is empty.

Try this out with using If ELSE If conditions. You can validate your editText fields easily.

 if(TextUtils.isEmpty(username)) {
                userNameView.setError("User Name Is Essential");
                return;
         } else  if(TextUtils.isEmpty(phone)) {
                phoneView.setError("Please Enter Your Phone Number");
                return;
            }

How to Lock the data in a cell in excel using vba

You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

Convert DataTable to List<T>

you can convert your datatable to list. check the following link

https://stackoverflow.com/a/35171050/1805776

public static class Helper
{
    public static List<T> DataTableToList<T>(this DataTable dataTable) where T : new()
    {
        var dataList = new List<T>();

        //Define what attributes to be read from the class
        const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;

        //Read Attribute Names and Types
        var objFieldNames = typeof(T).GetProperties(flags).Cast<System.Reflection.PropertyInfo>().
            Select(item => new
            {
                Name = item.Name,
                Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
            }).ToList();

        //Read Datatable column names and types
        var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
            Select(item => new
            {
                Name = item.ColumnName,
                Type = item.DataType
            }).ToList();

        foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
        {
            var classObj = new T();

            foreach (var dtField in dtlFieldNames)
            {
                System.Reflection.PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);

                var field = objFieldNames.Find(x => x.Name == dtField.Name);

                if (field != null)
                {

                    if (propertyInfos.PropertyType == typeof(DateTime))
                    {
                        propertyInfos.SetValue
                        (classObj, convertToDateTime(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(Nullable<DateTime>))
                    {
                        propertyInfos.SetValue
                        (classObj, convertToDateTime(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(int))
                    {
                        propertyInfos.SetValue
                        (classObj, ConvertToInt(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(long))
                    {
                        propertyInfos.SetValue
                        (classObj, ConvertToLong(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(decimal))
                    {
                        propertyInfos.SetValue
                        (classObj, ConvertToDecimal(dataRow[dtField.Name]), null);
                    }
                    else if (propertyInfos.PropertyType == typeof(String))
                    {
                        if (dataRow[dtField.Name].GetType() == typeof(DateTime))
                        {
                            propertyInfos.SetValue
                            (classObj, ConvertToDateString(dataRow[dtField.Name]), null);
                        }
                        else
                        {
                            propertyInfos.SetValue
                            (classObj, ConvertToString(dataRow[dtField.Name]), null);
                        }
                    }
                    else
                    {

                        propertyInfos.SetValue
                            (classObj, Convert.ChangeType(dataRow[dtField.Name], propertyInfos.PropertyType), null);

                    }
                }
            }
            dataList.Add(classObj);
        }
        return dataList;
    }

    private static string ConvertToDateString(object date)
    {
        if (date == null)
            return string.Empty;

        return date == null ? string.Empty : Convert.ToDateTime(date).ConvertDate();
    }

    private static string ConvertToString(object value)
    {
        return Convert.ToString(ReturnEmptyIfNull(value));
    }

    private static int ConvertToInt(object value)
    {
        return Convert.ToInt32(ReturnZeroIfNull(value));
    }

    private static long ConvertToLong(object value)
    {
        return Convert.ToInt64(ReturnZeroIfNull(value));
    }

    private static decimal ConvertToDecimal(object value)
    {
        return Convert.ToDecimal(ReturnZeroIfNull(value));
    }

    private static DateTime convertToDateTime(object date)
    {
        return Convert.ToDateTime(ReturnDateTimeMinIfNull(date));
    }

    public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
    {
        if (datetTime != DateTime.MinValue)
        {
            if (excludeHoursAndMinutes)
                return datetTime.ToString("yyyy-MM-dd");
            return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
        }
        return null;
    }
    public static object ReturnEmptyIfNull(this object value)
    {
        if (value == DBNull.Value)
            return string.Empty;
        if (value == null)
            return string.Empty;
        return value;
    }
    public static object ReturnZeroIfNull(this object value)
    {
        if (value == DBNull.Value)
            return 0;
        if (value == null)
            return 0;
        return value;
    }
    public static object ReturnDateTimeMinIfNull(this object value)
    {
        if (value == DBNull.Value)
            return DateTime.MinValue;
        if (value == null)
            return DateTime.MinValue;
        return value;
    }
}

Angular 2 Date Input not binding to date value

As per HTML5, you can use input type="datetime-local" instead of input type="date".

It will allow the [(ngModel)] directive to read and write value from input control.

Note: If the date string contains 'Z' then to implement above solution, you need to trim the 'Z' character from date.

For more details, please go through this link on mozilla docs.