Programs & Examples On #Celko

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

How to convert an array of strings to an array of floats in numpy?

If you have (or create) a single string, you can use np.fromstring:

import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )

Note, x = ','.join(x) transforms the x array to string '1.1, 2.2, 3.2'. If you read a line from a txt file, each line will be already a string.

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

Just if someone is having this issue and hadn't done list[index, sub-index], you could be having the problem because you're missing a comma between two arrays in an array of arrays (It happened to me).

How to set up fixed width for <td>?

In my case I was able to fix that issue by using min-width: 100px instead of width: 100px for the cells th or td.

.table td, .table th {
    min-width: 100px;
}

CSS hexadecimal RGBA?

Chrome 52+ supports alpha hex:

background: #56ff0077;

Unable to establish SSL connection, how do I fix my SSL cert?

There are a few possibilities:

  1. Your workstation doesn't have the root CA cert used to sign your server's cert. How exactly you fix that depends on what OS you're running and what release, etc. (I suspect this is not related)
  2. Your cert isn't installed properly. If your SSL cert requires an intermediate cert to be presented and you didn't set that up, you can get these warnings.
  3. Are you sure you've enabled SSL on port 443?

For starters, to eliminate (3), what happens if you telnet to that port?

Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.

If you want to manually verify the cert, post more details from the openssl s_client output. Or use openssl x509 -text -in /path/to/cert to print it out to your terminal.

Get a Div Value in JQuery

You can do get id value by using

_x000D_
_x000D_
test_alert = $('#myDiv').val();_x000D_
alert(test_alert);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
_x000D_
_x000D_

Raise warning in Python without interrupting program

import warnings
warnings.warn("Warning...........Message")

See the python documentation: here

How to allow only numbers in textbox in mvc4 razor

i was just playing around with HTML5 input type=number. while its not supported by all browsers I expect it is the way going forward to handle type specific handling (number for ex). pretty simple to do with razor (ex is VB)

@Html.TextBoxFor(Function(model) model.Port, New With {.type = "number"})

and thanks to Lee Richardson, the c# way

@Html.TextBoxFor(i => i.Port, new { @type = "number" }) 

beyond the scope of the question but you could do this same approach for any html5 input type

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

I had the same issue, my problem was, that I had two different webservices with two different wsdl-files. I generated the sources in the same package for both webservices, which seems to be a problem. I guess it's because of the ObjectFactory and perhaps also because of the package-info.java - because those are only generated once.

I solved it, by generating the sources for each webservice in a different package. This way, you also have two different ObjectFactories and package-info.java files.

Total Number of Row Resultset getRow Method

You need to call ResultSet#beforeFirst() to put the cursor back to before the first row before you return the ResultSet object. This way the user will be able to use next() the usual way.

resultSet.last();
rows = resultSet.getRow();
resultSet.beforeFirst();
return resultSet;

However, you have bigger problems with the code given as far. It's leaking DB resources and it is also not a proper OOP approach. Lookup the DAO pattern. Ultimately you'd like to end up as

public List<Operations> list() throws SQLException {
    // Declare Connection, Statement, ResultSet, List<Operation>.

    try {
        // Use Connection, Statement, ResultSet.

        while (resultSet.next()) {
            // Add new Operation to list.
        }
    } finally {
        // Close ResultSet, Statement, Connection.
    }

    return list;
}

This way the caller has just to use List#size() to know about the number of records.

How to parse a string into a nullable int

I feel my solution is a very clean and nice solution:

public static T? NullableParse<T>(string s) where T : struct
{
    try
    {
        return (T)typeof(T).GetMethod("Parse", new[] {typeof(string)}).Invoke(null, new[] { s });
    }
    catch (Exception)
    {
        return null;
    }
}

This is of course a generic solution which only require that the generics argument has a static method "Parse(string)". This works for numbers, boolean, DateTime, etc.

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

How do you get the length of a string?

jQuery is a JavaScript library.

You don't need to use jQuery to get the length of a string because it is a basic JavaScript string object property.

somestring.length;

Fit image to table cell [Pure HTML]

Inline content leaves space at the bottom for characters that descend (j, y, q):

https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps

There are a couple fixes:

Use display: block;

<img style="display:block;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

or use vertical-align: bottom;

<img style="vertical-align: bottom;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

Convert tuple to list and back

Convert tuple to list:

>>> t = ('my', 'name', 'is', 'mr', 'tuple')
>>> t
('my', 'name', 'is', 'mr', 'tuple')
>>> list(t)
['my', 'name', 'is', 'mr', 'tuple']

Convert list to tuple:

>>> l = ['my', 'name', 'is', 'mr', 'list']
>>> l
['my', 'name', 'is', 'mr', 'list']
>>> tuple(l)
('my', 'name', 'is', 'mr', 'list')

Set mouse focus and move cursor to end of input using jQuery

    function focusCampo(id){
        var inputField = document.getElementById(id);
        if (inputField != null && inputField.value.length != 0){
            if (inputField.createTextRange){
                var FieldRange = inputField.createTextRange();
                FieldRange.moveStart('character',inputField.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                var elemLen = inputField.value.length;
                inputField.selectionStart = elemLen;
                inputField.selectionEnd = elemLen;
                inputField.focus();
            }
        }else{
            inputField.focus();
        }
    }

$('#urlCompany').focus(focusCampo('urlCompany'));

works for all ie browsers..

Decompile Python 2.7 .pyc

Here is a great tool to decompile pyc files.

It was coded by me and supports python 1.0 - 3.3

Its based on uncompyle2 and decompyle++

http://sourceforge.net/projects/easypythondecompiler/

Remove values from select list based on condition

document.getElementById(this).innerHTML = '';

Put it inside your if-case. What it does is just to check for the current object within the document and replace it with nothing. You'll have too loop through the list first, I am guessing you are already doing that since you have that if.

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

Convert Date/Time for given Timezone - java

I should like to provide the modern answer.

You shouldn’t really want to convert a date and time from a string at one GMT offset to a string at a different GMT offset and with in a different format. Rather in your program keep an instant (a point in time) as a proper date-time object. Only when you need to give string output, format your object into the desired string.

java.time

Parsing input

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ISO_LOCAL_DATE)
            .appendLiteral(' ')
            .append(DateTimeFormatter.ISO_LOCAL_TIME)
            .toFormatter();

    String dateTimeString = "2011-10-06 03:35:05";
    Instant instant = LocalDateTime.parse(dateTimeString, formatter)
            .atOffset(ZoneOffset.UTC)
            .toInstant();

For most purposes Instant is a good choice for storing a point in time. If you needed to make it explicit that the date and time came from GMT, use an OffsetDateTime instead.

Converting, formatting and printing output

    ZoneId desiredZone = ZoneId.of("Pacific/Auckland");
    Locale desiredeLocale = Locale.forLanguageTag("en-NZ");
    DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern(
            "dd MMM uuuu HH:mm:ss OOOO", desiredeLocale);

    ZonedDateTime desiredDateTime = instant.atZone(desiredZone);
    String result = desiredDateTime.format(desiredFormatter);
    System.out.println(result);

This printed:

06 Oct 2011 16:35:05 GMT+13:00

I specified time zone Pacific/Auckland rather than the offset you mentioned, +13:00. I understood that you wanted New Zealand time, and Pacific/Auckland better tells the reader this. The time zone also takes summer time (DST) into account so you don’t need to take this into account in your own code (for most purposes).

Since Oct is in English, it’s a good idea to give the formatter an explicit locale. GMT might be localized too, but I think that it just prints GMT in all locales.

OOOO in the format patterns string is one way of printing the offset, which may be a better idea than printing the time zone abbreviation you would get from z since time zone abbreviations are often ambiguous. If you want NZDT (for New Zealand Daylight Time), just put z there instead.

Your questions

I will answer your numbered questions in relation to the modern classes in java.time.

Is possible to:

  1. Set the time on an object

No, the modern classes are immutable. You need to create an object that has the desired date and time from the outset (this has a number of advantages including thread safety).

  1. (Possibly) Set the TimeZone of the initial time stamp

The atZone method that I use in the code returns a ZonedDateTime with the specified time zone. Other date-time classes have a similar method, sometimes called atZoneSameInstant or other names.

  1. Format the time stamp with a new TimeZone

With java.time converting to a new time zone and formatting are two distinct steps as shown.

  1. Return a string with new time zone time.

Yes, convert to the desired time zone as shown and format as shown.

I found that anytime I try to set the time like this:

calendar.setTime(new Date(1317816735000L));

the local machine's TimeZone is used. Why is that?

It’s not the way you think, which goes nicely to show just a couple of the (many) design problems with the old classes.

  • A Date hasn’t got a time zone. Only when you print it, its toString method grabs your local time zone and uses it for rendering the string. This is true for new Date() too. This behaviour has confused many, many programmers over the last 25 years.
  • A Calender has got a time zone. It doesn’t change when you do calendar.setTime(new Date(1317816735000L));.

Link

Oracle tutorial: Date Time explaining how to use java.time.

How to find the location of the Scheduled Tasks folder

Looks like TaskCache registry data is in ...

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache

... on my Windows 10 PC (i.e. add Schedule before TaskCache and TaskCache has an upper case C).

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Speed comparion (using Wouter's method)

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))

In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop

gradlew command not found?

You must have the Gradle wrapper available locally before using gradlew. To construct that

gradle wrapper # --gradle-version v.xy

Optionally, pass the gradle version explicitly. This step produces the gradlew binary.And then you should be able to

./gradlew build

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

Why docker container exits immediately

Why docker container exits immediately?

If you want to force the image to hang around (in order to debug something or examine state of the file system) you can override the entry point to change it to a shell:

docker run -it --entrypoint=/bin/bash myimagename

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.

http://jsfiddle.net/P2QhE/

Javascript code embedded aswell:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

How to repeat a char using printf?

char buffer[41];

memset(buffer, '-', 40);    // initialize all with the '-' character<br /><br />
buffer[40] = 0;             // put a NULL at the end<br />

printf("%s\n", buffer);     // show 40 dashes<br />

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

Initialize a vector array of strings

In C++0x you will be able to initialize containers just like arrays

http://www2.research.att.com/~bs/C++0xFAQ.html#init-list

T-SQL get SELECTed value of stored procedure

there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set

ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...

if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.

RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:

CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int

SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue

this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.

OUTPUT PARAMETER
you can use an output parameter:

CREATE PROCEDURE GetMyInt
( @Param     int
 ,@OutValue  int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue 

Output parameters can only return one value, but can be any data type

RESULT SET for a result set make the procedure like:

CREATE PROCEDURE GetMyInt
( @Param     int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

use it like:

DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
    EXEC GetMyInt @Param
SELECT * FROM @ResultSet 

result sets can have many rows and many columns of any data type

How to update each dependency in package.json to the latest version?

  1. Use npm outdated to discover dependencies that are out of date.

  2. Use npm update to perform safe dependency upgrades.

  3. Use npm install @latest to upgrade to the latest major version of a package.

  4. Use npx npm-check-updates -u and npm install to upgrade all dependencies to their latest major versions.

Django development IDE

I use Komodo Edit. Check out the Open Komodo Edit.

Windows error 2 occured while loading the Java VM

Launch the installer with the following command line parameters:

LAX_VM

For example: InstallXYZ.exe LAX_VM "C:\Program Files (x86)\Java\jre6\bin\java.exe"

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

Order Bars in ggplot2 bar graph

Using scale_x_discrete (limits = ...) to specify the order of bars.

positions <- c("Goalkeeper", "Defense", "Striker")
p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)

What is the difference between 'my' and 'our' in Perl?

The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:

my variables are lexically scoped within a single block defined by {} or within the same file if not in {}s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.

our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.

Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.

Android ClassNotFoundException: Didn't find class on path

I had this problem after upgrading from version 18. After the upgrade I had the following: Project Build Target was 5.01, targetSDKVersion=21

But: Build Tools were still from Android 4.3.1 (18) What I noticed was that those apps that were deriving their activities from ActionBarActivity crashed with the above error those that did not still ran.

So the simple fix was to use the latest Android SDK Build Tools 21.1.2 instead of only those of Android SDK Build Tools 18, which seems somehow the default.

So the culprit seems the Appcompat library, which I use for Actionbar backward compability.

And a by the way: using the appcompat library I had to set/fix: $SDKInstallDIR$\Android\android-sdk\extras\android\support\v7\appcompat\project.properties target=android-21 (which was recommended in some other useful post and which has a value of 19 by default))

What's the most efficient way to test two integer ranges for overlap?

Subtracting the Minimum of the ends of the ranges from the Maximum of the beginning seems to do the trick. If the result is less than or equal to zero, we have an overlap. This visualizes it well:

enter image description here

Different between parseInt() and valueOf() in java?

The parse* variations return primitive types and the valueOf versions return Objects. I believe the valueOf versions will also use an internal reference pool to return the SAME object for a given value, not just another instance with the same internal value.

How to call a method defined in an AngularJS directive?

Just use scope.$parent to associate function called to directive function

angular.module('myApp', [])
.controller('MyCtrl',['$scope',function($scope) {

}])
.directive('mydirective',function(){
 function link(scope, el, attr){
   //use scope.$parent to associate the function called to directive function
   scope.$parent.myfunction = function directivefunction(parameter){
     //do something
}
}
return {
        link: link,
        restrict: 'E'   
      };
});

in HTML

<div ng-controller="MyCtrl">
    <mydirective></mydirective>
    <button ng-click="myfunction(parameter)">call()</button>
</div>

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

To improve the performance, you could use the Task Parallel Library (TPL). Here is a good sample: Directory file size calculation - how to make it faster?

I didn't test it, but the author says it is 3 times faster than a non-multithreaded method...

Where is Java Installed on Mac OS X?

just write /Library/Java/JavaVirtualMachines/
in Go to Folder --> Go in Finder

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In Java or JavaScript:

driver.navigate().refresh();

This should refresh page.

Select Rows with id having even number

You are not using Oracle, so you should be using the modulus operator:

SELECT * FROM Orders where OrderID % 2 = 0;

The MOD() function exists in Oracle, which is the source of your confusion.

Have a look at this SO question which discusses your problem.

java.sql.SQLException: Exhausted Resultset

This occurs typically when the stmt is reused butexpecting a different ResultSet, try creting a new stmt and executeQuery. It fixed it for me!

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I turn on .Net Framework 3.5 and 4.5 Advance Service in Control Panel->Programs and Features->Turn Windows features on or off.it work for me.

What's the proper value for a checked attribute of an HTML checkbox?

  1. checked
  2. checked=""
  3. checked="checked"

    are equivalent;


according to spec checkbox '----? checked = "checked" or "" (empty string) or empty Specifies that the element represents a selected control.---'

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

try typing the following code in anaconda prompt one by one.

this worked for me.

Source: https://anaconda.org/conda-forge/python-graphviz

conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz 

Get user's non-truncated Active Directory groups from command line

Or you could use dsquery and dsget:

dsquery user domainroot -name <userName> | dsget user -memberof

To retrieve group memberships something like this:

Tue 09/10/2013 13:17:41.65
C:\
>dsquery user domainroot -name jqpublic | dsget user -memberof
"CN=Technical Support Staff,OU=Acme,OU=Applications,DC=YourCompany,DC=com"
"CN=Technical Support Staff,OU=Contosa,OU=Applications,DC=YourCompany,DC=com"
"CN=Regional Administrators,OU=Workstation,DC=YourCompany,DC=com"

Although I can't find any evidence that I ever installed this package on my computer, you might need to install the Remote Server Administration Tools for Windows 7.

Git cli: get user info from username

Add my two cents, if you're using windows commnad line:

git config --list | findstr user.name will give username directly.

The findstr here is quite similar to grep in linux.

How to get the range of occupied cells in excel sheet

I had a very similar issue as you had. What actually worked is this:

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count;
iTotalRows = xlWorkSheet.UsedRange.Rows.Count;

//These two lines do the magic.
xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count;
iTotalRows = xlWorkSheet.UsedRange.Rows.Count;

IMHO what happens is that when you delete data from Excel, it keeps on thinking that there is data in those cells, though they are blank. When I cleared the formats, it removes the blank cells and hence returns actual counts.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This happened to me when I registered a new domain name, e.g., "new" for example.com (new.example.com). The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.

I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.

How to specify in crontab by what user to run script?

Instead of creating a crontab to run as the root user, create a crontab for the user that you want to run the script. In your case, crontab -u www-data -e will edit the crontab for the www-data user. Just put your full command in there and remove it from the root user's crontab.

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

How do you search an amazon s3 bucket?

If you're on Windows and have no time finding a nice grep alternative, a quick and dirty way would be:

aws s3 ls s3://your-bucket/folder/ --recursive > myfile.txt

and then do a quick-search in myfile.txt

The "folder" bit is optional.

P.S. if you don't have AWS CLI installed - here's a one liner using Chocolatey package manager

choco install awscli

P.P.S. If you don't have the Chocolatey package manager - get it! Your life on Windows will get 10x better. (I'm not affiliated with Chocolatey in any way, but hey, it's a must-have, really).

Call a child class method from a parent class object

Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).

I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.

http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html

The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.

UPDATE: found it here.

How can I write a byte array to a file in Java?

As of Java 1.7, there's a new way: java.nio.file.Files.write

import java.nio.file.Files;
import java.nio.file.Paths;

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);

Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:

byte[] data = Files.readAllBytes(Paths.get("source-file"));

Keep SSH session alive

I wanted a one-time solution:

ssh -o ServerAliveInterval=60 [email protected]

Stored it in an alias:

alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'

Now can connect like this:

me@MyMachine:~$ sshprod

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

How to get SQL from Hibernate Criteria API (*not* for logging)

This answer is based on user3715338's answer (with a small spelling error corrected) and mixed with Michael's answer for Hibernate 3.6 - based on the accepted answer from Brian Deterling. I then extended it (for PostgreSQL) with a couple more types replacing the questionmarks:

public static String toSql(Criteria criteria)
{
    String sql = "";
    Object[] parameters = null;
    try
    {
        CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
        SessionImpl sessionImpl = (SessionImpl) criteriaImpl.getSession();
        SessionFactoryImplementor factory = sessionImpl.getSessionFactory();
        String[] implementors = factory.getImplementors(criteriaImpl.getEntityOrClassName());
        OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister(implementors[0]);
        LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers();
        CriteriaLoader loader = new CriteriaLoader(persister, factory,
            criteriaImpl, implementors[0].toString(), loadQueryInfluencers);
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String) f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("translator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
    if (sql != null)
    {
        int fromPosition = sql.indexOf(" from ");
        sql = "\nSELECT * " + sql.substring(fromPosition);

        if (parameters != null && parameters.length > 0)
        {
            for (Object val : parameters)
            {
                String value = "%";
                if (val instanceof Boolean)
                {
                    value = ((Boolean) val) ? "1" : "0";
                }
                else if (val instanceof String)
                {
                    value = "'" + val + "'";
                }
                else if (val instanceof Number)
                {
                    value = val.toString();
                }
                else if (val instanceof Class)
                {
                    value = "'" + ((Class) val).getCanonicalName() + "'";
                }
                else if (val instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss.SSS");
                    value = "'" + sdf.format((Date) val) + "'";
                }
                else if (val instanceof Enum)
                {
                    value = "" + ((Enum) val).ordinal();
                }
                else
                {
                    value = val.toString();
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replaceAll(
        " and ", "\nand ").replaceAll(" on ", "\non ").replaceAll("<>",
        "!=").replaceAll("<", " < ").replaceAll(">", " > ");
}

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date -j -f "%Y-%m-%d" "2010-10-02" "+%s"

Batch file to map a drive when the folder name contains spaces

net use f: \\\VFServer"\HQ Publications" /persistent:yes

Note that the first quotation mark goes before the leading \ and the second goes after the end of the folder name.

How to remove close button on the jQuery UI dialog?

As shown on the official page and suggested by David:

Create a style:

.no-close .ui-dialog-titlebar-close {
    display: none;
}

Then, you can simply add the no-close class to any dialog in order to hide it's close button:

$( "#dialog" ).dialog({
    dialogClass: "no-close",
    buttons: [{
        text: "OK",
        click: function() {
            $( this ).dialog( "close" );
        }
    }]
});

What is a "method" in Python?

http://docs.python.org/2/tutorial/classes.html#method-objects

Usually, a method is called right after it is bound:

x.f()

In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:

xf = x.f
while True:
    print xf()

will continue to print hello world until the end of time.

What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used...

Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

How to impose maxlength on textArea in HTML using JavaScript

Better Solution compared to trimming the value of the textarea.

$('textarea[maxlength]').live('keypress', function(e) {
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    if (val.length > maxlength) {
        return false;
    }
});

Why should we typedef a struct so often in C?

From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):


The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s
    {
    ...
    };

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
    {
    ...
    };
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

This is good.

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    {
    ...
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

Turning Sonar off for certain code

Use //NOSONAR on the line you get warning if it is something you cannot help your code with. It works!

How to extract the substring between two markers?

import re
print re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1)

Eclipse CDT: Symbol 'cout' could not be resolved

For me it helped to enable the automated discovery in Properties -> C/C++-Build -> Discovery Options to resolve this problem.

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Get Image Height and Width as integer values?

Like this :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

RGB to hex and hex to RGB

While this answer is unlikely to fit the question perfectly it may be very useful none the less.

  1. Create any random element

var toRgb = document.createElement('div');

  1. Set any valid style to the color you want to convert

toRg.style.color = "hsl(120, 60%, 70%)";

  1. Call the style property again

> toRgb.style.color;

< "rgb(133, 225, 133)" Your color has been converted to Rgb

Works for: Hsl, Hex

Does not work for: Named colors

How to compare DateTime without time via LINQ?

I found that in my case this is the only way working: (in my application I want to remove old log entries)

 var filterDate = dtRemoveLogs.SelectedDate.Value.Date;
 var loadOp = context.Load<ApplicationLog>(context.GetApplicationLogsQuery()
              .Where(l => l.DateTime.Year <= filterDate.Year
                       && l.DateTime.Month <= filterDate.Month
                       && l.DateTime.Day <= filterDate.Day));

I don't understand why the Jon's solution is not working ....

Excel to JSON javascript code?

The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.

I took the sample from the official sample link.

Hope it may help !

function fileReader(oEvent) {
        var oFile = oEvent.target.files[0];
        var sFilename = oFile.name;

        var reader = new FileReader();
        var result = {};

        reader.onload = function (e) {
            var data = e.target.result;
            data = new Uint8Array(data);
            var workbook = XLSX.read(data, {type: 'array'});
            console.log(workbook);
            var result = {};
            workbook.SheetNames.forEach(function (sheetName) {
                var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
                if (roa.length) result[sheetName] = roa;
            });
            // see the result, caution: it works after reader event is done.
            console.log(result);
        };
        reader.readAsArrayBuffer(oFile);
}

// Add your id of "File Input" 
$('#fileUpload').change(function(ev) {
        // Do something 
        fileReader(ev);
}

Anchor links in Angularjs?

You need to only add target="_self" to your link

ex. <a href="#services" target="_self">Services</a><div id="services"></div>

java.nio.file.Path for a classpath resource

The most general solution is as follows:

interface IOConsumer<T> {
    void accept(T t) throws IOException;
}
public static void processRessource(URI uri, IOConsumer<Path> action) throws IOException {
    try {
        Path p=Paths.get(uri);
        action.accept(p);
    }
    catch(FileSystemNotFoundException ex) {
        try(FileSystem fs = FileSystems.newFileSystem(
                uri, Collections.<String,Object>emptyMap())) {
            Path p = fs.provider().getPath(uri);
            action.accept(p);
        }
    }
}

The main obstacle is to deal with the two possibilities, either, having an existing filesystem that we should use, but not close (like with file URIs or the Java 9’s module storage), or having to open and thus safely close the filesystem ourselves (like zip/jar files).

Therefore, the solution above encapsulates the actual action in an interface, handles both cases, safely closing afterwards in the second case, and works from Java 7 to Java 10. It probes whether there is already an open filesystem before opening a new one, so it also works in the case that another component of your application has already opened a filesystem for the same zip/jar file.

It can be used in all Java versions named above, e.g. to listing the contents of a package (java.lang in the example) as Paths, like this:

processRessource(Object.class.getResource("Object.class").toURI(), new IOConsumer<Path>() {
    public void accept(Path path) throws IOException {
        try(DirectoryStream<Path> ds = Files.newDirectoryStream(path.getParent())) {
            for(Path p: ds)
                System.out.println(p);
        }
    }
});

With Java 8 or newer, you can use lambda expressions or method references to represent the actual action, e.g.

processRessource(Object.class.getResource("Object.class").toURI(), path -> {
    try(Stream<Path> stream = Files.list(path.getParent())) {
        stream.forEach(System.out::println);
    }
});

to do the same.


The final release of Java 9’s module system has broken the above code example. The JRE inconsistently returns the path /java.base/java/lang/Object.class for Object.class.getResource("Object.class") whereas it should be /modules/java.base/java/lang/Object.class. This can be fixed by prepending the missing /modules/ when the parent path is reported as non-existent:

processRessource(Object.class.getResource("Object.class").toURI(), path -> {
    Path p = path.getParent();
    if(!Files.exists(p))
        p = p.resolve("/modules").resolve(p.getRoot().relativize(p));
    try(Stream<Path> stream = Files.list(p)) {
        stream.forEach(System.out::println);
    }
});

Then, it will again work with all versions and storage methods.

Difference between DOM parentNode and parentElement

Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null

Check if checkbox is checked with jQuery

All following methods are useful:

$('#checkbox').is(":checked")

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked

It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.

Can't connect to MySQL server error 111

If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

When you call figure, simply number the plot.

x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)

z = np.sin(x)
plt.figure(1)
plt.plot(x, z)

w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)

Edit: Note that you can number the plots however you want (here, starting from 0) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1 ("Matlab Style" according to the docs).

How to run a shell script at startup

In Lubuntu I had to deal with the opposite situation. Skype start running after booting and I found in ~/.config/autostart/ the file skypeforlinux.desktop. The content of the file is as follows:

[Desktop Entry]
Name=Skype for Linux
Comment=Skype Internet Telephony
Exec=/usr/bin/skypeforlinux
Icon=skypeforlinux
Terminal=false
Type=Application
StartupNotify=false
X-GNOME-Autostart-enabled=true

Deleting this file helped me.

How to find length of digits in an integer?

All math.log10 solutions will give you problems.

math.log10 is fast but gives problem when your number is greater than 999999999999997. This is because the float have too many .9s, causing the result to round up.

The solution is to use a while counter method for numbers above that threshold.

To make this even faster, create 10^16, 10^17 so on so forth and store as variables in a list. That way, it is like a table lookup.

def getIntegerPlaces(theNumber):
    if theNumber <= 999999999999997:
        return int(math.log10(theNumber)) + 1
    else:
        counter = 15
        while theNumber >= 10**counter:
            counter += 1
        return counter

ReflectionException: Class ClassName does not exist - Laravel

Check file/folder permissions

I struggled with this error today, and no amount of cache, config, autoload clears did anything to help. To add to the confusion, the error was thrown if initiated by a web request, but accessing the class in tinker worked fine.

After checking for typo's, syntax errors, and incorrect namespaces, I ended up discovering it was a file permission issue. The folder and file containing my class did not have appropriate permissions so it was throwing this error. The incorrect permission level I had was 771 (folder) and 660 (file), by changing it to 775 and 664 I was able to get it working.

My understanding of the different behaviors is that when running from the command line it was reading the file as my user (which had all the permissions it needed), but when initiated from the web it uses the "other" permission group which could do nothing.

git: can't push (unpacker error) related to permission issues

A simpler way to do this is to add a post-receive script which runs the chmod command after every push to the 'hub' repo on the server. Add the following line to hooks/post-receive inside your git folder on the server:

chmod -Rf u+w /path/to/git/repo/objects

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How to empty the content of a div

An alternative way to do it is:

var div = document.getElementById('myDiv');
while(div.firstChild)
    div.removeChild(div.firstChild);

However, using document.getElementById('myDiv').innerHTML = ""; is faster.

See: Benchmark test

N.B.

Both methods preserve the div.

How to check if spark dataframe is empty?

You can do it like:

val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
    println("empty df ")
else 
    println("normal df")

How do I view an older version of an SVN file?

Using the latest versions of Subclipse, you can actually view them without using the cmd prompt. On the file, simply right-click => Team => Switch to another branch/tag/revision. Besides the revision field, you click select, and you'll see all the versions of that file.

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Run this command :

    sudo chown -R yourUser /home/yourUser/.composer

Change language of Visual Studio 2017 RC

For having a language at Visual Studio Ui , basically the language package of that language must be installed during the installation.

You can not select a language in options -> environment -> international settings that didn't installed.

If the language that you want to select in above path is not appearing than you have to modify your visual studio by re-executing installer and selecting Language Packages tab and check your language that you want to have.

enter image description here

And than at Visual Studio toolbar just click Tools --> Options --> Environment --> International Settings and than select your language from dropdown list.

Spin or rotate an image on hover

here is the automatic spin and rotating zoom effect using css3

#obj1{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj1.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

#obj2{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj2.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

#obj6{
    float:right;
    width: 96px;
    height: 100px;
    -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
    animation: mymove 20s infinite;
    animation-delay:2s;
    background-image:url("obj6.png");
    transform: scale(1.5);
    -moz-transform: scale(1.5);
    -webkit-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5); /* IE 9 */
    margin-bottom: 70px;
}

/* Standard syntax */
@keyframes mymove {
    50% {transform: rotate(30deg);
}
<div style="width:100px; float:right; ">
    <div id="obj2"></div><br /><br /><br />
    <div id="obj6"></div><br /><br /><br />
    <div id="obj1"></div><br /><br /><br />
</div>

Here is the demo

Undo scaffolding in Rails

for first time, you can check you database migration if you have generate scaffold. you must destroy them to clean up your database

rake db:rollback

then

rails d scaffold

Responsive web design is working on desktop but not on mobile device

I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

horizontal line and right way to code it in html, css

In HTML5, the <hr> tag defines a thematic break. In HTML 4.01, the <hr> tag represents a horizontal rule.

http://www.w3schools.com/tags/tag_hr.asp

So after definition, I would prefer <hr>

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

This is due to locking of Mongodb
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart

How to disable text selection highlighting

I combined the various browser CSS select attributes with the unselectable tag required for Internet Explorer < 9.

<style>
[unselectable="on"] {
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* Internet Explorer 10+/Edge */
    user-select: none; /* Standard */
}
</style>
<div unselectable="on">Unselectable Text</div>

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

i work on a multi platform project, so i can't use _s function and i don't want pollute my code with visual studio specific code.
my solution is disable the warning 4996 on the visual studio project. go to Project -> Properties -> Configuration properties -> C/C++ -> Advanced -> Disable specific warning add the value 4996.
if you use also the mfc and/or atl library (not my case) define before include mfc _AFX_SECURE_NO_DEPRECATE and before include atl _ATL_SECURE_NO_DEPRECATE.
i use this solution across visual studio 2003 and 2005.

p.s. if you use only visual studio the secure template overloads could be a good solution.

How to center div vertically inside of absolutely positioned parent div

You may use display:table/table-cell;

_x000D_
_x000D_
.a{_x000D_
   position: absolute; _x000D_
  left: 50px; _x000D_
  top: 50px;_x000D_
  display:table;_x000D_
}_x000D_
.b{_x000D_
  text-align: left; _x000D_
  display:table-cell;_x000D_
  height: 56px;_x000D_
  vertical-align: middle;_x000D_
  background-color: pink;_x000D_
}_x000D_
.c {_x000D_
  background-color: lightblue;_x000D_
}
_x000D_
<div class="a">_x000D_
  <div  class="b">_x000D_
    <div class="c" >test</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

How to disable an input type=text?

If the data is populated from the database, you might consider not using an <input> tag to display it. Nevertheless, you can disable it right in the tag:

<input type='text' value='${magic.database.value}' disabled>

If you need to disable it with Javascript later, you can set the "disabled" attribute:

document.getElementById('theInput').disabled = true;

The reason I suggest not showing the value as an <input> is that, in my experience, it causes layout issues. If the text is long, then in an <input> the user will need to try and scroll the text, which is not something normal people would guess to do. If you just drop it into a <span> or something, you have more styling flexibility.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

How do I select an element in jQuery by using a variable for the ID?

There are two problems with your code

  1. To find an element by ID you must prefix it with a "#"
  2. You are attempting to pass a Number to the find function when a String is required (passing "#" + 5 would fix this as it would convert the 5 to a "5" first)

Anaconda version with Python 3.5

You can install any current version of Anaconda. You can then make a conda environment with your particular needs from the documentation

conda create -n tensorflowproject python=3.5 tensorflow ipython

This command has a specific version for python and when this tensorflowproject environment gets updated it will upgrade to Python 3.5999999999 but never go to 3.6 . Then you switch to your environment using either

source activate tensorflowproject

for linux/mac or

activate tensorflowproject

on windows

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

decompiling DEX into Java sourcecode

It's easy

Get these tools:

  1. dex2jar to translate dex files to jar files

  2. jd-gui to view the java files in the jar

The source code is quite readable as dex2jar makes some optimizations.

Procedure:

And here's the procedure on how to decompile:

Step 1:

Convert classes.dex in test_apk-debug.apk to test_apk-debug_dex2jar.jar

d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk
d2j-dex2jar.sh -f -o output_jar.jar dex_to_decompile.dex

Note 1: In the Windows machines all the .sh scripts are replaced by .bat scripts

Note 2: On linux/mac don't forget about sh or bash. The full command should be:

sh d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk 

Note 3: Also, remember to add execute permission to dex2jar-X.X directory e.g. sudo chmod -R +x dex2jar-2.0

dex2jar documentation

Step 2:

Open the jar in JD-GUI

The decompiled source

How can I add "href" attribute to a link dynamically using JavaScript?

document.getElementById('link-id').href = "new-href";

I know this is an old post, but here's a one-liner that might be more suitable for some folks.

Jquery how to find an Object by attribute in an Array

you should pass reference on item in grep function:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(item){
      return item.purpose == purposeName;
    });
};

Example

AngularJS open modal on button click

Hope this will help you .

Here is Html code:-

    <body>
    <div ng-controller="MyController" class="container">
      <h1>Modal example</h1>
      <button ng-click="open()" class="btn btn-primary">Test Modal</button>

      <modal title="Login form" visible="showModal">
        <form role="form">

        </form>
      </modal>
    </div>
</body>

AngularJs code:-

var mymodal = angular.module('mymodal', []);

mymodal.controller('MyController', function ($scope) {
    $scope.showModal = false;
    $scope.open = function(){
    $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ title }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

Check this--jsfiddle

How to style a select tag's option element?

This question is really multiple questions in one. They are different ways of styling something. Here are links to the questions within this question:

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

SQL MAX of multiple columns?

From SQL Server 2012 we can use IIF.

 DECLARE @Date1 DATE='2014-07-03';
 DECLARE @Date2 DATE='2014-07-04';
 DECLARE @Date3 DATE='2014-07-05';

 SELECT IIF(@Date1>@Date2,
        IIF(@Date1>@Date3,@Date1,@Date3),
        IIF(@Date2>@Date3,@Date2,@Date3)) AS MostRecentDate

Change R default library path using .libPaths in Rprofile.site fails to work

I generally try to keep all of my packages in one library, but if you want to add a library why not append the new library (which must already exist in your filesystem) to the existing library path?

.libPaths( c( .libPaths(), "~/userLibrary") )
 # obviously this would need to be a valid file directory in your OS
 # min just happened to be on a Mac that day

Or (and this will make the userLibrary the first place to put new packages):

.libPaths( c( "~/userLibrary" , .libPaths() ) )

Then I get (at least back when I wrote this originally):

> .libPaths()
[1] "/Library/Frameworks/R.framework/Versions/2.15/Resources/library"
[2] "/Users/user_name/userLibrary"  

The .libPaths function is a bit different than most other nongraphics functions. It works via side-effect. The functions Sys.getenv and Sys.setenv that report and alter the R environment variables have been split apart but .libPaths can either report or alter its target.

The information about the R startup process can be read at ?Startup help page and there is RStudio material at: https://support.rstudio.com/hc/en-us/articles/200549016-Customizing-RStudio

In your case it appears that RStudio is not respecting the Rprofile.site settings or perhaps is overriding them by reading an .Rprofile setting from one of the RStudio defaults. It should also be mentioned that the result from this operation also appends the contents of calls to .Library and .Library.site, which is further reason why an RStudio- (or any other IDE or network installed-) hosted R might exhibit different behavior.

Since Sys.getenv() returns the current system environment for the R process, you can see the library and other paths with:

Sys.getenv()[ grep("LIB|PATH", names(Sys.getenv())) ]

The two that matter for storing and accessing packages are (now different on a Linux box):

R_LIBS_SITE                          /usr/local/lib/R/site-library:/usr/lib/R/site-library:/usr/lib/R/library
R_LIBS_USER                          /home/david/R/x86_64-pc-linux-gnu-library/3.5.1/
 

Getting attributes of a class

I don't know if something similar has been made by now or not, but I made a nice attribute search function using vars(). vars() creates a dictionary of the attributes of a class you pass through it.

class Player():
    def __init__(self):
        self.name = 'Bob'
        self.age = 36
        self.gender = 'Male'

s = vars(Player())
#From this point if you want to print all the attributes, just do print(s)

#If the class has a lot of attributes and you want to be able to pick 1 to see
#run this function
def play():
    ask = input("What Attribute?>: ")
    for key, value in s.items():
        if key == ask:
            print("self.{} = {}".format(key, value))
            break
    else:
        print("Couldn't find an attribute for self.{}".format(ask))

I'm developing a pretty massive Text Adventure in Python, my Player class so far has over 100 attributes. I use this to search for specific attributes I need to see.

Determine function name from within that function (without using traceback)

Here's a future-proof approach.

Combining @CamHart's and @Yuval's suggestions with @RoshOxymoron's accepted answer has the benefit of avoiding:

  • _hidden and potentially deprecated methods
  • indexing into the stack (which could be reordered in future pythons)

So I think this plays nice with future python versions (tested on 2.7.3 and 3.3.2):

from __future__ import print_function
import inspect

def bar():
    print("my name is '{}'".format(inspect.currentframe().f_code.co_name))

How to get PID of process I've just started within java program?

In my testing all IMPL classes had the field "pid". This has worked for me:

public static int getPid(Process process) {
    try {
        Class<?> cProcessImpl = process.getClass();
        Field fPid = cProcessImpl.getDeclaredField("pid");
        if (!fPid.isAccessible()) {
            fPid.setAccessible(true);
        }
        return fPid.getInt(process);
    } catch (Exception e) {
        return -1;
    }
}

Just make sure the returned value is not -1. If it is, then parse the output of ps.

Get last dirname/filename in a file path argument in Bash

The following approach can be used to get any path of a pathname:

some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))

Output:

c
b
a

Variable used in lambda expression should be final or effectively final

In your example, you can replace the forEach with lamdba with a simple for loop and modify any variable freely. Or, probably, refactor your code so that you don't need to modify any variables. However, I'll explain for completeness what does the error mean and how to work around it.

Java 8 Language Specification, §15.27.2:

Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

Basically you cannot modify a local variable (calTz in this case) from within a lambda (or a local/anonymous class). To achieve that in Java, you have to use a mutable object and modify it (via a final variable) from the lambda. One example of a mutable object here would be an array of one element:

private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {
    TimeZone[] result = { null };
    try {
        cal.getComponents().getComponents("VTIMEZONE").forEach(component -> {
            ...
            result[0] = ...;
            ...
        }
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return result[0];
}

How to find an available port?

I have recently released a tiny library for doing just that with tests in mind. Maven dependency is:

<dependency>
    <groupId>me.alexpanov</groupId>
    <artifactId>free-port-finder</artifactId>
    <version>1.0</version>
</dependency>

Once installed, free port numbers can be obtained via:

int port = FreePortFinder.findFreeLocalPort();

Checking Value of Radio Button Group via JavaScript?

_x000D_
_x000D_
function myFunction() {_x000D_
document.getElementById("text").value='male'_x000D_
 document.getElementById("myCheck_2").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}_x000D_
function myFunction_2() {_x000D_
document.getElementById("text").value='female'_x000D_
 document.getElementById("myCheck").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck_2");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}
_x000D_
Male: <input type="checkbox" id="myCheck"  onclick="myFunction()">_x000D_
Female: <input type="checkbox" id="myCheck_2"  onclick="myFunction_2()">_x000D_
_x000D_
<input type="text" id="text" placeholder="Name">
_x000D_
_x000D_
_x000D_

What characters are forbidden in Windows and Linux directory names?

Well, if only for research purposes, then your best bet is to look at this Wikipedia entry on Filenames.

If you want to write a portable function to validate user input and create filenames based on that, the short answer is don't. Take a look at a portable module like Perl's File::Spec to have a glimpse to all the hops needed to accomplish such a "simple" task.

How do I bind a List<CustomObject> to a WPF DataGrid?

if you do not expect that your list will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource this property in WPF is usually named ItemsSource):

this.dataGrid1.ItemsSource = list;

But if you would like to replace your list with new collection instance then you should consider using databinding.

Virtual network interface in Mac OS X

What do you mean by

"but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive"

?

I can make a new interface, base it on an already existing one, then disable the existing one and the new one still works. Making a second interface does however not create a real interface (when you check with ifconfig), it will just assign a second IP to the already existing one (however, this one can be DHCP while the first one is hard coded for example).

So did I understand you right, that you want to create an interface, not bound to any real interface? How would this interface then be used? E.g. if you disconnect all WLAN and pull all network cables, where would this interface send traffic to, if you send traffic to it? Maybe your question is a bit unclear, it might help a lot if rephrase it, so it's clear what you are actually trying to do with this "virtual interface" once you have it.

As you mentioned "alias IP" in your question, this would mean an alias interface. But an alias interface is always bound to a real interface. The difference is in Linux such an interface really IS an interface (e.g. an alias interface for eth0 could be eth1), while on Mac, no real interface is created, instead a virtual interface is created, that can configured and used independently, but it is still the same interface physically and thus no new named interface is generated (you just have two interfaces, that are both in fact en0, but both can be enabled/disabled and configured independently).

Refresh Part of Page (div)

You need to do that on the client side for instance with jQuery.

Let's say you want to retrieve HTML into div with ID mydiv:

<h1>My page</h1>
<div id="mydiv">
    <h2>This div is updated</h2>
</div>

You can update this part of the page with jQuery as follows:

$.get('/api/mydiv', function(data) {
  $('#mydiv').html(data);
});

In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.

See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

Copy all the lines to clipboard

I have added the following line to my .vimrc

nnoremap <F5> :%y+<CR>

This allows me to copy all text in Vim to the clipboard by pressing F5 (in command mode).

hide/show a image in jquery

I had to do something like this just now. I ended up doing:

function newWaitImg(id) {
    var img = {
       "id" : id,
       "state" : "on",
       "hide" : function () {
           $(this.id).hide();
           this.state = "off";
       },
       "show" : function () {
           $(this.id).show();
           this.state = "on";
       },
       "toggle" : function () {
           if (this.state == "on") {
               this.hide();
           } else {
               this.show();
           }
       }
    };
};

.
.
.

var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();

How to redirect a url in NGINX

This is the top hit on Google for "nginx redirect". If you got here just wanting to redirect a single location:

location = /content/unique-page-name {
  return 301 /new-name/unique-page-name;
}

How to change the text of a label?

try this

$("label").html(your value); or $("label").text(your value);

How to increase Bootstrap Modal Width?

In your code, for the modal-dialog div, add another class, modal-lg:

<div class="modal-dialog modal-lg">

Or if you wanna centre your modal dialog, use:

.modal-ku {
  width: 750px;
  margin: auto;
}

Upgrade Node.js to the latest version on Mac OS

On macOS the homebrew recommended way is to run

brew install node
npm install -g npm@latest

Screenshot of Terminal Commands

Dots in URL causes 404 with ASP.NET mvc and IIS

MVC 5.0 Workaround.

Many of the suggested answers doesn't seem to work in MVC 5.0.

As the 404 dot problem in the last section can be solved by closing that section with a trailing slash, here's the little trick I use, clean and simple.

While keeping a convenient placeholder in your view:

@Html.ActionLink("Change your Town", "Manage", "GeoData", new { id = User.Identity.Name }, null)

add a little jquery/javascript to get the job done:

<script>
    $('a:contains("Change your Town")').on("click", function (event) {
        event.preventDefault();
        window.location.href = '@Url.Action("Manage", "GeoData", new { id = User.Identity.Name })' + "/";
    });</script>

please note the trailing slash, that is responsible for changing

http://localhost:51003/GeoData/Manage/[email protected]

into

http://localhost:51003/GeoData/Manage/[email protected]/

How to install pandas from pip on windows cmd?

If you are a windows user:
make sure you added the script(dir) path to environment variables
C:\Python34\Scripts
for more how to set path vist

Difference between Dictionary and Hashtable

Dictionary is typed (so valuetypes don't need boxing), a Hashtable isn't (so valuetypes need boxing). Hashtable has a nicer way of obtaining a value than dictionary IMHO, because it always knows the value is an object. Though if you're using .NET 3.5, it's easy to write an extension method for dictionary to get similar behavior.

If you need multiple values per key, check out my sourcecode of MultiValueDictionary here: multimap in .NET

Operator overloading in Java

No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.

For a Java-like (and JVM-based) language which does support operator overloading, you could look at Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.

Show div when radio button selected

$('input[name=test]').click(function () {
    if (this.id == "watch-me") {
        $("#show-me").show('slow');
    } else {
        $("#show-me").hide('slow');
    }
});

http://jsfiddle.net/2SsAk/2/

Location of the android sdk has not been setup in the preferences in mac os?

If you have not installed plugin for eclipse, install it first.

If the plugin is installed, setup preferences: "Eclipse">"Preferences...", in left column choose "Android"(do not expand list, just choose root element), and first preference will be "SDK Location".

int value under 10 convert to string two digit number

You can also do it this way

private static string GetPaddingSequence(int padding)
{
      StringBuilder SB = new StringBuilder();
      for (int i = 0; i < padding; i++)
      {
           SB.Append("0");
      }

      return SB.ToString();
  }

public static string FormatNumber(int number, int padding)
{
    return number.ToString(GetPaddingSequence(padding));
}

Finally call the function FormatNumber

string x = FormatNumber(1,2);

Output will be 01 which is based on your padding parameter. Increasing it will increase the number of 0s

Get real path from URI, Android KitKat new storage access framework

Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.

You could use the URI to obtain document id, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI (depending on the SD card situation).

To get document id:

// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };     

// where id is equal to             
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = getContentResolver().
                          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                          column, sel, new String[]{ id }, null);

String filePath = "";

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
    filePath = cursor.getString(columnIndex);
}   

cursor.close();

Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.

How do I add a Font Awesome icon to input field?

You can use another tag instead of input and apply FontAwesome the normal way.

instead of your input with type image you can use this:

<i class="icon-search icon-2x"></i>

quick CSS:

.icon-search {
    color:white;
    background-color:black;
}

Here is a quick fiddle: DEMO

You can style it a little better and add event functionality, to the i object, which you can do by using a <button type="submit"> object instead of i, or with javascript.

The button sollution would be something like this:

<button type="submit" class="icon-search icon-large"></button>

And the CSS:

.icon-search {
    height:32px;
    width:32px;
    border: none;
    cursor: pointer;
    color:white;
    background-color:black;
    position:relative;
}

here is my fiddle updated with the button instead of i: DEMO


Update: Using FontAwesome on any tag

The problem with FontAwsome is that its stylesheet uses :before pseudo-elements to add the icons to an element - and pseudo elements don't work/are not allowed on input elements. This is why using FontAwesome the normal way will not work with input.

But there is a solution - you can use FontAwesome as a regular font like so:

CSS:

input[type="submit"] {
    font-family: FontAwesome;
}

HTML:

<input type="submit" class="search" value="&#xf002;" />

The glyphs can be passed as values of the value attribute. The ascii codes for the individual letters/icons can be found in the FontAwesome css file, you just need to change them into a HTML ascii number like \f002 to &#xf002; and it should work.

Link to the FontAwesome ascii code (cheatsheet): fortawesome.github.io/Font-Awesome/cheatsheet

The size of the icons can be easily adjusted via font-size.

See the above example using an input element in a jsfidde:

DEMO


Update: FontAwesome 5

With FontAwesome version 5 the CSS required for this solution has changed - the font family name has changed and the font weight must be specified:

input[type="submit"] {
    font-family: "Font Awesome 5 Free"; // for the open access version
    font-size: 1.3333333333333333em;
    font-weight: 900;
}

See @WillFastie 's comment with link to updated fiddle bellow. Thanks!

Play an audio file using jQuery when a button is clicked

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var audioElement = document.createElement('audio');_x000D_
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
    _x000D_
    audioElement.addEventListener('ended', function() {_x000D_
        this.play();_x000D_
    }, false);_x000D_
    _x000D_
    audioElement.addEventListener("canplay",function(){_x000D_
        $("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
        $("#source").text("Source:" + audioElement.src);_x000D_
        $("#status").text("Status: Ready to play").css("color","green");_x000D_
    });_x000D_
    _x000D_
    audioElement.addEventListener("timeupdate",function(){_x000D_
        $("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
    });_x000D_
    _x000D_
    $('#play').click(function() {_x000D_
        audioElement.play();_x000D_
        $("#status").text("Status: Playing");_x000D_
    });_x000D_
    _x000D_
    $('#pause').click(function() {_x000D_
        audioElement.pause();_x000D_
        $("#status").text("Status: Paused");_x000D_
    });_x000D_
    _x000D_
    $('#restart').click(function() {_x000D_
        audioElement.currentTime = 0;_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
    <h2>Sound Information</h2>_x000D_
    <div id="length">Duration:</div>_x000D_
    <div id="source">Source:</div>_x000D_
    <div id="status" style="color:red;">Status: Loading</div>_x000D_
    <hr>_x000D_
    <h2>Control Buttons</h2>_x000D_
    <button id="play">Play</button>_x000D_
    <button id="pause">Pause</button>_x000D_
    <button id="restart">Restart</button>_x000D_
    <hr>_x000D_
    <h2>Playing Information</h2>_x000D_
    <div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

When to use Common Table Expression (CTE)

There are two reasons I see to use cte's.

To use a calculated value in the where clause. This seems a little cleaner to me than a derived table.

Suppose there are two tables - Questions and Answers joined together by Questions.ID = Answers.Question_Id (and quiz id)

WITH CTE AS
(
    Select Question_Text,
           (SELECT Count(*) FROM Answers A WHERE A.Question_ID = Q.ID) AS Number_Of_Answers
    FROM Questions Q
)
SELECT * FROM CTE
WHERE Number_Of_Answers > 0

Here's another example where I want to get a list of questions and answers. I want the Answers to be grouped with the questions in the results.

WITH cte AS
(
    SELECT [Quiz_ID] 
      ,[ID] AS Question_Id
      ,null AS Answer_Id
          ,[Question_Text]
          ,null AS Answer
          ,1 AS Is_Question
    FROM [Questions]

    UNION ALL

    SELECT Q.[Quiz_ID]
      ,[Question_ID]
      ,A.[ID] AS  Answer_Id
      ,Q.Question_Text
          ,[Answer]
          ,0 AS Is_Question
        FROM [Answers] A INNER JOIN [Questions] Q ON Q.Quiz_ID = A.Quiz_ID AND Q.Id = A.Question_Id
)
SELECT 
    Quiz_Id,
    Question_Id,
    Is_Question,
    (CASE WHEN Answer IS NULL THEN Question_Text ELSE Answer END) as Name
FROM cte    
GROUP BY Quiz_Id, Question_Id, Answer_id, Question_Text, Answer, Is_Question 
order by Quiz_Id, Question_Id, Is_Question Desc, Name

Search an Oracle database for tables with specific column names?

TO search a column name use the below query if you know the column name accurately:

select owner,table_name from all_tab_columns where upper(column_name) =upper('keyword');

TO search a column name if you dont know the accurate column use below:

select owner,table_name from all_tab_columns where upper(column_name) like upper('%keyword%');

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

For me, I didn't have xcode installed (on Mojave OS). I went to the App Store on my mac and downloaded it, then went back to terminal and typed git and hit enter, then it worked.

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

CR LF notepad++ removal

"View -> Show Symbol -> uncheck Show All characters" may not work if you have pending update for notepad++. So update Notepad++ and then View -> Show Symbol -> uncheck Show All characters

Hope this is helpful!

How do I use valgrind to find memory leaks?

How to Run Valgrind

Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.

Valgrind is readily usable for C/C++ code, but can even be used for other languages when configured properly (see this for Python).

To run Valgrind, pass the executable as an argument (along with any parameters to the program).

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

The flags are, in short:

  • --leak-check=full: "each individual leak will be shown in detail"
  • --show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.
  • --track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.
  • --verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.
  • --log-file: Write to a file. Useful when output exceeds terminal space.

Finally, you would like to see a Valgrind report that looks like this:

HEAP SUMMARY:
    in use at exit: 0 bytes in 0 blocks
  total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated

All heap blocks were freed -- no leaks are possible

ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I have a leak, but WHERE?

So, you have a memory leak, and Valgrind isn't saying anything meaningful. Perhaps, something like this:

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (in /home/Peri461/Documents/executable)

Let's take a look at the C code I wrote too:

#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}

Well, there were 5 bytes lost. How did it happen? The error report just says main and malloc. In a larger program, that would be seriously troublesome to hunt down. This is because of how the executable was compiled. We can actually get line-by-line details on what went wrong. Recompile your program with a debug flag (I'm using gcc here):

gcc -o executable -std=c11 -Wall main.c         # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c  # add -ggdb3 to it

Now with this debug build, Valgrind points to the exact line of code allocating the memory that got leaked! (The wording is important: it might not be exactly where your leak is, but what got leaked. The trace helps you find where.)

5 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x40053E: main (main.c:4)

Techniques for Debugging Memory Leaks & Errors

  • Make use of www.cplusplus.com! It has great documentation on C/C++ functions.
  • General advice for memory leaks:
    • Make sure your dynamically allocated memory does in fact get freed.
    • Don't allocate memory and forget to assign the pointer.
    • Don't overwrite a pointer with a new one unless the old memory is freed.
  • General advice for memory errors:
    • Access and write to addresses and indices you're sure belong to you. Memory errors are different from leaks; they're often just IndexOutOfBoundsException type problems.
    • Don't access or write to memory after freeing it.
  • Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:

    • List out the functions in your code that depend on/are dependent on the "offending" code that has the memory error. Follow the program's execution (maybe even in gdb perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.
    • Try commenting out the "offending" block of code (within reason, so your code still compiles). If the Valgrind error goes away, you've found where it is.
  • If all else fails, try looking it up. Valgrind has documentation too!

A Look at Common Leaks and Errors

Watch your pointers

60 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
   by 0x4005E4: resizeArray (main.c:12)
   by 0x40062E: main (main.c:19)

And the code:

#include <stdlib.h>
#include <stdint.h>

struct _List {
    int32_t* data;
    int32_t length;
};
typedef struct _List List;

List* resizeArray(List* array) {
    int32_t* dPtr = array->data;
    dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
    return array;
}

int main() {
    List* array = calloc(1, sizeof(List));
    array->data = calloc(10, sizeof(int32_t));
    array = resizeArray(array);

    free(array->data);
    free(array);
    return 0;
}

As a teaching assistant, I've seen this mistake often. The student makes use of a local variable and forgets to update the original pointer. The error here is noticing that realloc can actually move the allocated memory somewhere else and change the pointer's location. We then leave resizeArray without telling array->data where the array was moved to.

Invalid write

1 errors in context 1 of 1:
Invalid write of size 1
   at 0x4005CA: main (main.c:10)
 Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
   at 0x4C2B975: calloc (vg_replace_malloc.c:711)
   by 0x400593: main (main.c:5)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* alphabet = calloc(26, sizeof(char));

    for(uint8_t i = 0; i < 26; i++) {
        *(alphabet + i) = 'A' + i;
    }
    *(alphabet + 26) = '\0'; //null-terminate the string?

    free(alphabet);
    return 0;
}

Notice that Valgrind points us to the commented line of code above. The array of size 26 is indexed [0,25] which is why *(alphabet + 26) is an invalid write—it's out of bounds. An invalid write is a common result of off-by-one errors. Look at the left side of your assignment operation.

Invalid read

1 errors in context 1 of 1:
Invalid read of size 1
   at 0x400602: main (main.c:9)
 Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
   at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
   by 0x4005E1: main (main.c:6)

And the code:

#include <stdlib.h>
#include <stdint.h>

int main() {
    char* destination = calloc(27, sizeof(char));
    char* source = malloc(26 * sizeof(char));

    for(uint8_t i = 0; i < 27; i++) {
        *(destination + i) = *(source + i); //Look at the last iteration.
    }

    free(destination);
    free(source);
    return 0;
}

Valgrind points us to the commented line above. Look at the last iteration here, which is
*(destination + 26) = *(source + 26);. However, *(source + 26) is out of bounds again, similarly to the invalid write. Invalid reads are also a common result of off-by-one errors. Look at the right side of your assignment operation.


The Open Source (U/Dys)topia

How do I know when the leak is mine? How do I find my leak when I'm using someone else's code? I found a leak that isn't mine; should I do something? All are legitimate questions. First, 2 real-world examples that show 2 classes of common encounters.

Jansson: a JSON library

#include <jansson.h>
#include <stdio.h>

int main() {
    char* string = "{ \"key\": \"value\" }";

    json_error_t error;
    json_t* root = json_loads(string, 0, &error); //obtaining a pointer
    json_t* value = json_object_get(root, "key"); //obtaining a pointer
    printf("\"%s\" is the value field.\n", json_string_value(value)); //use value

    json_decref(value); //Do I free this pointer?
    json_decref(root);  //What about this one? Does the order matter?
    return 0;
}

This is a simple program: it reads a JSON string and parses it. In the making, we use library calls to do the parsing for us. Jansson makes the necessary allocations dynamically since JSON can contain nested structures of itself. However, this doesn't mean we decref or "free" the memory given to us from every function. In fact, this code I wrote above throws both an "Invalid read" and an "Invalid write". Those errors go away when you take out the decref line for value.

Why? The variable value is considered a "borrowed reference" in the Jansson API. Jansson keeps track of its memory for you, and you simply have to decref JSON structures independent of each other. The lesson here: read the documentation. Really. It's sometimes hard to understand, but they're telling you why these things happen. Instead, we have existing questions about this memory error.

SDL: a graphics and gaming library

#include "SDL2/SDL.h"

int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
        SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
        return 1;
    }

    SDL_Quit();
    return 0;
}

What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.

That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)

Answers unto the void

How do I know when the leak is mine?
It is. (99% sure, anyway)

How do I find my leak when I'm using someone else's code?
Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.

I found a leak that isn't mine; should I do something?
Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!


Further Reading

Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:

Best way to read a large file into a byte array in C#?

use this:

 bytesRead = responseStream.ReadAsync(buffer, 0, Length).Result;

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

What REALLY happens when you don't free after malloc?

You are absolutely correct in that respect. In small trivial programs where a variable must exist until the death of the program, there is no real benefit to deallocating the memory.

In fact, I had once been involved in a project where each execution of the program was very complex but relatively short-lived, and the decision was to just keep memory allocated and not destabilize the project by making mistakes deallocating it.

That being said, in most programs this is not really an option, or it can lead you to run out of memory.

Python subprocess/Popen with a modified environment

I know this has been answered for some time, but there are some points that some may want to know about using PYTHONPATH instead of PATH in their environment variable. I have outlined an explanation of running python scripts with cronjobs that deals with the modified environment in a different way (found here). Thought it would be of some good for those who, like me, needed just a bit more than this answer provided.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.

I think your best bet is to store it as a CHAR(60) as it is always 60 chars long

How to fetch the dropdown values from database and display in jsp

I made this in my code to do that

note: I am a beginner.

It is my jsp code.

<%
java.sql.Connection Conn = DBconnector.SetDBConnection(); /* make connector as you make in your code */
Statement st = null;
ResultSet rs = null;
st = Conn.createStatement();
rs = st.executeQuery("select * from department"); %>
<tr> 
    <td> 
        Student Major  : <select name ="Major">
        <%while(rs.next()){ %>
        <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
                        <%}%>           
                         </select> 
   </td> 

Copy a file from one folder to another using vbscripting

Please find the below code:

If ComboBox21.Value = "Delimited file" Then
    'Const txtFldrPath As String = "C:\Users\513090.CTS\Desktop\MACRO"      'Change to folder path containing text files
    Dim myValue2 As String
    myValue2 = ComboBox22.Value
    Dim txtFldrPath As Variant
    txtFldrPath = InputBox("Give the file path")
    'Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "LL.txt")
    Dim strLine() As String
    Dim LineIndex As Long
    Dim myValue As Variant
    On Error GoTo Errhandler
    myValue = InputBox("Give the DELIMITER")

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    While txtFldrPath <> vbNullString
        LineIndex = 0
        Close #1
        'Open txtFldrPath & "\" & CurrentFile For Input As #1
        Open txtFldrPath For Input As #1
        While Not EOF(1)
            LineIndex = LineIndex + 1
            ReDim Preserve strLine(1 To LineIndex)
            Line Input #1, strLine(LineIndex)
        Wend
        Close #1

        With ActiveWorkbook.Sheets(myValue2).Range("A1").Resize(LineIndex, 1)
            .Value = WorksheetFunction.Transpose(strLine)
            .TextToColumns Other:=True, OtherChar:=myValue
        End With

        'ActiveSheet.UsedRange.EntireColumn.AutoFit
        'ActiveSheet.Copy
        'ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xls"), xlNormal
        'ActiveWorkbook.Close False
       ' ActiveSheet.UsedRange.ClearContents

        CurrentFile = Dir
    Wend
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End If

UITableView Separator line

Set the color of the separator to be patterned with your image.

in viewDidLoad:

self.tableView.separatorColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mySeparatorImage"]];

XAMPP on Windows - Apache not starting

The most likely reason would be that something else is using port 80. (Often this can be Skype, IIS, etc.)

This tutorials shows How to Change the Apache Port in XAMPP

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

How do I disable form resizing for users?

Use the FormBorderStyle property of your Form:

this.FormBorderStyle = FormBorderStyle.FixedDialog;

Changing project port number in Visual Studio 2013

Right click the web application and select "properties"

There should be a 'Web' tab where http://localhost:XXXXX is specified - change the port number there and this will modify the configuration to use your new port number.

I usually start at 10000 and increment by 1 for each web app, to attempt to steer well clear of other applications and port numbers.

Get the item doubleclick event of listview

I'm using something like this to only trigger on ListViewItem double-click and not for example when you double-click on the header of the ListView.

private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject obj = (DependencyObject)e.OriginalSource;

    while (obj != null && obj != myListView)
    {
        if (obj.GetType() == typeof(ListViewItem))
        {
            // Do something here
            MessageBox.Show("A ListViewItem was double clicked!");

            break;
        }
        obj = VisualTreeHelper.GetParent(obj);
    }
}

python: SyntaxError: EOL while scanning string literal

In this case, three single quotations or three double quotations both will work! For example:

    """Parameters:
    ...Type something.....
    .....finishing statement"""

OR

    '''Parameters:
    ...Type something.....
    .....finishing statement'''

Background color of text in SVG

Instead of using a <text> tag, the <foreignObject> tag can be used, which allows for XHTML content with CSS.

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

How to print colored text to the terminal?

On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.

To see complete code that supports both ways, see the color console reporting code from Testoob.

ctypes example:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)

Removing Data From ElasticSearch

You can delete the index by Kibana Console:

Console Icon

To get all index:

GET /_cat/indices?v

To delete a specific index:

DELETE /INDEX_NAME_TO_DELETE

Using .htaccess to make all .html pages to run as .php files?

Running .html files as php stopped working all of a sudden in my .htaccess file.

Godaddy support had me change it to:

AddHandler application/x-httpd-lsphp .html

Check play state of AVPlayer

To get notification for reaching the end of an item (via Apple):

[[NSNotificationCenter defaultCenter] 
      addObserver:<self>
      selector:@selector(<#The selector name#>)
      name:AVPlayerItemDidPlayToEndTimeNotification 
      object:<#A player item#>];

And to track playing you can:

"track changes in the position of the playhead in an AVPlayer object" by using addPeriodicTimeObserverForInterval:queue:usingBlock: or addBoundaryTimeObserverForTimes:queue:usingBlock:.

Example is from Apple:

// Assume a property: @property (retain) id playerObserver;

Float64 durationSeconds = CMTimeGetSeconds([<#An asset#> duration]);
CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 1);
CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 1);
NSArray *times = [NSArray arrayWithObjects:[NSValue valueWithCMTime:firstThird], [NSValue valueWithCMTime:secondThird], nil];

self.playerObserver = [<#A player#> addBoundaryTimeObserverForTimes:times queue:NULL usingBlock:^{
    // Passing NULL for the queue specifies the main queue.

    NSString *timeDescription = (NSString *)CMTimeCopyDescription(NULL, [self.player currentTime]);
    NSLog(@"Passed a boundary at %@", timeDescription);
    [timeDescription release];
}];

Java, How do I get current index/key in "for each" loop

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

How to get MD5 sum of a string using python?

Have you tried using the MD5 implementation in hashlib? Note that hashing algorithms typically act on binary data rather than text data, so you may want to be careful about which character encoding is used to convert from text to binary data before hashing.

The result of a hash is also binary data - it looks like Flickr's example has then been converted into text using hex encoding. Use the hexdigest function in hashlib to get this.

JavaScript and Threads

There's no true threading in JavaScript. JavaScript being the malleable language that it is, does allow you to emulate some of it. Here is an example I came across the other day.

Simplest way to detect a pinch

My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.

HTML:

<div id="zoom_here">....</div>

JS

<script>
var dist1=0;
function start(ev) {
           if (ev.targetTouches.length == 2) {//check if two fingers touched screen
               dist1 = Math.hypot( //get rough estimate of distance between two fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);                  
           }
    
    }
    function move(ev) {
           if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
                 // Check if the two target touches are the same ones that started
               var dist2 = Math.hypot(//get rough estimate of new distance between fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);
                //alert(dist);
                if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
                  alert('zoom out');
                }
                if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
                   alert('zoom in');
                }
           }
           
    }
        document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
        document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>

Skip certain tables with mysqldump

You can use the --ignore-table option. So you could do

mysqldump -u USERNAME -pPASSWORD DATABASE --ignore-table=DATABASE.table1 > database.sql

There is no whitespace after -p (this is not a typo).

To ignore multiple tables, use this option multiple times, this is documented to work since at least version 5.0.

If you want an alternative way to ignore multiple tables you can use a script like this:

#!/bin/bash
PASSWORD=XXXXXX
HOST=XXXXXX
USER=XXXXXX
DATABASE=databasename
DB_FILE=dump.sql
EXCLUDED_TABLES=(
table1
table2
table3
table4
tableN   
)
 
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
   IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done

echo "Dump structure"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}

echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}

How do I populate a JComboBox with an ArrayList?

Check this simple code

import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;


public class FirstFrame extends JFrame{

    static JComboBox<ArrayList> mycombo;

    FirstFrame()
    {
        this.setSize(600,500);
        this.setTitle("My combo");
        this.setLayout(null);

        ArrayList<String> names=new ArrayList<String>();   
        names.add("jessy");
        names.add("albert");
        names.add("grace");
        mycombo=new JComboBox(names.toArray());
        mycombo.setBounds(60,32,200,50);
        this.add(mycombo);
        this.setVisible(true); // window visible
    }   

    public static void main(String[] args) {

        FirstFrame frame=new FirstFrame();  

    }

}

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!

Enter image description here

how to Call super constructor in Lombok

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

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

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

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

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

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

SQL Server SELECT LAST N Rows

This may not be quite the right fit to the question, but…

OFFSET clause

The OFFSET number clause enables you to skip over a number of rows and then return rows after that.

That doc link is to Postgres; I don't know if this applies to Sybase/MS SQL Server.

While loop to test if a file exists in bash

I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.

I found that if I ran cat /tmp/list.txt the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1; just before the cat /tmp/list.txt it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.

My final code:

while [ ! -f /tmp/list.txt ];
do
    sleep 1;
done;
sleep 1;
cat /tmp/list.txt;

Hope this helps save someone a frustrating half hour!

How to make grep only match if the entire line matches?

Simply specify the regexp anchors.

grep '^ABB\.log$' a.tmp

What do these three dots in React do?

This will be compiled into:

React.createElement(Modal, { ...this.props, title: "Modal heading", animation: false }, child0, child1, child2, ...)

where it gives more two properties title & animation beyond the props the host element has.

... is the ES6 operator called Spread.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

pandas read_csv and filter columns with usecols

If your csv file contains extra data, columns can be deleted from the DataFrame after import.

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        index_col=["date", "loc"], 
        usecols=["dummy", "date", "loc", "x"],
        parse_dates=["date"],
        header=0,
        names=["dummy", "date", "loc", "x"])
del df['dummy']

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

Run Command Prompt Commands

if you want to keep the cmd window open or want to use it in winform/wpf then use it like this

    string strCmdText;
//For Testing
    strCmdText= "/K ipconfig";

 System.Diagnostics.Process.Start("CMD.exe",strCmdText);

/K

Will keep the cmd window open

How do I declare an array with a custom class?

Your class:

class name {
  public:
    string first;
    string last;

  name() { }  //Default constructor.

  name(string a, string b){
    first = a;
    last = b;
  }
};

Has an explicit constructor that requires two string parameters. Classes with no constructor written explicitly get default constructors taking no parameters. Adding the explicit one stopped the compiler from generating that default constructor for you.

So, if you wish to make an array of uninitialized objects, add a default constructor to your class so the compiler knows how to create them without providing those two string parameters - see the commented line above.

Make $JAVA_HOME easily changable in Ubuntu

Put the environment variables into the global /etc/environment file:

...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...

Execute "source /etc/environment" in every shell where you want the variables to be updated:

$ source /etc/environment

Check that it works:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

Great, no logout needed.

If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

Android: Proper Way to use onBackPressed() with Toast

I just had this issue and solved it by adding the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
             // click on 'up' button in the action bar, handle it here
             return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}    

Loading basic HTML in Node.js

This would probably be some what better since you will be streaming the file(s) rather than loading it all into memory like fs.readFile.

var http = require('http');
var fs = require('fs');
var path = require('path');
var ext = /[\w\d_-]+\.[\w\d]+$/;

http.createServer(function(req, res){
    if (req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/html'});
        fs.createReadStream('index.html').pipe(res);
    } else if (ext.test(req.url)) {
        fs.exists(path.join(__dirname, req.url), function (exists) {
            if (exists) {
                res.writeHead(200, {'Content-Type': 'text/html'});
                fs.createReadStream('index.html').pipe(res);
            } else {
                res.writeHead(404, {'Content-Type': 'text/html'});
                fs.createReadStream('404.html').pipe(res);
        });
    } else {
        //  add a RESTful service
    }
}).listen(8000);

smooth scroll to top

You can simply use

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("gotoTop").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("gotoTop").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#gotoTop {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#gotoTop:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

Angular 2 two way binding using ngModel is not working

In my case, I was missing a "name" attribute on my input element.