Programs & Examples On #Jai

The Java Advanced Imaging provides powerful collection of methods for image processing and image analysis for Java.

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

Bootstrap 4: Multilevel Dropdown Inside Navigation

I found this multidrop-down menu which work great in all device.

Also, have hover style

It supports multi-level submenus with bootstrap 4.

_x000D_
_x000D_
$( document ).ready( function () {_x000D_
    $( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
        var $el = $( this );_x000D_
        var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
        $( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
        if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
            $el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
        }_x000D_
        $( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
        return false;_x000D_
    } );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
    color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
    padding: 10px 15px;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
    background: transparent;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
    transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
    </button>_x000D_
    <a class="navbar-brand" href="#">Navbar</a>_x000D_
    <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
        <ul class="navbar-nav">_x000D_
            <li class="nav-item active">_x000D_
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Features</a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Pricing</a>_x000D_
            </li>_x000D_
            <li class="nav-item dropdown">_x000D_
                <a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
                    <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
                    <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
                    <li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
                        <ul class="dropdown-menu">_x000D_
                            <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
                            <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                        </ul>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </li>_x000D_
        </ul>_x000D_
    </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to overcome the CORS issue in ReactJS

Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.

A simpler way is to use express-http-proxy

  1. run npm run build to create the bundle.

    var proxy = require('express-http-proxy');
    
    var app = require('express')();
    
    //define the path of build
    
    var staticFilesPath = path.resolve(__dirname, '..', 'build');
    
    app.use(express.static(staticFilesPath));
    
    app.use('/api/api-server', proxy('www.api-server.com'));
    

Use "/api/api-server" from react code to call the API.

So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

`col-xs-*` not working in Bootstrap 4

In Bootstrap 4.3, col-xs-{value} is replaced by col-{value}

There is no change in sm, md, lg, xl remains the same.

.col-{value}
.col-sm-{value}
.col-md-{value}
.col-lg-{value}
.col-xl-{value}

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

PHP fwrite new line

fwrite($handle, "<br>"."\r\n");

Add this under

$password = $_POST['password'].PHP_EOL;

this. .

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

How do I get a background location update every n minutes in my iOS application?

Unfortunately, all of your assumptions seem correct, and I don't think there's a way to do this. In order to save battery life, the iPhone's location services are based on movement. If the phone sits in one spot, it's invisible to location services.

The CLLocationManager will only call locationManager:didUpdateToLocation:fromLocation: when the phone receives a location update, which only happens if one of the three location services (cell tower, gps, wifi) perceives a change.

A few other things that might help inform further solutions:

  • Starting & Stopping the services causes the didUpdateToLocation delegate method to be called, but the newLocation might have an old timestamp.

  • Region Monitoring might help

  • When running in the background, be aware that it may be difficult to get "full" LocationServices support approved by Apple. From what I've seen, they've specifically designed startMonitoringSignificantLocationChanges as a low power alternative for apps that need background location support, and strongly encourage developers to use this unless the app absolutely needs it.

Good Luck!

UPDATE: These thoughts may be out of date by now. Looks as though people are having success with @wjans answer, above.

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                 {
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]
                 };

Could not load NIB in bundle

Had this same issue nothing worked, so I figured something weird with derived data.

In xcode 6.3.2 I had to:

In XCode Menu --> Preferences --> Locations Tab --> In Locations Change Derived Data to Relative and then toggle back to Default

Then the nib loaded fine.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

These steps solved my problem:

  1. Go into organizer
  2. Devices
  3. select your device
  4. Delete the particular profile.
  5. Run again

Tada...

Test iOS app on device without apple developer program or jailbreak

It's worth the buck to apply for the Apple developer program. You will be able to use ad-hoc provisioning to distribute your app to testers and test devices. You're allowed to add 100 ad-hoc provisioning devices to your developer program.

Can I edit an iPad's host file?

Best Answer: Simply add http or https in your browser, the IP address, colon and port number. Example: https://123.23.145.67:80

How to export non-exportable private key from store

i wanted to mention Jailbreak specifically (GitHub):

Jailbreak

Jailbreak is a tool for exporting certificates marked as non-exportable from the Windows certificate store. This can help when you need to extract certificates for backup or testing. You must have full access to the private key on the filesystem in order for jailbreak to work.

Prerequisites: Win32

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

You'll need to post your statement for more clarification. But...

That error means that the table you are inserting data into has a foreign key relationship with another table. Before data can be inserted, the value in the foreign key field must exist in the other table first.

TSQL Pivot without aggregate function

yes, but why !!??

   Select CustomerID,
     Min(Case DBColumnName When 'FirstName' Then Data End) FirstName,
     Min(Case DBColumnName When 'MiddleName' Then Data End) MiddleName,
     Min(Case DBColumnName When 'LastName' Then Data End) LastName,
     Min(Case DBColumnName When 'Date' Then Data End) Date
   From table
   Group By CustomerId

What's the best way to select the minimum value from several columns?

You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.

Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
From   YourTable T
       Inner Join (
         Select A.Id, Min(A.Col1) As TheMin
         From   (
                Select Id, Col1
                From   YourTable

                Union All

                Select Id, Col2
                From   YourTable

                Union All

                Select Id, Col3
                From   YourTable
                ) As A
         Group By A.Id
       ) As A
       On T.Id = A.Id

Is there a way I can capture my iPhone screen as a video?

You can use Lookback. It records your screen, face, voice and all gestures, and uploads them to your account on the web.

Here's a demo: https://lookback.io/watch/JK354d5jcEpA7CNkE

iPhone App Minus App Store?

With the upcoming Xcode 7 it's now possible to install apps on your devices without an apple developer license, so now it is possible to skip the app store and you don't have to jailbreak your device.

Now everyone can get their app on their Apple device.

Xcode 7 and Swift now make it easier for everyone to build apps and run them directly on their Apple devices. Simply sign in with your Apple ID, and turn your idea into an app that you can touch on your iPad, iPhone, or Apple Watch. Download Xcode 7 beta and try it yourself today. Program membership is not required.

Quoted from: https://developer.apple.com/xcode/

Update:

XCode 7 is now released:

Free On-Device Development Now everyone can run and test their own app on a device—for free. You can run and debug your own creations on a Mac, iPhone, iPad, iPod touch, or Apple Watch without any fees, and no programs to join. All you need to do is enter your free Apple ID into Xcode. You can even use the same Apple ID you already use for the App Store or iTunes. Once you’ve perfected your app the Apple Developer Program can help you get it on the App Store.

See Launching Your App on Devices for detailed information about installing and running on devices.

What's the main difference between int.Parse() and Convert.ToInt32

  • If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().

  • If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.

  • Convert.ToInt32() takes an object as its argument. (See Chris S's answer for how it works)

    Convert.ToInt32() also does not throw ArgumentNullException when its argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

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

An alternative to Trikaldarshi's one line solution. (It avoids having to construct FileInfo objects)

long sizeInBytes = Directory.EnumerateFiles("{path}","*", SearchOption.AllDirectories).Sum(fileInfo => new FileInfo(fileInfo).Length);

Android appcompat v7:23

Ran into a similar issue using React Native

> Could not find com.android.support:appcompat-v7:23.0.1.

the Support Libraries are Local Maven repository for Support Libraries

enter image description here

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

Resolve issue Immediate, It's related to internal security

We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.

As investigate in server log found

[error] (13)Permission denied: proxy: AJP: attempt to connect to
   10.x.x.x:8069 (virtualhost.virtualdomain.com) failed

Audit log found similar port issue

type=AVC msg=audit(1265039669.305:14): avc:  denied  { name_connect } for  pid=4343 comm="httpd" dest=8069 
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket

Due to internal default security of linux, this cause, now to fix (temporary)

 /usr/sbin/setsebool httpd_can_network_connect 1

Resolve Permanent Issue

/usr/sbin/setsebool -P httpd_can_network_connect 1

How to detect if numpy is installed

In the numpy README.txt file, it says

After installation, tests can be run with:

python -c 'import numpy; numpy.test()'

This should be a sufficient test for proper installation.

ReportViewer Client Print Control "Unable to load client print control"?

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

Equivalent of String.format in jQuery

Way past the late season but I've just been looking at the answers given and have my tuppence worth:

Usage:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

Method:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

Result:

"aalert" is not defined
3.14 3.14 a{2}bc foo

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use &check; for ✓ and &cross; for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.

As mentioned in the comments, &check; and &cross; are not supported in HTML4, so you may be better off using the more cryptic &#x2713; and &#x2717; if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.

How can I get the current date and time in UTC or GMT in Java?

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied

Wrong!

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()

and

Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));aNotGMTCalendar.getTime();

will return the same time. Idem for

new Date(); //it's not GMT.

How to click a browser button with JavaScript automatically?

This will give you some control over the clicking, and looks tidy

<script>
var timeOut = 0;
function onClick(but)
{
    //code
    clearTimeout(timeOut);
    timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>

Carriage return in C?

From 5.2.2/2 (character display semantics) :

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n (new line) Moves the active position to the initial position of the next line.

\r (carriage return) Moves the active position to the initial position of the current line.

Here, your code produces :

  • <new_line>ab
  • \b : back one character
  • write si : overrides the b with s (producing asi on the second line)
  • \r : back at the beginning of the current line
  • write ha : overrides the first two characters (producing hai on the second line)

In the end, the output is :

\nhai

Getting "cannot find Symbol" in Java project in Intellij

I know this thread is old but, another solution was to run

$ mvn clean install -Dmaven.test.skip=true

And on IntelliJ do CMD + Shift + A (mac os) -> type "Reimport all Maven projects".

If that doesn't work, try forcing maven dependencies to be re-downloaded

$ mvn clean -U install -Dmaven.test.skip=true

Push items into mongo array via mongoose

The $push operator appends a specified value to an array.

{ $push: { <field1>: <value1>, ... } }

$push adds the array field with the value as its element.

Above answer fulfils all the requirements, but I got it working by doing the following

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

JavaScript: How to pass object by value?

If you are using lodash or npm, use lodash's merge function to deep copy all of the object's properties to a new empty object like so:

var objectCopy = lodash.merge({}, originalObject);

https://lodash.com/docs#merge

https://www.npmjs.com/package/lodash.merge

How to parse a CSV in a Bash script?

In a CSV file, each field is separated by a comma. The problem is, a field itself might have an embedded comma:

Name,Phone
"Woo, John",425-555-1212

You really need a library package that offer robust CSV support instead of relying on using comma as a field separator. I know that scripting languages such as Python has such support. However, I am comfortable with the Tcl scripting language so that is what I use. Here is a simple Tcl script which does what you are asking for:

#!/usr/bin/env tclsh

package require csv 
package require Tclx

# Parse the command line parameters
lassign $argv fileName columnNumber expectedValue

# Subtract 1 from columnNumber because Tcl's list index starts with a
# zero instead of a one
incr columnNumber -1

for_file line $fileName {
    set columns [csv::split $line]
    set columnValue [lindex $columns $columnNumber]
    if {$columnValue == $expectedValue} {
        puts $line
    }   
}

Save this script to a file called csv.tcl and invoke it as:

$ tclsh csv.tcl filename indexNumber expectedValue

Explanation

The script reads the CSV file line by line and store the line in the variable $line, then it split each line into a list of columns (variable $columns). Next, it picks out the specified column and assigned it to the $columnValue variable. If there is a match, print out the original line.

PHP - Indirect modification of overloaded property

All you need to do is add "&" in front of your __get function to pass it as reference:

public function &__get ( $index )

Struggled with this one for a while.

How can I insert binary file data into a binary SQL field using a simple insert statement?

If you mean using a literal, you simply have to create a binary string:

insert into Files (FileId, FileData) values (1, 0x010203040506)

And you will have a record with a six byte value for the FileData field.


You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).

You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).


In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.

How to unzip a file in Powershell?

In PowerShell v5.1 this is slightly different compared to v5. According to MS documentation, it has to have a -Path parameter to specify the archive file path.

Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference

Or else, this can be an actual path:

Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference

Expand-Archive Doc

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

sys.stdout.buffer.write(some_bytes_object)

This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

Correct way to write loops for promise.

If you really want a general promiseWhen() function for this and other purposes, then by all means do so, using Bergi's simplifications. However, because of the way promises work, passing callbacks in this way is generally unnecessary and forces you to jump through complex little hoops.

As far as I can tell you're trying :

  • to asynchronously fetch a series of user details for a collection of email addresses (at least, that's the only scenario that makes sense).
  • to do so by building a .then() chain via recursion.
  • to maintain the original order when handling the returned results.

Defined thus, the problem is actually the one discussed under "The Collection Kerfuffle" in Promise Anti-patterns, which offers two simple solutions :

  • parallel asynchronous calls using Array.prototype.map()
  • serial asynchronous calls using Array.prototype.reduce().

The parallel approach will (straightforwardly) give the issue that you are trying to avoid - that the order of the responses is uncertain. The serial approach will build the required .then() chain - flat - no recursion.

function fetchUserDetails(arr) {
    return arr.reduce(function(promise, email) {
        return promise.then(function() {
            return db.getUser(email).done(function(res) {
                logger.log(res);
            });
        });
    }, Promise.resolve());
}

Call as follows :

//Compose here, by whatever means, an array of email addresses.
var arrayOfEmailAddys = [...];

fetchUserDetails(arrayOfEmailAddys).then(function() {
    console.log('all done');
});

As you can see, there's no need for the ugly outer var count or it's associated condition function. The limit (of 10 in the question) is determined entirely by the length of the array arrayOfEmailAddys.

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

How do I access (read, write) Google Sheets spreadsheets with Python?

(Jun-Dec 2016) Most answers here are now out-of-date as: 1) GData APIs are the previous generation of Google APIs, and that's why it was hard for @Josh Brown to find that old GData Docs API documentation. While not all GData APIs have been deprecated, all newer Google APIs do not use the Google Data protocol; and 2) Google released a new Google Sheets API (not GData). In order to use the new API, you need to get the Google APIs Client Library for Python (it's as easy as pip install -U google-api-python-client [or pip3 for Python 3]) and use the latest Sheets API v4+, which is much more powerful & flexible than older API releases.

Here's one code sample from the official docs to help get you kickstarted. However, here are slightly longer, more "real-world" examples of using the API you can learn from (videos plus blog posts):

The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.), but NOT as if it was some database that you could perform searches on and get selected rows from. You'd basically have to build a querying layer on top of the API that does this. One alternative is to use the Google Charts Visualization API query language, which does support SQL-like querying. You can also query from within the Sheet itself. Be aware that this functionality existed before the v4 API, and that the security model was updated in Aug 2016. To learn more, check my G+ reshare to a full write-up from a Google Developer Expert.

Also note that the Sheets API is primarily for programmatically accessing spreadsheet operations & functionality as described above, but to perform file-level access such as imports/exports, copy, move, rename, etc., use the Google Drive API instead. Examples of using the Drive API:

(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a developer video combining both "poor man's converter" posts.

To learn more about how to use Google APIs with Python in general, check out my blog as well as a variety of Google developer videos (series 1 and series 2) I'm producing.

ps. As far as Google Docs goes, there isn't a REST API available at this time, so the only way to programmatically access a Doc is by using Google Apps Script (which like Node.js is JavaScript outside of the browser, but instead of running on a Node server, these apps run in Google's cloud; also check out my intro video.) With Apps Script, you can build a Docs app or an add-on for Docs (and other things like Sheets & Forms).

UPDATE Jul 2018: The above "ps." is no longer true. The G Suite developer team pre-announced a new Google Docs REST API at Google Cloud NEXT '18. Developers interested in getting into the early access program for the new API should register at https://developers.google.com/docs.

UPDATE Feb 2019: The Docs API launched to preview last July is now available generally to all... read the launch post for more details.

UPDATE Nov 2019: In an effort to bring G Suite and GCP APIs more inline with each other, earlier this year, all G Suite code samples were partially integrated with GCP's newer (lower-level not product) Python client libraries. The way auth is done is similar but (currently) requires a tiny bit more code to manage token storage, meaning rather than our libraries manage storage.json, you'll store them using pickle (token.pickle or whatever name you prefer) instead, or choose your own form of persistent storage. For you readers here, take a look at the updated Python quickstart example.

PHP How to find the time elapsed since a date time?

Improvisation to the function "humanTiming" by arnorhs. It would calculate a "fully stretched" translation of time string to human readable text version. For example to say it like "1 week 2 days 1 hour 28 minutes 14 seconds"

function humantime ($oldtime, $newtime = null, $returnarray = false)    {
    if(!$newtime) $newtime = time();
    $time = $newtime - $oldtime; // to get the time since that moment
    $tokens = array (
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
    );
    $htarray = array();
    foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
            $numberOfUnits = floor($time / $unit);
            $htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
            $time = $time - ( $unit * $numberOfUnits );
    }
    if($returnarray) return $htarray;
    return implode(' ', $htarray);
}

Getting pids from ps -ef |grep keyword

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).

alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"

Download pdf file using jquery ajax

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

Given that, you have one of two solutions:

First solution, abandon JQuery and use XMLHTTPRequest

Go with the native HTMLHTTPRequest, here is the code to do what you need

  var req = new XMLHttpRequest();
  req.open("GET", "/file.pdf", true);
  req.responseType = "blob";

  req.onload = function (event) {
    var blob = req.response;
    console.log(blob.size);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="Dossier_" + new Date() + ".pdf";
    link.click();
  };

  req.send();

Second solution, use the jquery-ajax-native plugin

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

$.ajax({
  dataType: 'native',
  url: "/file.pdf",
  xhrFields: {
    responseType: 'blob'
  },
  success: function(blob){
    console.log(blob.size);
      var link=document.createElement('a');
      link.href=window.URL.createObjectURL(blob);
      link.download="Dossier_" + new Date() + ".pdf";
      link.click();
  }
});

How to change UINavigationBar background color from the AppDelegate

You can use [[UINavigationBar appearance] setTintColor:myColor];

Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor]; and also [[UINavigationBar appearance] setTranslucent:NO].

[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];

Filter output in logcat by tagname

Another option is setting the log levels for specific tags:

adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E

If you just want to set the log levels for some tags you can do it on a tag by tag basis.

Check if a String contains a special character

Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean b = m.find();

if (b)
   System.out.println("There is a special character in my string");

Linq style "For Each"

The official MS line is "because it's not a functional operation" (ie it's a stateful operation).

Couldn't you do something like:

list.Select( x => x+1 )

or if you really need it in a List:

var someValues = new List<int>( list.Select( x => x+1 ) );

Send string to stdin

You can also use read like this

echo "enter your name"
read name
echo $name

fast way to copy formatting in excel

You could have simply used Range("x1").value(11) something like below:

Sheets("Output").Range("$A$1:$A$500").value(11) =  Sheets(sheet_).Range("$A$1:$A$500").value(11)

range has default property "Value" plus value can have 3 optional orguments 10,11,12. 11 is what you need to tansfer both value and formats. It doesn't use clipboard so it is faster.- Durgesh

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

How to set a cookie for another domain

In this link, we will find the solution Link.

setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "b.com", 1);

How to check internet access on Android? InetAddress never times out

public class Network {

Context context;

public Network(Context context){
    this.context = context;
}

public boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
                          activeNetwork.isConnectedOrConnecting();
}

}

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

Find the below code in xampp/phpmyadmin/config.inc.php

$cfg['Servers'][$i]['controluser']  = 'user_name/root';   
$cfg['Servers'][$i]['controlpass']  = 'passwaord';
$cfg['Servers'][$i]['auth_type']    = 'config';
$cfg['Servers'][$i]['user']         = 'user_name/root';
$cfg['Servers'][$i]['password']     = 'password';

Replace each statement above with the corresponding entry below:

$cfg['Servers'][$i]['controluser']  = 'root';   
$cfg['Servers'][$i]['controlpass']  = 'xxxx';
$cfg['Servers'][$i]['auth_type']    = 'config';
$cfg['Servers'][$i]['user']         = 'root';
$cfg['Servers'][$i]['password']     = 'xxxx';

Doing this caused localhost/phpmyadmin in the browser and the MySQL command prompt to work properly.

What are CN, OU, DC in an LDAP search?

  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component

These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.

You can also read up on LDAP data Interchange Format (LDIF), which is an alternate format.

You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.

Each = pair is a search criteria.

With your example query

("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");

In effect the query is:

From the com Domain Component, find the google Domain Component, and then inside it the gl Domain Component and then inside it the gp Domain Component.

In the gp Domain Component, find the Organizational Unit called Distribution Groups and then find the the object that has a common name of Dev-India.

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Only to supplement. If you need to pass a variable and iterate it, you can do just like so:

function start(counter){
  if(counter < 10){
    setTimeout(function(){
      counter++;
      console.log(counter);
      start(counter);
    }, 1000);
  }
}
start(0);

Output:

1
2
3
...
9
10

One line per second.

showDialog deprecated. What's the alternative?

This code worked for me. Easy fix but probably not a preferred way.

public void onClick (View v) {
    createdDialog(0).show(); // Instead of showDialog(0);
}

protected Dialog createdDialog(int id) {
    // Your code
}

Python class inherits object

The syntax of the class creation statement:

class <ClassName>(superclass):
    #code follows

In the absence of any other superclasses that you specifically want to inherit from, the superclass should always be object, which is the root of all classes in Python.

object is technically the root of "new-style" classes in Python. But the new-style classes today are as good as being the only style of classes.

But, if you don't explicitly use the word object when creating classes, then as others mentioned, Python 3.x implicitly inherits from the object superclass. But I guess explicit is always better than implicit (hell)

Reference

Why does pycharm propose to change method to static

Since you didn't refer to self in the bar method body, PyCharm is asking if you might have wanted to make bar static. In other programming languages, like Java, there are obvious reasons for declaring a static method. In Python, the only real benefit to a static method (AFIK) is being able to call it without an instance of the class. However, if that's your only reason, you're probably better off going with a top-level function - as note here.

In short, I'm not one hundred percent sure why it's there. I'm guessing they'll probably remove it in an upcoming release.

Quantile-Quantile Plot using SciPy

import numpy as np 
import pylab 
import scipy.stats as stats
measurements = np.random.normal(loc = 20, scale = 5, size=100)   
stats.probplot(measurements, dist="norm", plot=pylab)
pylab.show()

Here probplot draw the graph measurements vs normal distribution which speofied in dist="norm"

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

How can I read an input string of unknown length?

Enter while securing an area dynamically

E.G.

#include <stdio.h>
#include <stdlib.h>

char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(*str)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(*str)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(*str)*len);
}

int main(void){
    char *m;

    printf("input string : ");
    m = inputString(stdin, 10);
    printf("%s\n", m);

    free(m);
    return 0;
}

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Importing files from different folder

In case anyone still looking for a solution. This worked for me.

Python adds the folder containing the script you launch to the PYTHONPATH, so if you run

python application/app2/some_folder/some_file.py

Only the folder application/app2/some_folder is added to the path (not the base dir that you're executing the command in). Instead, run your file as a module and add a __init__.py in your some_folder directory.

python -m application.app2.some_folder.some_file

This will add the base dir to the python path, and then classes will be accessible via a non-relative import.

What is the difference between require and require-dev sections in composer.json?

  1. According to composer's manual:

    require-dev (root-only)

    Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

    So running composer install will also download the development dependencies.

  2. The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.

How to get selected value from Dropdown list in JavaScript

Hope it's working for you

 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text 
 }

Root element is missing

Make sure you XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<rootElement>
...
</rootElement>

Also, a blank XML file will return the same Root elements is missing exception. Each XML file must have a root element / node which encloses all the other elements.

SQL Server 2008: How to query all databases sizes?

with Total Database size ordered Desc

SELECT     
DB_NAME(db.database_id) DatabaseName,     
(CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,     
(CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB, 
(CAST(mfrows.RowSize AS FLOAT)*8)/1024/1024+(CAST(mflog.LogSize AS FLOAT)*8)/1024/1024 DBSizeG,
(CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB,     
(CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB 
FROM sys.databases db     
LEFT JOIN (SELECT database_id, 
                  SUM(size) RowSize 
            FROM sys.master_files 
            WHERE type = 0 
            GROUP BY database_id, type) mfrows 
    ON mfrows.database_id = db.database_id     
LEFT JOIN (SELECT database_id, 
                  SUM(size) LogSize 
            FROM sys.master_files 
            WHERE type = 1 
            GROUP BY database_id, type) mflog 
    ON mflog.database_id = db.database_id     
LEFT JOIN (SELECT database_id, 
                  SUM(size) StreamSize 
                  FROM sys.master_files 
                  WHERE type = 2 
                  GROUP BY database_id, type) mfstream 
    ON mfstream.database_id = db.database_id     
LEFT JOIN (SELECT database_id, 
                  SUM(size) TextIndexSize 
                  FROM sys.master_files 
                  WHERE type = 4 
                  GROUP BY database_id, type) mftext 
    ON mftext.database_id = db.database_id 
       ORDER BY 4 DESC

Get characters after last / in url

$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);

SOAP or REST for Web Services?

SOAP is useful from a tooling perspective because the WSDL is so easily consumed by tools. So, you can get Web Service clients generated for you in your favorite language.

REST plays well with AJAX'y web pages. If you keep your requests simple, you can make service calls directly from your JavaScript, and that comes in very handy. Try to stay away from having any namespaces in your response XML, I've seen browsers choke on those. So, xsi:type is probably not going to work for you, no overly complex XML Schemas.

REST tends to have better performance as well. CPU requirements of the code generating REST responses tend to be lower than what SOAP frameworks exhibit. And, if you have your XML generation ducks lined up on the server side, you can effectively stream XML out to the client. So, imagine you're reading rows of database cursor. As you read a row, you format it as an XML element, and you write that directly out to the service consumer. This way, you don't have to collect all of the database rows in memory before starting to write your XML output - you read and write at the same time. Look into novel templating engines or XSLT to get the streaming to work for REST.

SOAP on the other hand tends to get generated by tool-generated services as a big blob and only then written. This is not an absolute truth, mind you, there are ways to get streaming characteristics out of SOAP, like by using attachments.

My decision making process is as follows: if I want my service to be easily tooled by consumers, and the messages I write will be medium-to-small-ish (10MB or less), and I don't mind burning some extra CPU cycles on the server, I go with SOAP. If I need to serve to AJAX on web browsers, or I need the thing to stream, or my responses are gigantic, I go REST.

Finally, there are lots of great standards built up around SOAP, like WS-Security and getting stateful Web Services, that you can plug in to if you're using the right tools. That kind of stuff really makes a difference, and can help you satisfy some hairy requirements.

Simple check for SELECT query empty result

SELECT * FROM service s WHERE s.service_id = ?;
BEGIN
   print 'no data'
END

CSS Inset Borders

I would recomnend using box-sizing.

*{
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
  -ms-box-sizing:border-box;
  box-sizing:border-box;
}

#bar{
  border: 10px solid green;
  }

How to query nested objects?

db.messages.find( { headers : { From: "[email protected]" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "[email protected]" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs

Java equivalent to #region in C#

Contrary to what most are posting, this is NOT an IDE thing. It is a language thing. The #region is a C# statement.

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

Can I use break to exit multiple nested 'for' loops?

I'm not sure if it's worth it, but you can emulate Java's named loops with a few simple macros:

#define LOOP_NAME(name) \
    if ([[maybe_unused]] constexpr bool _namedloop_InvalidBreakOrContinue = false) \
    { \
        [[maybe_unused]] CAT(_namedloop_break_,name): break; \
        [[maybe_unused]] CAT(_namedloop_continue_,name): continue; \
    } \
    else

#define BREAK(name) goto CAT(_namedloop_break_,name)
#define CONTINUE(name) goto CAT(_namedloop_continue_,name)

#define CAT(x,y) CAT_(x,y)
#define CAT_(x,y) x##y

Example usage:

#include <iostream>

int main()
{
    // Prints:
    // 0 0
    // 0 1
    // 0 2
    // 1 0
    // 1 1

    for (int i = 0; i < 3; i++) LOOP_NAME(foo)
    {
        for (int j = 0; j < 3; j++)
        {
            std::cout << i << ' ' << j << '\n';
            if (i == 1 && j == 1)
                BREAK(foo);
        }
    }
}

Another example:

#include <iostream>

int main()
{
    // Prints: 
    // 0
    // 1
    // 0
    // 1
    // 0
    // 1

    int count = 3;
    do LOOP_NAME(foo)
    {
        for (int j = 0; j < 3; j++)
        {
            std::cout << ' ' << j << '\n';
            if (j == 1)
                CONTINUE(foo);
        }
    }
    while(count-- > 1);
}

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

Java foreach loop: for (Integer i : list) { ... }

The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:

  if(x.isEmpty()) return;
  int last = x.size() - 1;
  for(Integer i : x.subList(0, last)) out.println(i);
  out.println("last " + x.get(last));

This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).

How to use activity indicator view on iPhone?

The documentation on this is pretty clear. It's a UIView subclass so you use it like any other view. To start/stop the animation you use

[activityIndicator startAnimating];
[activityIndicator stopAnimating];

How can I hide a TD tag using inline JavaScript or CSS?

We can hide the content inside a by using the following inline css:

<div style="visibility:hidden"></div>

for example:

<td><div style="visibility:hidden">Your Content Goes Here:</div></td>

What does %5B and %5D in POST requests stand for?

They represent [ and ]. The encoding is called "URL encoding".

How to count the number of occurrences of an element in a List

I wonder, why you can't use that Google's Collection API with JDK 1.6. Does it say so? I think you can, there should not be any compatibility issues, as it is built for a lower version. The case would have been different if that were built for 1.6 and you are running 1.5.

Am I wrong somewhere?

Prevent screen rotation on Android

Add

android:screenOrientation="portrait" 

or

 android:screenOrientation="landscape" 

to the <activity> element/s in the manifest and you're done.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

The startup project that references the project where Entity Framework is being used needs the following two assemblies in it's bin folder:

  • EntityFramework.dll
  • EntityFramework.SqlServer.dll

Adding a <section> to the <configSections> of the .config file on the startup project makes the first assembly available in that bin directory. You can copy this from the .config file of your Entity Framework project:

<configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>

To make the second .dll available in the bin folder, although not practical, a manual copy from the bin folder of the Entity Framework project can be made. A better alternative is to add to the Post-Build Events of the Entity Framework project the following lines, which will automate the process:

cd $(ProjectDir)
xcopy /y bin\Debug\EntityFramework.SqlServer.dll ..\{PATH_TO_THE_PROJECT_THAT_NEEDS_THE_DLL}\bin\Debug\

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

Cookies vs. sessions

TL;DR

Criteria / factors Sessions Cookies
Epoch (start of existence) Created BEFORE an HTTP response Created AFTER an HTTP response
Availability during the first HTTP request YES NO
Availability during the succeeding HTTP requests YES YES
Ultimate control for the data and expiration Server administrator End-user
Default expiration Expires earlier than cookies Lasts longer than sessions
Server costs Memory Memory
Network costs None Unnecessary extra bytes
Browser costs None Memory
Security Difficult to hijack Easy to hijack
Deprecation None Now discouraged in favor of the JavaScript "Web Storage"

Details

Advantages and disadvantages are subjective. They can result in a dichotomy (an advantage for some, but considered disadvantage for others). Instead, I laid out above the factors that can help you decide which one to pick.

Existence during the first HTTP request-and-response

Let's just say you are a server-side person who wants to process both the session and cookie. The first HTTP handshake will go like so:

  1. Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: not available
  2. Browser sends the HTTP request
  3. Server receives the HTTP request
  4. Server processes the HTTP request -- SESSIONS: existed; COOKIES: cast
  5. Server sends the HTTP response
  6. Browser receives the HTTP response
  7. Browser processes the HTTP response -- SESSIONS: not available; COOKIES: existed

In step 1, the browser have no idea of the contents of both sessions and cookies. In step 4, the server can have the opportunity to set the values of the session and cookies.

Availability during the succeeding HTTP requests-and-responses

  1. Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: available
  2. Browser sends the HTTP request
  3. Server receives the HTTP request
  4. Server processes the HTTP request -- SESSIONS: available; COOKIES: available
  5. Server sends the HTTP response
  6. Browser receives the HTTP response
  7. Browser processes the HTTP response -- SESSIONS: not available; COOKIES: available

Payload

Let's say in a single web page you are loading 20 resources hosted by example.com, those 20 resources will carry extra bytes of information about the cookies. Even if it's just a resource request for CSS or a JPG image, it would still carry cookies in their headers on the way to the server. Should an HTTP request to a JPG resource carry a bunch of unnecessary cookies?

Deprecation

There is no replacement for sessions. For cookies, there are many other options in storing data in the browser rather than the old school cookies.

Storing of user data

Session is safer for storing user data because it can not be modified by the end-user and can only be set on the server-side. Cookies on the other hand can be hijacked because they are just stored on the browser.

What's the difference between IFrame and Frame?

iframes are used a lot to include complete pages. When those pages are hosted on another domain you get problems with cross side scripting and stuff. There are ways to fix this.

Frames were used to divide your page into multiple parts (for example, a navigation menu on the left). Using them is no longer recommended.

Fixed GridView Header with horizontal and vertical scrolling in asp.net

// create this Js and add reference

var GridViewScrollOptions = /** @class */ (function () {
    function GridViewScrollOptions() {
    }
    return GridViewScrollOptions;
}());

var GridViewScroll = /** @class */ (function ()
 {

    function GridViewScroll(options) {
        this._initialized = false;
        if (options.elementID == null)
            options.elementID = "";
        if (options.width == null)
            options.width = "700";
        if (options.height == null)
            options.height = "350";
        if (options.freezeColumnCssClass == null)
            options.freezeColumnCssClass = "";
        if (options.freezeFooterCssClass == null)
            options.freezeFooterCssClass = "";
        if (options.freezeHeaderRowCount == null)
            options.freezeHeaderRowCount = 1;
        if (options.freezeColumnCount == null)
            options.freezeColumnCount = 1;
        this.initializeOptions(options);
    }
    GridViewScroll.prototype.initializeOptions = function (options) {
        this.GridID = options.elementID;
        this.GridWidth = options.width;
        this.GridHeight = options.height;
        this.FreezeColumn = options.freezeColumn;
        this.FreezeFooter = options.freezeFooter;
        this.FreezeColumnCssClass = options.freezeColumnCssClass;
        this.FreezeFooterCssClass = options.freezeFooterCssClass;
        this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
        this.FreezeColumnCount = options.freezeColumnCount;
    };

    GridViewScroll.prototype.enhance = function () 
{

        this.FreezeCellWidths = [];
        this.IsVerticalScrollbarEnabled = false;
        this.IsHorizontalScrollbarEnabled = false;
        if (this.GridID == null || this.GridID == "")
 {

            return;
        }

        this.ContentGrid = document.getElementById(this.GridID);
        if (this.ContentGrid == null) {

            return;
        }
        if (this.ContentGrid.rows.length < 2) {


            return;
        }
        if (this._initialized) {

            this.undo();
        }

        this._initialized = true;
        this.Parent = this.ContentGrid.parentNode;
        this.ContentGrid.style.display = "none";
        if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
            var percentage = parseInt(this.GridWidth);
            this.Width = this.Parent.offsetWidth * percentage / 100;
        }
        else {

            this.Width = parseInt(this.GridWidth);
        }
        if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {


            var percentage = parseInt(this.GridHeight);
            this.Height = this.Parent.offsetHeight * percentage / 100;
        }
        else {

            this.Height = parseInt(this.GridHeight);
        }

        this.ContentGrid.style.display = "";
        this.ContentGridHeaderRows = this.getGridHeaderRows();
        this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
        var footerIndex = this.ContentGrid.rows.length - 1;
        this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
        this.Content = document.createElement('div');
        this.Content.id = this.GridID + "_Content";
        this.Content.style.position = "relative";
        this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
        this.ContentFixed = document.createElement('div');
        this.ContentFixed.id = this.GridID + "_Content_Fixed";
        this.ContentFixed.style.overflow = "auto";
        this.ContentFixed = this.Content.appendChild(this.ContentFixed);
        this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
        this.ContentFixed.style.width = String(this.Width) + "px";
        if (this.ContentGrid.offsetWidth > this.Width) {

            this.IsHorizontalScrollbarEnabled = true;
        }

        if (this.ContentGrid.offsetHeight > this.Height) {

            this.IsVerticalScrollbarEnabled = true;
        }

        this.Header = document.createElement('div');
        this.Header.id = this.GridID + "_Header";
        this.Header.style.backgroundColor = "#F0F0F0";
        this.Header.style.position = "relative";
        this.HeaderFixed = document.createElement('div');
        this.HeaderFixed.id = this.GridID + "_Header_Fixed";
        this.HeaderFixed.style.overflow = "hidden";
        this.Header = this.Parent.insertBefore(this.Header, this.Content);
        this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
        this.ScrollbarWidth = this.getScrollbarWidth();
        this.prepareHeader();
        this.calculateHeader();
        this.Header.style.width = String(this.Width) + "px";
        if (this.IsVerticalScrollbarEnabled) {

            this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
            if (this.IsHorizontalScrollbarEnabled) {

                this.ContentFixed.style.width = this.HeaderFixed.style.width;
                if (this.isRTL()) {

                    this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
                }

                else {

                    this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
                }

            }

            this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
        }

        else {

            this.HeaderFixed.style.width = this.Header.style.width;
            this.ContentFixed.style.width = this.Header.style.width;
        }

        if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {

            this.appendFreezeHeader();
            this.appendFreezeContent();
        }
        if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {

            this.appendFreezeFooter();
            if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {


                this.appendFreezeFooterColumn();
            }
        }
        var self = this;
        this.ContentFixed.onscroll = function (event) {

            self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
            if (self.ContentFreeze != null)
                self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
            if (self.FooterFreeze != null)
                self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
        };
    };
    GridViewScroll.prototype.getGridHeaderRows = function () {



        var gridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            gridHeaderRows.push(this.ContentGrid.rows.item(i));

        }
        return gridHeaderRows;
    };
    GridViewScroll.prototype.prepareHeader = function () {

        this.HeaderGrid = this.ContentGrid.cloneNode(false);
        this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
        this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
        this.prepareHeaderGridRows();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
            this.appendHelperElement(this.HeaderGridHeaderCells[i]);
        }
    };
    GridViewScroll.prototype.prepareHeaderGridRows = function () {

        this.HeaderGridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
            var gridHeaderRow = this.ContentGridHeaderRows[i];
            var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
            this.HeaderGridHeaderRows.push(headerGridHeaderRow);
            this.HeaderGrid.appendChild(headerGridHeaderRow);
        }

        this.prepareHeaderGridCells();
    };
    GridViewScroll.prototype.prepareHeaderGridCells = function () {

        this.HeaderGridHeaderCells = new Array();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            for (var rowIndex in this.HeaderGridHeaderRows) {


                var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
                var fixedCellIndex = 0;
                for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
                    var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
                    if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {

                        this.HeaderGridHeaderCells.push(cgridHeaderCell);
                    }
                    else {
                        fixedCellIndex += cgridHeaderCell.colSpan - 1;
                    }
                    fixedCellIndex++;
                }
            }
        }
    };
    GridViewScroll.prototype.calculateHeader = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            var helperWidth = parseInt(String(helperElement.offsetWidth));
            this.FreezeCellWidths.push(helperWidth);
            helperElement.style.width = helperWidth + "px";
            helperElement = this.HeaderGridHeaderCells[i].firstChild;
            helperElement.style.width = helperWidth + "px";
        }
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            this.ContentGridHeaderRows[i].style.display = "none";
        }
    };
    GridViewScroll.prototype.appendFreezeHeader = function () {

        this.HeaderFreeze = document.createElement('div');
        this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
        this.HeaderFreeze.style.position = "absolute";
        this.HeaderFreeze.style.overflow = "hidden";
        this.HeaderFreeze.style.top = "0px";
        this.HeaderFreeze.style.left = "0px";
        this.HeaderFreeze.style.width = "";
        this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
        this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
        this.HeaderFreezeGridHeaderRows = new Array();
        for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {

            var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
            this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
                headerFreezeGridHeaderRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
        }
        this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
    };
    GridViewScroll.prototype.appendFreezeContent = function () {

        this.ContentFreeze = document.createElement('div');
        this.ContentFreeze.id = this.GridID + "_Content_Freeze";
        this.ContentFreeze.style.position = "absolute";
        this.ContentFreeze.style.overflow = "hidden";
        this.ContentFreeze.style.top = "0px";
        this.ContentFreeze.style.left = "0px";
        this.ContentFreeze.style.width = "";
        this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
        this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
        var freezeCellHeights = [];
        var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
        var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var helperElement = void 0;
            if (gridItemCell.firstChild.className == "gridViewScrollHelper") {

                helperElement = gridItemCell.firstChild;
            }
            else {
                helperElement = this.appendHelperElement(gridItemCell);
            }
            var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
            freezeCellHeights.push(helperHeight);
            var cgridItemRow = gridItemRow.cloneNode(false);
            var cgridItemCell = gridItemCell.cloneNode(true);
            if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
                cgridItemRow.className = this.FreezeColumnCssClass;
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
                cgridItemRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.ContentFreezeGrid.appendChild(cgridItemRow);
        }
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
            var cgridItemCell = cgridItemRow.cells.item(0);
            var helperElement = gridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
            helperElement = cgridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
        }
        if (this.IsVerticalScrollbarEnabled) {
            this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
        }
        else {
            this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
        }
        this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
    };
    GridViewScroll.prototype.appendFreezeFooter = function () {

        this.FooterFreeze = document.createElement('div');
        this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
        this.FooterFreeze.style.position = "absolute";
        this.FooterFreeze.style.overflow = "hidden";
        this.FooterFreeze.style.left = "0px";
        this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
        this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
        this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
        this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
        if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
            this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
        for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {

            var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
            var helperElement = this.appendHelperElement(cgridHeaderCell);
            helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
        }
        this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
        this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
    };
    GridViewScroll.prototype.appendFreezeFooterColumn = function () {

        this.FooterFreezeColumn = document.createElement('div');
        this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
        this.FooterFreezeColumn.style.position = "absolute";
        this.FooterFreezeColumn.style.overflow = "hidden";
        this.FooterFreezeColumn.style.left = "0px";
        this.FooterFreezeColumn.style.width = "";
        this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
        this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
        if (this.FreezeFooterCssClass != null)
            this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
        var columnIndex = 0;
        var columnCount = 0;
        while (columnCount < this.FreezeColumnCount) {

            var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
            this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
            columnCount += freezeColumn.colSpan;
            columnIndex++;
        }
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
        this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
    };
    GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {

        var helperElement = document.createElement('div');
        helperElement.className = "gridViewScrollHelper";
        while (gridItemCell.hasChildNodes()) {

            helperElement.appendChild(gridItemCell.firstChild);
        }
        return gridItemCell.appendChild(helperElement);
    };
    GridViewScroll.prototype.getScrollbarWidth = function () {

        var innerElement = document.createElement('p');
        innerElement.style.width = "100%";
        innerElement.style.height = "200px";
        var outerElement = document.createElement('div');
        outerElement.style.position = "absolute";
        outerElement.style.top = "0px";
        outerElement.style.left = "0px";
        outerElement.style.visibility = "hidden";
        outerElement.style.width = "200px";
        outerElement.style.height = "150px";
        outerElement.style.overflow = "hidden";
        outerElement.appendChild(innerElement);
        document.body.appendChild(outerElement);
        var innerElementWidth = innerElement.offsetWidth;
        outerElement.style.overflow = 'scroll';
        var outerElementWidth = innerElement.offsetWidth;
        if (innerElementWidth === outerElementWidth)
            outerElementWidth = outerElement.clientWidth;
        document.body.removeChild(outerElement);
        return innerElementWidth - outerElementWidth;
    };
    GridViewScroll.prototype.isRTL = function () {

        var direction = "";
        if (window.getComputedStyle) {

            direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
        }
        else {
            direction = this.ContentGrid.currentStyle.direction;
        }
        return direction === "rtl";
    };
    GridViewScroll.prototype.getPaddingTop = function (element) {

        var value = "";
        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
        }
        else {

            value = element.currentStyle.paddingTop;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.getPaddingBottom = function (element) {
        var value = "";

        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
        }
        else {

            value = element.currentStyle.paddingBottom;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.undo = function () {

        this.undoHelperElement();
        for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
            var contentGridHeaderRow = _a[_i];
            contentGridHeaderRow.style.display = "";
        }
        this.Parent.insertBefore(this.ContentGrid, this.Header);
        this.Parent.removeChild(this.Header);
        this.Parent.removeChild(this.Content);
        this._initialized = false;
    };
    GridViewScroll.prototype.undoHelperElement = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            while (helperElement.hasChildNodes()) {

                gridItemCell.appendChild(helperElement.firstChild);
            }
            gridItemCell.removeChild(helperElement);
        }
        if (this.FreezeColumn) {

            for (var i = 2; i < this.ContentGrid.rows.length; i++) {

                var gridItemRow = this.ContentGrid.rows.item(i);
                var gridItemCell = gridItemRow.cells.item(0);
                var helperElement = gridItemCell.firstChild;
                while (helperElement.hasChildNodes()) {


                    gridItemCell.appendChild(helperElement.firstChild);
                }
                gridItemCell.removeChild(helperElement);
            }
        }
    };
    return GridViewScroll;
}());

//add On Head

<head runat="server">
    <title></title>

    <script src="client/js/jquery-3.1.1.min.js"></script>

    <script src="js/gridviewscroll.js"></script>

    <script type="text/javascript">
        window.onload = function () {

            var gridViewScroll = new GridViewScroll({
                elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
            });
            gridViewScroll.enhance();
        }
    </script>

</head>

//Add on Body

<body>
    <form id="form1" runat="server">

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">

       // <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

           <%-- <Columns>
                <asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
                    ReadOnly="True" SortExpression="SHIPMENT_ID" />
                <asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
                    SortExpression="TypeValue" />
                <asp:BoundField DataField="CHAId" HeaderText="CHAId"
                    SortExpression="CHAId" />
                <asp:BoundField DataField="Status" HeaderText="Status"
                    SortExpression="Status" />
            </Columns>--%>
        </asp:GridView>

SQL server stored procedure return a table

The Status Value being returned by a Stored Procedure can only be an INT datatype. You cannot return other datatypes in the RETURN statement.

From Lesson 2: Designing Stored Procedures:

Every stored procedure can return an integer value known as the execution status value or return code.

If you still want a table returned from the SP, you'll either have to work the record set returned from a SELECT within the SP or tie into an OUTPUT variable that passes an XML datatype.

HTH,

John

Matplotlib scatter plot with different text at each data point

As a one liner using list comprehension and numpy:

[ax.annotate(x[0], (x[1], x[2])) for x in np.array([n,z,y]).T]

setup is ditto to Rutger's answer.

How to define global variable in Google Apps Script

I'm using a workaround by returning a function with an object of my global variables:

function globalVariables(){
  var variables = {
    sheetName: 'Sheet1',
    variable1: 1,
    variable2: 2
  };
  return variables;
}

function functionThatUsesVariable (){
  var sheet =   SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}

How to include External CSS and JS file in Laravel 5

In laravel 5.1,

 <link rel="stylesheet" href="{{URL::asset('assets/css/bootstrap.min.css')}}">
 <script type="text/javascript" src="{{URL::asset('assets/js/jquery.min.js')}}"></script>

Where assets folder location is inside public folder

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

The profiler trace puts it into perspective.

  • Query A: 1.3 secs CPU, 1.4 secs duration
  • Query B: 2.3 secs CPU, 1.2 secs duration

Query B is using parallelism: CPU > duration eg the query uses 2 CPUs, average 1.15 secs each

Query A is probably not: CPU < duration

This explains cost relative to batch: 17% of the for the simpler, non-parallel query plan.

The optimiser works out that query B is more expensive and will benefit from parallelism, even though it takes extra effort to do so.

Remember though, that query B uses 100% of 2 CPUS (so 50% for 4 CPUs) for one second or so. Query A uses 100% of a single CPU for 1.5 seconds.

The peak for query A is lower, at the expense of increased duration. With one user, who cares? With 100, perhaps it makes a difference...

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

Session 'app' error while installing APK

Turning off the instant run(File >>Settings >>Build,Execution,Deployment >> Instant Run), solved my issue

Adding minutes to date time in PHP

$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);

result is

2011-11-17 05:21:00

Live demo is here

If you are no familiar with strtotime yet, you better head to php.net to discover it's great power :-)

Creating a JSON dynamically with each input value using jquery

Like this:

function createJSON() {
    jsonObj = [];
    $("input[class=email]").each(function() {

        var id = $(this).attr("title");
        var email = $(this).val();

        item = {}
        item ["title"] = id;
        item ["email"] = email;

        jsonObj.push(item);
    });

    console.log(jsonObj);
}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 

How to use SharedPreferences in Android to store, fetch and edit values

Best practice ever

Create Interface named with PreferenceManager:

// Interface to save values in shared preferences and also for retrieve values from shared preferences
public interface PreferenceManager {

    SharedPreferences getPreferences();
    Editor editPreferences();

    void setString(String key, String value);
    String getString(String key);

    void setBoolean(String key, boolean value);
    boolean getBoolean(String key);

    void setInteger(String key, int value);
    int getInteger(String key);

    void setFloat(String key, float value);
    float getFloat(String key);

}

How to use with Activity / Fragment:

public class HomeActivity extends AppCompatActivity implements PreferenceManager{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout_activity_home);
    }

    @Override
    public SharedPreferences getPreferences(){
        return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
    }

    @Override
    public SharedPreferences.Editor editPreferences(){
        return getPreferences().edit();
    }

    @Override
    public void setString(String key, String value) {
        editPreferences().putString(key, value).commit();
    }

    @Override
    public String getString(String key) {
        return getPreferences().getString(key, "");
    }

    @Override
    public void setBoolean(String key, boolean value) {
        editPreferences().putBoolean(key, value).commit();
    }

    @Override
    public boolean getBoolean(String key) {
        return  getPreferences().getBoolean(key, false);
    }

    @Override
    public void setInteger(String key, int value) {
        editPreferences().putInt(key, value).commit();
    }

    @Override
    public int getInteger(String key) {
        return getPreferences().getInt(key, 0);
    }

    @Override
    public void setFloat(String key, float value) {
        editPreferences().putFloat(key, value).commit();
    }

    @Override
    public float getFloat(String key) {
        return getPreferences().getFloat(key, 0);
    }
}

Note: Replace your key of SharedPreference with SP_TITLE.

Examples:

Store string in shareperence:

setString("my_key", "my_value");

Get string from shareperence:

String strValue = getString("my_key");

Hope this will help you.

Iterating through a variable length array

for(int i = 0; i < array.length; i++)
{
    System.out.println(array[i]);
}

or

for(String value : array)
{
    System.out.println(value);
}

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;

while(index < myArray.length)
{
  final String value;

  value = myArray[index];
  System.out.println(value);
  index++;
}

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

How to compare DateTime without time via LINQ?

Just use the Date property:

var today = DateTime.Today;

var q = db.Games.Where(t => t.StartDate.Date >= today)
                .OrderBy(t => t.StartDate);

Note that I've explicitly evaluated DateTime.Today once so that the query is consistent - otherwise each time the query is executed, and even within the execution, Today could change, so you'd get inconsistent results. For example, suppose you had data of:

Entry 1: March 8th, 8am
Entry 2: March 10th, 10pm
Entry 3: March 8th, 5am
Entry 4: March 9th, 8pm

Surely either both entries 1 and 3 should be in the results, or neither of them should... but if you evaluate DateTime.Today and it changes to March 9th after it's performed the first two checks, you could end up with entries 1, 2, 4.

Of course, using DateTime.Today assumes you're interested in the date in the local time zone. That may not be appropriate, and you should make absolutely sure you know what you mean. You may want to use DateTime.UtcNow.Date instead, for example. Unfortunately, DateTime is a slippery beast...

EDIT: You may also want to get rid of the calls to DateTime static properties altogether - they make the code hard to unit test. In Noda Time we have an interface specifically for this purpose (IClock) which we'd expect to be injected appropriately. There's a "system time" implementation for production and a "stub" implementation for testing, or you can implement it yourself.

You can use the same idea without using Noda Time, of course. To unit test this particular piece of code you may want to pass the date in, but you'll be getting it from somewhere - and injecting a clock means you can test all the code.

What is the difference between instanceof and Class.isAssignableFrom(...)?

instanceof cannot be used with primitive types or generic types either. As in the following code:

//Define Class< T > type ... 

Object e = new Object();

if(e instanceof T) {
  // Do something.
}

The error is: Cannot perform instanceof check against type parameter T. Use it's erasure Object instead since further generic type information will be erased at runtime.

Does not compile due to type erasure removing the runtime reference. However, the code below will compile:

if( type.isAssignableFrom(e.getClass())){
  // Do something.
}

Setting a windows batch file variable to the day of the week

Another spin on this topic. The below script displays a few days around the current, with day-of-week prefix.

At the core is the standalone :dpack routine that encodes the date into a value whose modulo 7 reveals the day-of-week per ISO 8601 standards (Mon == 0). Also provided is :dunpk which is the inverse function:

@echo off& setlocal enabledelayedexpansion
rem 10/23/2018 daydate.bat: Most recent version at paulhoule.com/daydate
rem Example of date manipulation within a .BAT file.
rem This is accomplished by first packing the date into a single number.
rem This demo .bat displays dates surrounding the current date, prefixed
rem with the day-of-week.

set days=0Mon1Tue2Wed3Thu4Fri5Sat6Sun
call :dgetl y m d
call :dpack p %y% %m% %d%
for /l %%o in (-3,1,3) do (
  set /a od=p+%%o
  call :dunpk y m d !od!
  set /a dow=od%%7
  for %%d in (!dow!) do set day=!days:*%%d=!& set day=!day:~,3!
  echo !day! !y! !m! !d!
)
exit /b


rem gets local date returning year month day as separate variables
rem in: %1 %2 %3=var names for returned year month day
:dgetl
setlocal& set "z="
for /f "skip=1" %%a in ('wmic os get localdatetime') do set z=!z!%%a
set /a y=%z:~0,4%, m=1%z:~4,2% %%100, d=1%z:~6,2% %%100
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b


rem packs date (y,m,d) into count of days since 1/1/1 (0..n)
rem in: %1=return var name, %2= y (1..n), %3=m (1..12), %4=d (1..31)
rem out: set %1= days since 1/1/1 (modulo 7 is weekday, Mon= 0)
:dpack
setlocal enabledelayedexpansion
set mtb=xxx  0 31 59 90120151181212243273304334& set /a r=%3*3
set /a t=%2-(12-%3)/10, r=365*(%2-1)+%4+!mtb:~%r%,3!+t/4-(t/100-t/400)-1
endlocal& set %1=%r%& exit /b


rem inverse of date packer
rem in: %1 %2 %3=var names for returned year month day
rem %4= packed date (large decimal number, eg 736989)
:dunpk
setlocal& set /a y=%4+366, y+=y/146097*3+(y%%146097-60)/36524
set /a y+=y/1461*3+(y%%1461-60)/365, d=y%%366+1, y/=366
set e=31 60 91 121 152 182 213 244 274 305 335
set m=1& for %%x in (%e%) do if %d% gtr %%x set /a m+=1, d=%d%-%%x
endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b

How can I import a large (14 GB) MySQL dump file into a new MySQL database?

I've searched around, and only this solution helped me:

mysql -u root -p

set global net_buffer_length=1000000; --Set network buffer length to a large byte number

set global max_allowed_packet=1000000000; --Set maximum allowed packet size to a large byte number

SET foreign_key_checks = 0; --Disable foreign key checking to avoid delays,errors and unwanted behaviour

source file.sql --Import your sql dump file

SET foreign_key_checks = 1; --Remember to enable foreign key checks when procedure is complete!

The answer is found here.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

How to initialize List<String> object in Java?

In most cases you want simple ArrayList - an implementation of List

Before JDK version 7

List<String> list = new ArrayList<String>();

JDK 7 and later you can use the diamond operator

List<String> list = new ArrayList<>();

Further informations are written here Oracle documentation - Collections

Linux/Unix command to determine if process is running?

The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :

isPidRunning() {
  cmd=`
    PATH=\`getconf PATH\` export PATH
    ps -e -o pid= -o comm= |
      awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
  `
  [ -n "$cmd" ] &&
    printf "%s is running\n%s\n\n" "$1" "$cmd" ||
    printf "%s is not running\n\n" $1
  [ -n "$cmd" ]
}

$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd

$ isPidRunning ksh
ksh is running
5230 ksh

$ isPidRunning bash
bash is not running

Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.

Note too that the most upvoted and accepted solution demands non portable ps options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash)

Simple dynamic breadcrumb

Here is a great simple dynamic breadcrumb (tweak as needed):

    <?php 
    $docroot = "/zen/index5.php";
    $path =($_SERVER['REQUEST_URI']);
    $names = explode("/", $path); 
    $trimnames = array_slice($names, 1, -1);
    $length = count($trimnames)-1;
    $fixme = array(".php","-","myname");
    $fixes = array(""," ","My<strong>Name</strong>");
    echo '<div id="breadwrap"><ol id="breadcrumb">';
    $url = "";
    for ($i = 0; $i <= $length;$i++){
    $url .= $trimnames[$i]."/";
        if($i>0 && $i!=$length){
            echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>';
    }
    elseif ($i == $length){
        echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>';       
    }
    else{
        echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>';
    }
}
echo '</ol>';
?>

How to convert a string to number in TypeScript?

if you are talking about just types, as other people said, parseInt() etc will return the correct type. Also, if for any reason the value could be both a number or a string and you don't want to call parseInt(), typeof expressions will also cast to the correct type:

function f(value:number|string){
  if(typeof value==='number'){
   // value : number
  }else {
   // value : string
  }
}

Call a function with argument list in python

You can use *args and **kwargs syntax for variable length arguments.

What do *args and **kwargs mean?

And from the official python tutorial

http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions

Is it possible to print a variable's type in standard C++?

Don't forget to include <typeinfo>

I believe what you are referring to is runtime type identification. You can achieve the above by doing .

#include <iostream>
#include <typeinfo>

using namespace std;

int main() {
  int i;
  cout << typeid(i).name();
  return 0;
}

CSS Change List Item Background Color with Class

This is an issue of selector specificity. (The selector .selected is less specific than ul.nav li.)

To fix, use as much specificity in the overriding rule as in the original:

ul.nav li {
 background-color:blue;
}
ul.nav li.selected {
 background-color:red;
}

You might also consider nixing the ul, unless there will be other .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

That's a bit cleaner, less typing, and fewer bits.

How to change text and background color?

`enter code here`#include <stdafx.h> // Used with MS Visual Studio Express. Delete line if using something different
#include <conio.h> // Just for WaitKey() routine
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // For use of SetConsoleTextAttribute()

void WaitKey();

int main()
{

    int len = 0,x, y=240; // 240 = white background, black foreground 

    string text = "Hello World. I feel pretty today!";
    len = text.length();
    cout << endl << endl << endl << "\t\t"; // start 3 down, 2 tabs, right
    for ( x=0;x<len;x++)
    {
        SetConsoleTextAttribute(console, y); // set color for the next print
        cout << text[x];
        y++; // add 1 to y, for a new color
        if ( y >254) // There are 255 colors. 255 being white on white. Nothing to see. Bypass it
            y=240; // if y > 254, start colors back at white background, black chars
        Sleep(250); // Pause between letters 
    }

    SetConsoleTextAttribute(console, 15); // set color to black background, white chars
    WaitKey(); // Program over, wait for a keypress to close program
}


void WaitKey()
{
    cout  << endl << endl << endl << "\t\t\tPress any key";
    while (_kbhit()) _getch(); // Empty the input buffer
    _getch(); // Wait for a key
    while (_kbhit()) _getch(); // Empty the input buffer (some keys sends two messages)
}

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

A project with an Output Type of Class Library cannot be started directly

The project you have downloaded compiles into a dll assembly and provide a set of classes with implemented functionality.

You should add to your solution a new project with Output Type of either Console Application or Windows Application (VS Add Project wizard will offer you different templates of Projects).

In the newly added project, you can implement logic to test your Class Library.

Output type of the project you can find and change by the following steps:

  1. Right click on project in Solution Explorer -> Properties.

  2. In opened tab with properties select Application and there will be ComboBox marked with Output Type label.

How to show loading spinner in jQuery?

You can always use Block UI jQuery plugin which does everything for you, and it even blocks the page of any input while the ajax is loading. In case that the plugin seems to not been working, you can read about the right way to use it in this answer. Check it out.

Node.js: How to read a stream into a buffer?

You can convert your readable stream to a buffer and integrate it in your code in an asynchronous way like this.

async streamToBuffer (stream) {
    return new Promise((resolve, reject) => {
      const data = [];

      stream.on('data', (chunk) => {
        data.push(chunk);
      });

      stream.on('end', () => {
        resolve(Buffer.concat(data))
      })

      stream.on('error', (err) => {
        reject(err)
      })
   
    })
  }

the usage would be as simple as:

 // usage
  const myStream // your stream
  const buffer = await streamToBuffer(myStream) // this is a buffer

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

Overloading and overriding

Simple definitions for overloading and overriding

Overloading (Compile Time Polymorphism):: Functions with same name and different parameters

public class A
{
    public void print(int x, int y)
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public void print(float x, float y)
    {
        Console.WriteLine("Overload child method");
    }
}

Overriding (Run Time Polymorphism):: Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.

public class A
{
    public virtual void print()
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public override void print()
    {
        Console.WriteLine("Overriding child method");
    }
}

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

What is your most productive shortcut with Vim?

I recently discovered q:. It opens the "command window" and shows your most recent ex-mode (command-mode) commands. You can move as usual within the window, and pressing <CR> executes the command. You can edit, etc. too. Priceless when you're messing around with some complex command or regex and you don't want to retype the whole thing, or if the complex thing you want to do was 3 commands back. It's almost like bash's set -o vi, but for vim itself (heh!).

See :help q: for more interesting bits for going back and forth.

Inserting code in this LaTeX document with indentation

A very simple way if your code is in Python, where I didn't have to install a Python package, is the following:

\documentclass[11pt]{article}  
\usepackage{pythonhighlight}

\begin{document}

The following is some Python code

\begin{python}
# A comment
x = [5, 7, 10]
y = 0

for num in x:
    y += num
    
print(y)
\end{python}

\end{document}

which looks like: enter image description here

Unfortunately, this only works for Python.

How to clear jQuery validation error messages?

I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate.

Here is what I came up with:

  • Clear errors by indicating validation success
  • Call handler for error display
  • Clear all storage of success or errors
  • Reset entire form validation

    Here is what it looks like in code:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
     $('[name]',formElement).each(function(){
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     });
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    }
    //used
    var myForm = document.getElementById("myFormId");
    clearValidation(myForm);
    

    minified as a jQuery extension:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
    //used:
    $("#formId").clearValidation();
    
  • What do Push and Pop mean for Stacks?

    after all these good examples adam shankman still can't make sense of it. I think you should open up some code and try it. The second you try a myStack.Push(1) and myStack.Pop(1) you really should get the picture. But by the looks of it, even that will be a challenge for you!

    Apache shutdown unexpectedly

    You can disable port 80 and 443 as alternative incoming connections in Skype settings - Advanced settings - Connection.

    disable alternative incoming connections
    (source: ctrlv.in)

    Best way to change font colour halfway through paragraph?

    wrap a <span> around those words and style with the appropriate color

    now is the time for <span style='color:orange'>all good men</span> to come to the
    

    Get the latest date from grouped MySQL data

    Subquery giving dates. We are not linking with the model. So below query solves the problem.

    If there are duplicate dates/model can be avoided by the following query.

    select t.model, t.date
    from doc t
    inner join (select model, max(date) as MaxDate from doc  group by model)
    tm on t.model = tm.model and t.date = tm.MaxDate
    

    How to use Angular2 templates with *ngFor to create a table out of nested arrays?

       <tbody  *ngFor="let defect of items">            
              <tr>
                <td>{{defect.param1}}</td>
                <td>{{defect.param2}}</td>
                <td>{{defect.param3}}</td>                
                <td>{{defect.param4}}</td>
                <td>{{defect.param5}} </td>
                <td>{{defect.param6}}</td>
                <td>{{defect.param7}}</td>           
              </tr>
              <tr>
                <td> <strong> Notes:</strong></td>
                <td colspan="6"> {{defect.param8}}
                </td>`enter code here`
              </tr>          
            </tbody>
    

    Javascript can't find element by id?

    The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

    window.onload = function () {
        var e = document.getElementById("db_info");
        e.innerHTML='Found you';
    };
    

    Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

    Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

    Override browser form-filling and input highlighting with HTML/CSS

    You can disable auto-completion as of HTML5 (via autocomplete="off"), but you CAN'T override the browser's highlighting. You could try messing with ::selection in CSS (most browsers require a vendor prefix for that to work), but that probably won't help you either.

    Unless the browser vendor specifically implemented a vendor-specific way of overriding it, you can't do anything about such styles that are already intended to override the site's stylesheet for the user. These are usually applied after your stylesheets are applied and ignore ! important overrides, too.

    How to elegantly check if a number is within a range?

    Using an && expression to join two comparisons is simply the most elegant way to do this. If you try using fancy extension methods and such, you run into the question of whether to include the upper bound, the lower bound, or both. Once you start adding additional variables or changing the extension names to indicate what is included, your code becomes longer and harder to read (for the vast majority of programmers). Furthermore, tools like Resharper will warn you if your comparison doesn't make sense (number > 100 && number < 1), which they won't do if you use a method ('i.IsBetween(100, 1)').

    The only other comment I'd make is that if you're checking inputs with the intention to throw an exception, you should consider using code contracts:

    Contract.Requires(number > 1 && number < 100)
    

    This is more elegant than if(...) throw new Exception(...), and you could even get compile-time warnings if someone tries to call your method without ensuring that the number is in bounds first.

    Rails DB Migration - How To Drop a Table?

    I wasn't able to make it work with migration script so I went ahead with this solution. Enter rails console using the terminal:

    rails c
    

    Type

    ActiveRecord::Migration.drop_table(:tablename)
    

    It works well for me. This will remove the previous table. Don't forget to run

    rails db:migrate
    

    Python 3 Building an array of bytes

    Use a bytearray:

    >>> frame = bytearray()
    >>> frame.append(0xA2)
    >>> frame.append(0x01)
    >>> frame.append(0x02)
    >>> frame.append(0x03)
    >>> frame.append(0x04)
    >>> frame
    bytearray(b'\xa2\x01\x02\x03\x04')
    

    or, using your code but fixing the errors:

    frame = b""
    frame += b'\xA2' 
    frame += b'\x01' 
    frame += b'\x02' 
    frame += b'\x03'
    frame += b'\x04'
    

    What is the difference between Linear search and Binary search?

    A linear search starts at the beginning of a list of values, and checks 1 by 1 in order for the result you are looking for.

    A binary search starts in the middle of a sorted array, and determines which side (if any) the value you are looking for is on. That "half" of the array is then searched again in the same fashion, dividing the results in half by two each time.

    xlrd.biffh.XLRDError: Excel xlsx file; not supported

    The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

    pip install xlrd==1.2.0
    

    How should I copy Strings in Java?

    Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.

    How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

    Dictionary<int,string> comboSource = new Dictionary<int,string>();
    comboSource.Add(1, "Sunday");
    comboSource.Add(2, "Monday");
    

    Aftr adding values to Dictionary, use this as combobox datasource:

    comboBox1.DataSource = new BindingSource(comboSource, null);
    comboBox1.DisplayMember = "Value";
    comboBox1.ValueMember = "Key";
    

    javascript, for loop defines a dynamic variable name

    I think you could do it by creating parameters in an object maybe?

    var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

    If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

    Text Progress Bar in the Console

    I recommend using tqdm - https://pypi.python.org/pypi/tqdm - which makes it simple to turn any iterable or process into a progress bar, and handles all messing about with terminals needed.

    From the documentation: "tqdm can easily support callbacks/hooks and manual updates. Here’s an example with urllib"

    import urllib
    from tqdm import tqdm
    
    def my_hook(t):
      """
      Wraps tqdm instance. Don't forget to close() or __exit__()
      the tqdm instance once you're done with it (easiest using `with` syntax).
    
      Example
      -------
    
      >>> with tqdm(...) as t:
      ...     reporthook = my_hook(t)
      ...     urllib.urlretrieve(..., reporthook=reporthook)
    
      """
      last_b = [0]
    
      def inner(b=1, bsize=1, tsize=None):
        """
        b  : int, optional
            Number of blocks just transferred [default: 1].
        bsize  : int, optional
            Size of each block (in tqdm units) [default: 1].
        tsize  : int, optional
            Total size (in tqdm units). If [default: None] remains unchanged.
        """
        if tsize is not None:
            t.total = tsize
        t.update((b - last_b[0]) * bsize)
        last_b[0] = b
      return inner
    
    eg_link = 'http://www.doc.ic.ac.uk/~cod11/matryoshka.zip'
    with tqdm(unit='B', unit_scale=True, miniters=1,
              desc=eg_link.split('/')[-1]) as t:  # all optional kwargs
        urllib.urlretrieve(eg_link, filename='/dev/null',
                           reporthook=my_hook(t), data=None)
    

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

    You have two ways of ignoring files:

    • .gitignore in any folder will ignore the files as specified in the file for that folder. Using wildcards is possible.
    • .git/info/exclude holds the global ignore pattern, similar to the global-ignores in subversions configuration file.

    How to implement zoom effect for image view in android?

    Lazy man can use this lib, Just import inside your project and

    ImageView mImageView;
    PhotoViewAttacher mAttacher;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // Any implementation of ImageView can be used!
        mImageView = (ImageView) findViewById(R.id.iv_photo);
    
        // Set the Drawable displayed
        Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
        mImageView.setImageDrawable(bitmap);
    
        // Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
        mAttacher = new PhotoViewAttacher(mImageView);
    }
    
    
    // If you later call mImageView.setImageDrawable/setImageBitmap/setImageResource/etc then you just need to call
    mAttacher.update();
    

    Which selector do I need to select an option by its text?

    This works for me:

    var result = $('#SubjectID option')
                .filter(function () 
                 { return $(this).html() == "English"; }).val();
    

    The result variable will return the index of the matched text value. Now I will just set it using it's index:

    $('#SubjectID').val(result);
    

    Remove and Replace Printed items

    Just use CR to go to beginning of the line.

    import time
    for x in range (0,5):  
        b = "Loading" + "." * x
        print (b, end="\r")
        time.sleep(1)
    

    Rename multiple files based on pattern in Unix

    My version of renaming mass files:

    for i in *; do
        echo "mv $i $i"
    done |
    sed -e "s#from_pattern#to_pattern#g” > result1.sh
    sh result1.sh
    

    SSL InsecurePlatform error when using Requests package

    Use the somewhat hidden security feature:

    pip install requests[security] or pip install pyOpenSSL ndg-httpsclient pyasn1

    Both commands install following extra packages:

    • pyOpenSSL
    • cryptography
    • idna

    Please note that this is not required for python-2.7.9+.

    If pip install fails with errors, check whether you have required development packages for libffi, libssl and python installed in your system using distribution's package manager:

    • Debian/Ubuntu - python-dev libffi-dev libssl-dev packages.

    • Fedora - openssl-devel python-devel libffi-devel packages.

    Distro list above is incomplete.

    Workaround (see the original answer by @TomDotTom):

    In case you cannot install some of the required development packages, there's also an option to disable that warning:

    import requests.packages.urllib3
    requests.packages.urllib3.disable_warnings()
    

    If your pip itself is affected by InsecurePlatformWarning and cannot install anything from PyPI, it can be fixed with this step-by-step guide to deploy extra python packages manually.

    Move the mouse pointer to a specific position?

    So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.

    Here's the release documentation:
    FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
    Chrome: http://www.chromium.org/developers/design-documents/mouse-lock

    And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/

    How can I apply styles to multiple classes at once?

    just seperate the class name with a comma.

    .a,.b{
    your styles
    }
    

    Apply CSS rules if browser is IE

    A good way to avoid loading multiple CSS files or to have inline CSS is to hand a class to the body tag depending on the version of Internet Explorer. If you only need general IE hacks, you can do something like this, but it can be extended to be version specific:

    <!--[if IE ]><body class="ie"><![endif]-->
    <!--[if !IE]>--><body><!--<![endif]-->
    

    Now in your css code, you can simply do:

    .ie .abc {
      position:absolute;
      left:30;
      top:-10;
    }
    

    This also keeps your CSS files valid, as you do not have to use dirty (and invalid) CSS hacks.

    Spring Bean Scopes

    A short example what is the difference between @Scope("singleton") (default) and @Scope("prototype"):

    DAO class:

    package com.example.demo;
    
    public class Manager {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Configuration:

    @Configuration
    public class AppConfiguration {
        @Bean
        @Scope("singleton")
        public Manager getManager(){
            return new Manager();
        }
    }
    

    and MainApp:

    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
            context.scan("com.example.demo");
            context.refresh();
    
            Manager firstManager = context.getBean(Manager.class);
            firstManager.setName("Karol");
    
            Manager secondManager = context.getBean(Manager.class);
            System.out.println(secondManager.getName());
        }
    
    }
    

    In this example the result is: Karol even if we set this name only for firstManager object. It's because Spring IoC container created one instance of object. However when we change scope to @Scope("prototype") in Configuration class then result is: null because Spring IoC container creates a new bean instance of the object when request for that bean is made.

    Data binding for TextBox

    We can use following code

    textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
    

    Where

    • "Text" – the property of textbox
    • model – the model object enter code here
    • "Name" – the value of model which to bind the textbox.

    How get permission for camera in android.(Specifically Marshmallow)

    I try to add following code:

    private static final int MY_CAMERA_REQUEST_CODE = 100;
    
    @RequiresApi(api = Build.VERSION_CODES.M)
    
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
        }
    

    On onCreate Function and this following code:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }
    

    And this worked for me :)

    client denied by server configuration

    in my case,

    i'm using macOS Mojave (Apache/2.4.34). There was an issue in virtual host settings at /etc/apache2/extra/httpd-vhosts.conf file. after adding the required directory tag my problem was gone.

    Require all granted

    Hope the full virtual host setup structure will save you.

    <VirtualHost *:80>
        DocumentRoot "/Users/vagabond/Sites/MainProjectFolderName/public/"
        ServerName project.loc
    
        <Directory /Users/vagabond/Sites/MainProjectFolderName/public/>
            Require all granted
        </Directory>
    
        ErrorLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-error_log"
        CustomLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-access_log" common
    </VirtualHost>
    

    all you've to do replace the MainProjectFolderName with your exact ProjectFolderName.

    jQuery replace one class with another

    You can use .removeClass and .addClass. More in http://api.jquery.com.

    How to limit file upload type file size in PHP?

    Hope this helps :-)

    if(isset($_POST['submit'])){
        ini_set("post_max_size", "30M");
        ini_set("upload_max_filesize", "30M");
        ini_set("memory_limit", "20000M"); 
        $fileName='product_demo.png';
    
        if($_FILES['imgproduct']['size'] > 0 && 
                (($_FILES["imgproduct"]["type"] == "image/gif") || 
                    ($_FILES["imgproduct"]["type"] == "image/jpeg")|| 
                    ($_FILES["imgproduct"]["type"] == "image/pjpeg") || 
                    ($_FILES["imgproduct"]["type"] == "image/png") &&
                    ($_FILES["imgproduct"]["size"] < 2097152))){
    
            if ($_FILES["imgproduct"]["error"] > 0){
                echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
            } else {    
                $rnd=rand(100,999);
                $rnd=$rnd."_";
                $fileName = $rnd.trim($_FILES['imgproduct']['name']);
                $tmpName  = $_FILES['imgproduct']['tmp_name'];
                $fileSize = $_FILES['imgproduct']['size'];
                $fileType = $_FILES['imgproduct']['type'];  
                $target = "upload/";
                echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ; 
                move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
            }
        } else {
            echo "Sorry, there was a problem uploading your file.";
        }
    }
    

    Android java.lang.NoClassDefFoundError

    Try going to Project -> Properties -> Java Build Path -> Order & Export And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.

    3D Plotting from X, Y, Z Data, Excel or other Tools

    You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

          13    21   29      37    45   
    1000  75.2                              
    1000       79.21                            
    1000             80.02                      
    5000             87.9                   
    5000                    88.54               
    5000                           88.56            
    10000            90.11      
    10000                   90.79   
    10000                          90.87
    

    Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

    The best 3D representation that Excel will give you of the above data is pretty confusing:

    enter image description here

    Representing this limited dataset as 2D data might be a better choice:

    enter image description here

    As a note for future reference, these types of questions usually do a little better on superuser.com.

    Does reading an entire file leave the file handle open?

    You can use pathlib.

    For Python 3.5 and above:

    from pathlib import Path
    contents = Path(file_path).read_text()
    

    For older versions of Python use pathlib2:

    $ pip install pathlib2
    

    Then:

    from pathlib2 import Path
    contents = Path(file_path).read_text()
    

    This is the actual read_text implementation:

    def read_text(self, encoding=None, errors=None):
        """
        Open the file in text mode, read it, and close the file.
        """
        with self.open(mode='r', encoding=encoding, errors=errors) as f:
            return f.read()
    

    OS detecting makefile

    Another way to do this is by using a "configure" script. If you are already using one with your makefile, you can use a combination of uname and sed to get things to work out. First, in your script, do:

    UNAME=uname
    

    Then, in order to put this in your Makefile, start out with Makefile.in which should have something like

    UNAME=@@UNAME@@
    

    in it.

    Use the following sed command in your configure script after the UNAME=uname bit.

    sed -e "s|@@UNAME@@|$UNAME|" < Makefile.in > Makefile
    

    Now your makefile should have UNAME defined as desired. If/elif/else statements are all that's left!

    Remove NaN from pandas series

    If you have a pandas serie with NaN, and want to remove it (without loosing index):

    serie = serie.dropna()

    # create data for example
    data = np.array(['g', 'e', 'e', 'k', 's']) 
    ser = pd.Series(data)
    ser.replace('e', np.NAN)
    print(ser)
    
    0      g
    1    NaN
    2    NaN
    3      k
    4      s
    dtype: object
    
    # the code
    ser = ser.dropna()
    print(ser)
    
    0    g
    3    k
    4    s
    dtype: object
    

    JavaScript get child element

    ULs don't have a name attribute, but you can reference the ul by tag name.

    Try replacing line 3 in your script with this:

    var sub = cat.getElementsByTagName("UL");
    

    How do I get the last character of a string?

    Here is a method using String.charAt():

    String str = "India";
    System.out.println("last char = " + str.charAt(str.length() - 1));
    

    The resulting output is last char = a.

    How to get data out of a Node.js http get request

    I think it's too late to answer this question but I faced the same problem recently my use case was to call the paginated JSON API and get all the data from each pagination and append it to a single array.

    const https = require('https');
    const apiUrl = "https://example.com/api/movies/search/?Title=";
    let finaldata = [];
    let someCallBack = function(data){
      finaldata.push(...data);
      console.log(finaldata);
    };
    const getData = function (substr, pageNo=1, someCallBack) {
    
      let actualUrl = apiUrl + `${substr}&page=${pageNo}`;
      let mydata = []
      https.get(actualUrl, (resp) => {
        let data = '';
        resp.on('data', (chunk) => {
            data += chunk;
        });
        resp.on('end', async () => {
            if (JSON.parse(data).total_pages!==null){
              pageNo+=1;
              somCallBack(JSON.parse(data).data);
              await getData(substr, pageNo, someCallBack);
            }
        });
      }).on("error", (err) => {
          console.log("Error: " + err.message);
      });
    }
    
    getData("spiderman", pageNo=1, someCallBack);
    

    Like @ackuser mentioned we can use other module but In my use case I had to use the node https. Hoping this will help others.

    Convert data.frame column to a vector?

    You can try something like this-

    as.vector(unlist(aframe$a2))
    

    Ignore self-signed ssl cert using Jersey Client

    For Jersey 2.*:

    Client client = ClientBuilder.newBuilder()
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    }).build();
    

    -> https://jersey.java.net/documentation/latest/migration.html

    Multiple actions were found that match the request in Web Api

    It is possible due to using MVC controller instead of Web API controller. Check the namespace in Web API controller it should be as following

    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    

    If the namespace are as following then it is give above error in web api controller method calling

    using System.Web;
    using System.Web.Mvc;
    

    Pandas groupby month and year

    There are different ways to do that.

    • I created the data frame to showcase the different techniques to filter your data.
    df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],
    

    'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

    • I separated months/year/day and seperated month-year as you explained.
    def getMonth(s):
      return s.split("-")[1]
    
    def getDay(s):
      return s.split("-")[0]
    
    def getYear(s):
      return s.split("-")[2]
    
    def getYearMonth(s):
      return s.split("-")[1]+"-"+s.split("-")[2]
    
    • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
    df['year']= df['Date'].apply(lambda x: getYear(x))
    df['month']= df['Date'].apply(lambda x: getMonth(x))
    df['day']= df['Date'].apply(lambda x: getDay(x))
    df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))
    

    Output:

            Date  abc  xyz year month day YearMonth
    0  01-Jun-13  100  200   13   Jun  01    Jun-13
    1  03-Jun-13  -20   50   13   Jun  03    Jun-13
    2  15-Aug-13   40   -5   13   Aug  15    Aug-13
    3  20-Jan-14   25   15   14   Jan  20    Jan-14
    4  21-Feb-14   60   80   14   Feb  21    Feb-14
    
    • You can go through the different groups in groupby(..) items.

    In this case, we are grouping by two columns:

    for key,g in df.groupby(['year','month']):
        print key,g
    

    Output:

    ('13', 'Jun')         Date  abc  xyz year month day YearMonth
    0  01-Jun-13  100  200   13   Jun  01    Jun-13
    1  03-Jun-13  -20   50   13   Jun  03    Jun-13
    ('13', 'Aug')         Date  abc  xyz year month day YearMonth
    2  15-Aug-13   40   -5   13   Aug  15    Aug-13
    ('14', 'Jan')         Date  abc  xyz year month day YearMonth
    3  20-Jan-14   25   15   14   Jan  20    Jan-14
    ('14', 'Feb')         Date  abc  xyz year month day YearMonth
    

    In this case, we are grouping by one column:

    for key,g in df.groupby(['YearMonth']):
        print key,g
    

    Output:

    Jun-13         Date  abc  xyz year month day YearMonth
    0  01-Jun-13  100  200   13   Jun  01    Jun-13
    1  03-Jun-13  -20   50   13   Jun  03    Jun-13
    Aug-13         Date  abc  xyz year month day YearMonth
    2  15-Aug-13   40   -5   13   Aug  15    Aug-13
    Jan-14         Date  abc  xyz year month day YearMonth
    3  20-Jan-14   25   15   14   Jan  20    Jan-14
    Feb-14         Date  abc  xyz year month day YearMonth
    4  21-Feb-14   60   80   14   Feb  21    Feb-14
    
    • In case you wanna access to specific item, you can use get_group

    print df.groupby(['YearMonth']).get_group('Jun-13')

    Output:

            Date  abc  xyz year month day YearMonth
    0  01-Jun-13  100  200   13   Jun  01    Jun-13
    1  03-Jun-13  -20   50   13   Jun  03    Jun-13
    
    • Similar to get_group. This hack would help to filter values and get the grouped values.

    This also would give the same result.

    print df[df['YearMonth']=='Jun-13'] 
    

    Output:

            Date  abc  xyz year month day YearMonth
    0  01-Jun-13  100  200   13   Jun  01    Jun-13
    1  03-Jun-13  -20   50   13   Jun  03    Jun-13
    

    You can select list of abc or xyz values during Jun-13

    print df[df['YearMonth']=='Jun-13'].abc.values
    print df[df['YearMonth']=='Jun-13'].xyz.values
    

    Output:

    [100 -20]  #abc values
    [200  50]  #xyz values
    

    You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

    for x in set(df.YearMonth): 
        print df[df['YearMonth']==x].abc.values
        print df[df['YearMonth']==x].xyz.values
    

    I recommend also to check this answer as well.

    Equivalent of explode() to work with strings in MySQL

    First of all you should change database structure - the score in this case is some kind of composite value and should be stored in two columns, eg. score_host, score_guest.


    MySQL doesn't provide explode() equivalent however in this case you could use SUBSTRING() and LOCATE() to cut off score of a host and a guest.

    SELECT 
       CONVERT(SUBSTRING(score, 1, LOCATE('-',score) - 2) USING INTEGER) as score_host,
       CONVERT(SUBSTRING(score, LOCATE('-',score)+2) USING INTEGER) as score_guest
    FROM ...;
    

    CONVERT() is used to cast a string "23" into number 23.

    How to get request URI without context path?

    request.getRequestURI().substring(request.getContextPath().length())
    

    Get the week start date and week end date from week number

    I just encounter a similar case with this one, but the solution here seems not helping me. So I try to figure it out by myself. I work out the week start date only, week end date should be of similar logic.

    Select 
          Sum(NumberOfBrides) As [Wedding Count], 
          DATEPART( wk, WeddingDate) as [Week Number],
          DATEPART( year, WeddingDate) as [Year],
          DATEADD(DAY, 1 - DATEPART(WEEKDAY, dateadd(wk, DATEPART( wk, WeddingDate)-1,  DATEADD(yy,DATEPART( year, WeddingDate)-1900,0))), dateadd(wk, DATEPART( wk, WeddingDate)-1, DATEADD(yy,DATEPART( year, WeddingDate)-1900,0))) as [Week Start]
    
    FROM  MemberWeddingDates
    Group By DATEPART( year, WeddingDate), DATEPART( wk, WeddingDate)
    Order By Sum(NumberOfBrides) Desc
    

    Sending emails in Node.js?

    campaign is a comprehensive solution for sending emails in Node, and it comes with a very simple API.

    You instance it like this.

    var client = require('campaign')({
      from: '[email protected]'
    });
    

    To send emails, you can use Mandrill, which is free and awesome. Just set your API key, like this:

    process.env.MANDRILL_APIKEY = '<your api key>';
    

    (if you want to send emails using another provider, check the docs)

    Then, when you want to send an email, you can do it like this:

    client.sendString('<p>{{something}}</p>', {
      to: ['[email protected]', '[email protected]'],
      subject: 'Some Subject',
      preview': 'The first line',
      something: 'this is what replaces that thing in the template'
    }, done);
    

    The GitHub repo has pretty extensive documentation.

    Print empty line?

    Python 2.x: Prints a newline

    print      
    

    Python 3.x: You must call the function

    print() 
    

    Source: https://docs.python.org/3.0/whatsnew/3.0.html

    How to locate and insert a value in a text box (input) using Python Selenium?

    Assuming your page is available under "http://example.com"

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.Firefox()
    driver.get("http://example.com")
    

    Select element by id:

    inputElement = driver.find_element_by_id("a1")
    inputElement.send_keys('1')
    

    Now you can simulate hitting ENTER:

    inputElement.send_keys(Keys.ENTER)
    

    or if it is a form you can submit:

    inputElement.submit() 
    

    href="file://" doesn't work

    The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

    The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

    Note

    If you link to something like

    <a href="file:///K:/yourfile.pdf">yourfile.pdf</a>
    

    The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

    You can do this, for example the below creates a link to C:\temp\test.pdf

    <a href="file:///C:/Temp/test.pdf">test.pdf</a>
    

    By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

    Most people do not have a K:/ drive.

    But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

    You could try

    <a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
    <a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
    <a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
    

    Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

    How do I URl encode something in Node.js?

    encodeURIComponent(string) will do it:

    encodeURIComponent("Robert'); DROP TABLE Students;--")
    //>> "Robert')%3B%20DROP%20TABLE%20Students%3B--"
    

    Passing SQL around in a query string might not be a good plan though,

    see this one

    Why maven settings.xml file is not there?

    By Installing Maven you can not expect the settings.xml in your .m2 folder(If may be hidden folder, to unhide just press Ctrl+h). You need to place the file explicitly at that location. After placing the file maven plugin for eclipse will start using that file too.

    AngularJS app.run() documentation?

    Specifically...

    How and where is app.run() used? After module definition or after app.config(), after app.controller()?

    Where:

    In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

    How:

    Make it look like this

    var app = angular.module('mean.dashboard', ['ui.bootstrap']);
    
    app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
        function($scope, Global, Dashboard) {
            $scope.global = Global;
            $scope.package = {
                name: 'dashboard'
            };
            // ...
        }
    ]);
    
    app.run(function(editableOptions) {
        editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
    });
    

    What's the "Content-Length" field in HTTP header?

    According to the spec:

    The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

    Content-Length    = "Content-Length" ":" 1*DIGIT
    

    An example is

    Content-Length: 3495
    

    Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.

    Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.

    Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.

    SQL Server - SELECT FROM stored procedure

    You can copy output from sp to temporaty table.

    CREATE TABLE #GetVersionValues
    (
        [Index] int,
        [Name]  sysname,
        Internal_value  int,
        Character_Value sysname
    )
    INSERT #GetVersionValues EXEC master.dbo.xp_msver 'WindowsVersion'
    SELECT * FROM #GetVersionValues
    drop TABLE #GetVersionValues
    

    How to implement a read only property

    C# 6.0 adds readonly auto properties

    public object MyProperty { get; }
    

    So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


    Versioning:
    I think it doesn't make much difference if you are only interested in source compatibility.
    Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

    Convention:
    You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

    Serialization
    Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

    Using an Autoproperty
    Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

    Readonly field is selfdocumenting
    There is one advantage of the field though:
    It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

    But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

    Passing by reference in C

    pointers and references are two different thigngs.

    A couple of things I have not seen mentioned.

    A pointer is the address of something. A pointer can be stored and copied like any other variable. It thus have a size.

    A reference should be seen as an ALIAS of something. It does not have a size and cannot be stored. It MUST reference something, ie. it cannot be null or changed. Well, sometimes the compiler needs to store the reference as a pointer, but that is an implementation detail.

    With references you don't have the issues with pointers, like ownership handling, null checking, de-referencing on use.

    Send POST data using XMLHttpRequest

    I have faced similar problem, using the same post and and this link I have resolved my issue.

     var http = new XMLHttpRequest();
     var url = "MY_URL.Com/login.aspx";
     var params = 'eid=' +userEmailId+'&amp;pwd='+userPwd
    
     http.open("POST", url, true);
    
     // Send the proper header information along with the request
     //http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     //http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
     //http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
    
     // Call a function when the state 
     http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
     }
     http.send(params);
    

    This link has completed information.

    Validating input using java.util.Scanner

    One idea:

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

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

    SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

    After running below command it works for me

    sudo chmod 600 /path/to/my/key.pem

    What is the correct way to read from NetworkStream in .NET

    Networking code is notoriously difficult to write, test and debug.

    You often have lots of things to consider such as:

    • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

    • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

    • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

    If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

    Here are several different ways to handle the exchange:

    • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

    • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

    • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

    • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

    Each approach has its pros and cons for "correctness".

    The code below uses the "timeout" method, as that seems to be the one you want.

    See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

    string SendCmd(string cmd, string ip, int port)
    {
      var client = new TcpClient(ip, port);
      var data = Encoding.GetEncoding(1252).GetBytes(cmd);
      var stm = client.GetStream();
      // Set a 250 millisecond timeout for reading (instead of Infinite the default)
      stm.ReadTimeout = 250;
      stm.Write(data, 0, data.Length);
      byte[] resp = new byte[2048];
      var memStream = new MemoryStream();
      int bytesread = stm.Read(resp, 0, resp.Length);
      while (bytesread > 0)
      {
          memStream.Write(resp, 0, bytesread);
          bytesread = stm.Read(resp, 0, resp.Length);
      }
      return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
    }
    

    As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

    How should I escape strings in JSON?

    Not sure what you mean by "creating json manually", but you can use something like gson (http://code.google.com/p/google-gson/), and that would transform your HashMap, Array, String, etc, to a JSON value. I recommend going with a framework for this.

    Why shouldn't I use mysql_* functions in PHP?

    Ease of use

    The analytic and synthetic reasons were already mentioned. For newcomers there's a more significant incentive to stop using the dated mysql_ functions.

    Contemporary database APIs are just easier to use.

    It's mostly the bound parameters which can simplify code. And with excellent tutorials (as seen above) the transition to PDO isn't overly arduous.

    Rewriting a larger code base at once however takes time. Raison d'être for this intermediate alternative:

    Equivalent pdo_* functions in place of mysql_*

    Using <pdo_mysql.php> you can switch from the old mysql_ functions with minimal effort. It adds pdo_ function wrappers which replace their mysql_ counterparts.

    1. Simply include_once("pdo_mysql.php"); in each invocation script that has to interact with the database.

    2. Remove the mysql_ function prefix everywhere and replace it with pdo_.

      • mysql_connect() becomes pdo_connect()
      • mysql_query() becomes pdo_query()
      • mysql_num_rows() becomes pdo_num_rows()
      • mysql_insert_id() becomes pdo_insert_id()
      • mysql_fetch_array() becomes pdo_fetch_array()
      • mysql_fetch_assoc() becomes pdo_fetch_assoc()
      • mysql_real_escape_string() becomes pdo_real_escape_string()
      • and so on...

    3. Your code will work alike and still mostly look the same:

      include_once("pdo_mysql.php"); 
      
      pdo_connect("localhost", "usrABC", "pw1234567");
      pdo_select_db("test");
      
      $result = pdo_query("SELECT title, html FROM pages");  
      
      while ($row = pdo_fetch_assoc($result)) {
          print "$row[title] - $row[html]";
      }
      

    Et voilà.
    Your code is using PDO.
    Now it's time to actually utilize it.

    Bound parameters can be easy to use

    You just need a less unwieldy API.

    pdo_query() adds very facile support for bound parameters. Converting old code is straightforward:

    Move your variables out of the SQL string.

    • Add them as comma delimited function parameters to pdo_query().
    • Place question marks ? as placeholders where the variables were before.
    • Get rid of ' single quotes that previously enclosed string values/variables.

    The advantage becomes more obvious for lengthier code.

    Often string variables aren't just interpolated into SQL, but concatenated with escaping calls in between.

    pdo_query("SELECT id, links, html, title, user, date FROM articles
       WHERE title='" . pdo_real_escape_string($title) . "' OR id='".
       pdo_real_escape_string($title) . "' AND user <> '" .
       pdo_real_escape_string($root) . "' ORDER BY date")
    

    With ? placeholders applied you don't have to bother with that:

    pdo_query("SELECT id, links, html, title, user, date FROM articles
       WHERE title=? OR id=? AND user<>? ORDER BY date", $title, $id, $root)
    

    Remember that pdo_* still allows either or.
    Just don't escape a variable and bind it in the same query.

    • The placeholder feature is provided by the real PDO behind it.
    • Thus also allowed :named placeholder lists later.

    More importantly you can pass $_REQUEST[] variables safely behind any query. When submitted <form> fields match the database structure exactly it's even shorter:

    pdo_query("INSERT INTO pages VALUES (?,?,?,?,?)", $_POST);
    

    So much simplicity. But let's get back to some more rewriting advises and technical reasons on why you may want to get rid of mysql_ and escaping.

    Fix or remove any oldschool sanitize() function

    Once you have converted all mysql_ calls to pdo_query with bound params, remove all redundant pdo_real_escape_string calls.

    In particular you should fix any sanitize or clean or filterThis or clean_data functions as advertised by dated tutorials in one form or the other:

    function sanitize($str) {
       return trim(strip_tags(htmlentities(pdo_real_escape_string($str))));
    }
    

    Most glaring bug here is the lack of documentation. More significantly the order of filtering was in exactly the wrong order.

    • Correct order would have been: deprecatedly stripslashes as the innermost call, then trim, afterwards strip_tags, htmlentities for output context, and only lastly the _escape_string as its application should directly preceed the SQL intersparsing.

    • But as first step just get rid of the _real_escape_string call.

    • You may have to keep the rest of your sanitize() function for now if your database and application flow expect HTML-context-safe strings. Add a comment that it applies only HTML escaping henceforth.

    • String/value handling is delegated to PDO and its parameterized statements.

    • If there was any mention of stripslashes() in your sanitize function, it may indicate a higher level oversight.

      • That was commonly there to undo damage (double escaping) from the deprecated magic_quotes. Which however is best fixed centrally, not string by string.

      • Use one of the userland reversal approaches. Then remove the stripslashes() in the sanitize function.

      Historic note on magic_quotes. That feature is rightly deprecated. It's often incorrectly portrayed as failed security feature however. But magic_quotes are as much a failed security feature as tennis balls have failed as nutrition source. That simply wasn't their purpose.

      The original implementation in PHP2/FI introduced it explicitly with just "quotes will be automatically escaped making it easier to pass form data directly to msql queries". Notably it was accidentially safe to use with mSQL, as that supported ASCII only.
      Then PHP3/Zend reintroduced magic_quotes for MySQL and misdocumented it. But originally it was just a convenience feature, not intend for security.

    How prepared statements differ

    When you scramble string variables into the SQL queries, it doesn't just get more intricate for you to follow. It's also extraneous effort for MySQL to segregate code and data again.

    SQL injections simply are when data bleeds into code context. A database server can't later spot where PHP originally glued variables inbetween query clauses.

    With bound parameters you separate SQL code and SQL-context values in your PHP code. But it doesn't get shuffled up again behind the scenes (except with PDO::EMULATE_PREPARES). Your database receives the unvaried SQL commands and 1:1 variable values.

    While this answer stresses that you should care about the readability advantages of dropping mysql_. There's occasionally also a performance advantage (repeated INSERTs with just differing values) due to this visible and technical data/code separation.

    Beware that parameter binding still isn't a magic one-stop solution against all SQL injections. It handles the most common use for data/values. But can't whitelist column name / table identifiers, help with dynamic clause construction, or just plain array value lists.

    Hybrid PDO use

    These pdo_* wrapper functions make a coding-friendly stop-gap API. (It's pretty much what MYSQLI could have been if it wasn't for the idiosyncratic function signature shift). They also expose the real PDO at most times.
    Rewriting doesn't have to stop at using the new pdo_ function names. You could one by one transition each pdo_query() into a plain $pdo->prepare()->execute() call.

    It's best to start at simplifying again however. For example the common result fetching:

    $result = pdo_query("SELECT * FROM tbl");
    while ($row = pdo_fetch_assoc($result)) {
    

    Can be replaced with just an foreach iteration:

    foreach ($result as $row) {
    

    Or better yet a direct and complete array retrieval:

    $result->fetchAll();
    

    You'll get more helpful warnings in most cases than PDO or mysql_ usually provide after failed queries.

    Other options

    So this hopefully visualized some practical reasons and a worthwile pathway to drop mysql_.

    Just switching to doesn't quite cut it. pdo_query() is also just a frontend onto it.

    Unless you also introduce parameter binding or can utilize something else from the nicer API, it's a pointless switch. I hope it's portrayed simple enough to not further the discouragement to newcomers. (Education usually works better than prohibition.)

    While it qualifies for the simplest-thing-that-could-possibly-work category, it's also still very experimental code. I just wrote it over the weekend. There's a plethora of alternatives however. Just google for PHP database abstraction and browse a little. There always have been and will be lots of excellent libraries for such tasks.

    If you want to simplify your database interaction further, mappers like Paris/Idiorm are worth a try. Just like nobody uses the bland DOM in JavaScript anymore, you don't have to babysit a raw database interface nowadays.

    How do I evenly add space between a label and the input field regardless of length of text?

    2019 answer:

    Some time has passed and I changed my approach now when building forms. I've done thousands of them till today and got really tired of typing id for every label/input pair, so this was flushed down the toilet. When you dive input right into the label, things work the same way, no ids necessary. I also took advantage of flexbox being, well, very flexible.

    HTML:

    <label>
      Short label <input type="text" name="dummy1" />
    </label>
    
    <label>
      Somehow longer label <input type="text" name="dummy2" />
    </label>
    
    <label>
      Very long label for testing purposes <input type="text" name="dummy3" />
    </label>
    

    CSS:

    label {
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      text-align: right;
      width: 400px;
      line-height: 26px;
      margin-bottom: 10px;
    }
    
    input {
      height: 20px;
      flex: 0 0 200px;
      margin-left: 10px;
    }
    

    Fiddle DEMO


    Original answer:

    Use label instead of span. It's meant to be paired with inputs and preserves some additional functionality (clicking label focuses the input).

    This might be exactly what you want:

    HTML:

    <label for="dummy1">title for dummy1:</label>
    <input id="dummy1" name="dummy1" value="dummy1">
    
    <label for="dummy2">longer title for dummy2:</label>
    <input id="dummy2" name="dummy2" value="dummy2">
    
    <label for="dummy3">even longer title for dummy3:</label>
    <input id="dummy3" name="dummy3" value="dummy3">
    

    CSS:

    label {
        width:180px;
        clear:left;
        text-align:right;
        padding-right:10px;
    }
    
    input, label {
        float:left;
    }
    

    jsfiddle DEMO here.

    What does LINQ return when the results are empty

    var lst = new List<int>() { 1, 2, 3 };
    var ans = lst.Where( i => i > 3 );
    
    (ans == null).Dump();  // False
    (ans.Count() == 0 ).Dump();  // True
    

    (Dump is from LinqPad)

    Verify ImageMagick installation

    If your ISP/hosting service has installed ImageMagick and put its location in the PATH environment variable, you can find what versions are installed and where using:

    <?php
    echo "<pre>";
    system("type -a convert");  
    echo "</pre>";
    ?> 
    

    Disable clipboard prompt in Excel VBA on workbook close

    proposed solution edit works if you replace the row

    Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
    

    with

    Set rDst = ThisWorkbook.Sheets("SomeSheet").Range("YourRange").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
    

    Difference between int and double

    int and double have different semantics. Consider division. 1/2 is 0, 1.0/2.0 is 0.5. In any given situation, one of those answers will be right and the other wrong.

    That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int. Languages such as Java that support integer types make truncation automatic for integer variables.

    In addition to having different semantics from double, int arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.

    iPhone system font

    To the delight of font purists everywhere, the iPhone system interface uses Helvetica or a variant thereof.

    The original iPhone, iPhone 3G and iPhone 3GS system interface uses Helvetica. As first noted by the always excellent DaringFireball, the iPhone 4 uses a subtly revised font called "Helvetica Neue." DaringFireball also notes that this change is related to the iPhone 4 display rather than the iOS 4 operating system and older iPhone models running iOS 4 still use Helvetica as the system font.

    iPod models released prior to the iPhone use either Chicago, Espy Sans, or Myriad and use Helvetica after the release of the iPhone.

    From http://www.everyipod.com/iphone-faq/iphone-who-designed-iphone-font-used-iphone-ringtones.html

    For iOS9 it has changed to San Fransisco. See http://developer.apple.com/fonts for more info.

    IIS Request Timeout on long ASP.NET operation

    Remove ~ character in location so

    path="~/Admin/SomePage.aspx"
    

    becomes

    path="Admin/SomePage.aspx"
    

    Allowing Untrusted SSL Certificates with HttpClient

    If you're attempting to do this in a .NET Standard library, here's a simple solution, with all of the risks of just returning true in your handler. I leave safety up to you.

    var handler = new HttpClientHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.ServerCertificateCustomValidationCallback = 
        (httpRequestMessage, cert, cetChain, policyErrors) =>
    {
        return true;
    };
    
    var client = new HttpClient(handler);
    

    Django Reverse with arguments '()' and keyword arguments '{}' not found

    You have to specify project_id:

    reverse('edit_project', kwargs={'project_id':4})
    

    Doc here

    How to fix "Incorrect string value" errors?

    In my case, Incorrect string value: '\xCC\x88'..., the problem was that an o-umlaut was in its decomposed state. This question-and-answer helped me understand the difference between and ö. In PHP, the fix for me was to use PHP's Normalizer library. E.g., Normalizer::normalize('o¨', Normalizer::FORM_C).

    @Directive vs @Component in Angular

    A @Component requires a view whereas a @Directive does not.

    Directives

    I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

    import {Directive} from '@angular/core';
    
    @Directive({
        selector: "[logOnClick]",
        hostListeners: {
            'click': 'onClick()',
        },
    })
    class LogOnClick {
        constructor() {}
        onClick() { console.log('Element clicked!'); }
    }
    

    Which would be used like so:

    <button logOnClick>I log when clicked!</button>
    

    Components

    A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

    import {Component, View} from '@angular/core';
    
    @Component({
      selector: 'contact-card',
      template: `
        <div>
          <h1>{{name}}</h1>
          <p>{{city}}</p>
        </div>
      `
    })
    class ContactCard {
      @Input() name: string
      @Input() city: string
      constructor() {}
    }
    

    Which would be used like so:

    <contact-card [name]="'foo'" [city]="'bar'"></contact-card>
    

    ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.

    In summary

    Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

    Sources:

    Why is vertical-align: middle not working on my span or div?

    I used this to align everything in the center of the wrapper div in case it helps anyone - I found it simplest:

    _x000D_
    _x000D_
    div.wrapper {_x000D_
      /* --- This works --- */_x000D_
      display: flex;_x000D_
      /* Align Vertically */_x000D_
      align-items: center;_x000D_
      /* Align Horizontally */_x000D_
      justify-content: center;_x000D_
      /* --- ---------- ----- */_x000D_
      width: 100%;_x000D_
      height:100px;_x000D_
      background-color: blue;_x000D_
    }_x000D_
    div.inner {_x000D_
      width: 50px;_x000D_
      height: 50px;_x000D_
      background-color: orange;_x000D_
    }
    _x000D_
    <div class="wrapper">_x000D_
      <div class="inner">_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to change Android version and code version number?

    You can easily auto increase versionName and versionCode programmatically.

    For Android add this to your gradle script and also create a file version.properties with VERSION_CODE=555

    android {
            compileSdkVersion 30
            buildToolsVersion "30.0.3"
        
            def versionPropsFile = file('version.properties')
            if (versionPropsFile.canRead()) {
                def Properties versionProps = new Properties()
        
                versionProps.load(new FileInputStream(versionPropsFile))
        
                def code = versionProps['VERSION_CODE'].toInteger() + 1
        
                versionProps['VERSION_CODE'] = code.toString()
                versionProps.store(versionPropsFile.newWriter(), null)
        
        
                defaultConfig {
                    applicationId "app.umanusorn.playground"
                    minSdkVersion 29
                    targetSdkVersion 30
                    versionCode code
                    versionName code.toString()
    

    printing all contents of array in C#

    If you want to get cute, you could write an extension method that wrote an IEnumerable<object> sequence to the console. This will work with enumerables of any type, because IEnumerable<T> is covariant on T:

    using System;
    using System.Collections.Generic;
    
    namespace Demo
    {
        internal static class Program
        {
            private static void Main(string[] args)
            {
                string[] array  = new []{"One", "Two", "Three", "Four"};
                array.Print();
    
                Console.WriteLine();
    
                object[] objArray = new object[] {"One", 2, 3.3, TimeSpan.FromDays(4), '5', 6.6f, 7.7m};
                objArray.Print();
            }
        }
    
        public static class MyEnumerableExt
        {
            public static void Print(this IEnumerable<object> @this)
            {
                foreach (var obj in @this)
                    Console.WriteLine(obj);
            }
        }
    }
    

    (I don't think you'd use this other than in test code.)

    Serialize an object to XML

    Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.

    Just use it like this:

            string s = new MyObject().Serialize(); // to serialize into a string
            MyObject b = s.Deserialize<MyObject>();// deserialize from a string
    
    
    
    internal static class Extensions
    {
        public static T Deserialize<T>(this string value)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
    
            return (T)xmlSerializer.Deserialize(new StringReader(value));
        }
    
        public static string Serialize<T>(this T value)
        {
            if (value == null)
                return string.Empty;
    
            var xmlSerializer = new XmlSerializer(typeof(T));
    
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
                {
                    xmlSerializer.Serialize(xmlWriter, value);
                    return stringWriter.ToString();
                }
            }
        }
    }
    

    What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

    *args and **kwargs: allow you to pass a variable number of arguments to a function.

    *args: is used to send a non-keyworded variable length argument list to the function:

    def args(normal_arg, *argv):
        print("normal argument:", normal_arg)
    
        for arg in argv:
            print("Argument in list of arguments from *argv:", arg)
    
    args('animals', 'fish', 'duck', 'bird')
    

    Will produce:

    normal argument: animals
    Argument in list of arguments from *argv: fish
    Argument in list of arguments from *argv: duck
    Argument in list of arguments from *argv: bird
    

    **kwargs*

    **kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

    def who(**kwargs):
        if kwargs is not None:
            for key, value in kwargs.items():
                print("Your %s is %s." % (key, value))
    
    who(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")  
    

    Will produce:

    Your name is Nikola.
    Your last_name is Tesla.
    Your birthday is 7.10.1856.
    Your birthplace is Croatia.
    

    Android WebView not loading URL

    maybe SSL

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // ignore ssl error
            if (handler != null){
                handler.proceed();
            } else {
                super.onReceivedSslError(view, null, error);
            }
        }
    

    How to get the URL of the current page in C#

    You may at times need to get different values from URL.

    Below example shows different ways of extracting different parts of URL

    EXAMPLE: (Sample URL)

    http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2

    CODE

    Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
    Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
    Response.Write("<br/> " + HttpContext.Current.Request.Url.Port);
    Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
    Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
    Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
    Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
    

    OUTPUT

    localhost
    localhost:60527
    60527
    /WebSite1test/Default2.aspx
    /WebSite1test
    http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
    /WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
    

    You can copy paste above sample code & run it in asp.net web form application with different URL.

    I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.

    http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx

    return results from a function (javascript, nodejs)

    You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

    As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

    Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

    How to rename array keys in PHP?

    Recursive php rename keys function:

    function replaceKeys($oldKey, $newKey, array $input){
        $return = array(); 
        foreach ($input as $key => $value) {
            if ($key===$oldKey)
                $key = $newKey;
    
            if (is_array($value))
                $value = replaceKeys( $oldKey, $newKey, $value);
    
            $return[$key] = $value;
        }
        return $return; 
    }
    

    C: Run a System Command and Get Output?

    You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main( int argc, char *argv[] )
    {
    
      FILE *fp;
      char path[1035];
    
      /* Open the command for reading. */
      fp = popen("/bin/ls /etc/", "r");
      if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
      }
    
      /* Read the output a line at a time - output it. */
      while (fgets(path, sizeof(path), fp) != NULL) {
        printf("%s", path);
      }
    
      /* close */
      pclose(fp);
    
      return 0;
    }
    

    How to set a Postgresql default value datestamp like 'YYYYMM'?

    It's a common misconception that you can denormalise like this for performance. Use date_trunc('month', date) for your queries and add an index expression for this if you find it running slow.

    Make a borderless form movable?

    Also if you need to DoubleClick and make your Form bigger/smaller , you can use the First answer, create a global int variable, add 1 every time user clicks on the component you use for dragging. If variable == 2 then make your form bigger/smaller. Also use a timer for every half a sec or a second to make your variable = 0;

    Android changing Floating Action Button color

    The document suggests that it takes the @color/accent by default. But we can override it on code by using

    fab.setBackgroundTintList(ColorStateList)
    

    Also remember,

    The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!

    Change a web.config programmatically with C# (.NET)

    Here it is some code:

    var configuration = WebConfigurationManager.OpenWebConfiguration("~");
    var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
    section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
    configuration.Save();
    

    See more examples in this article, you may need to take a look to impersonation.