Programs & Examples On #Uidevice

UIDevice uniqueIdentifier deprecated - What to do now?

From iOS 6 onwards, we have NSUUID class which complies RFC4122

Apple Link : apple_ref for NSUUID

Notepad++ incrementally replace


Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!

stackoverflow Find/Replace but Increment Value

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

How to view user privileges using windows cmd?

I'd start with:

secedit /export /areas USER_RIGHTS /cfg OUTFILE.CFG

Then examine the line for the relevant privilege. However, the problem now is that the accounts are listed as SIDs, not usernames.

Creating a textarea with auto-resize

This code works for pasting and select delete also.

_x000D_
_x000D_
onKeyPressTextMessage = function(){_x000D_
   var textArea = event.currentTarget;_x000D_
     textArea.style.height = 'auto';_x000D_
     textArea.style.height = textArea.scrollHeight + 'px';_x000D_
};
_x000D_
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>
_x000D_
_x000D_
_x000D_

Here is the JSFiddle

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Creating Dynamic button with click event in JavaScript

Firstly, you need to change this line:

element.setAttribute("onclick", alert("blabla"));

To something like this:

element.setAttribute("onclick", function() { alert("blabla"); });

Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

What is (functional) reactive programming?

To me it is about 2 different meanings of symbol =:

  1. In math x = sin(t) means, that x is different name for sin(t). So writing x + y is the same thing as sin(t) + y. Functional reactive programming is like math in this respect: if you write x + y, it is computed with whatever the value of t is at the time it's used.
  2. In C-like programming languages (imperative languages), x = sin(t) is an assignment: it means that x stores the value of sin(t) taken at the time of the assignment.

Why is vertical-align:text-top; not working in CSS

The all above not work for me, I have just checked this and its work :

vertical-align: super;

 <div id="lbk_mng_rdooption" style="float: left;">
     <span class="bold" style="vertical-align: super;">View:</span>
 </div>

I know by padding or margin will work, but that is last choise I prefer.

library not found for -lPods

I had an old libPod.a file specified (probably caused by me changing targets).

Project Settings -> Build Phases -> Link Binary with Libraries

Usually, cocoapods would only include one library, such as libPods-target.a or libPods.a. I solved it by removing the duplicate.

Refresh image with a new one at the same url

Try adding a cachebreaker at the end of the url:

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.

Daylight saving time and time zone best practices

Just wanted to point out two things that seem inaccurate or at least confusing:

Always persist time according to a unified standard that is not affected by daylight savings. GMT and UTC have been mentioned by different people, though UTC seems to be mentioned most often.

For (almost) all practical computing purposes, UTC is, in fact, GMT. Unless you see a timestamps with a fractional second, you're dealing with GMT which makes this distinction redundant.

Include the local time offset as is (including DST offset) when storing timestamps.

A timestamp is always represented in GMT and thus has no offset.

How to change indentation mode in Atom?

I just had the same problem, and none of the suggestions above worked. Finally I tried unchecking "Atomic soft tabs" in the Editor Settings menu, which worked.

What are some ways of accessing Microsoft SQL Server from Linux?

FreeTDS + unixODBC or iODBC

Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine.

unixODBC has isql, iODBC has iodbctest

You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL)

I'm personally using FreeTDS + iODBC:

$more /etc/freetds/freetds.conf
[10.0.1.251]
    host = 10.0.1.251
    port = 1433
    tds version = 8.0

$ more /etc/odbc.ini
[ACCT]
Driver = /usr/local/freetds/lib/libtdsodbc.so
Description = ODBC to SQLServer via FreeTDS
Trace = No
Servername = 10.0.1.251
Database = accounts_ver8

Angular cli generate a service and include the provider in one step

Specify paths

--app
  --one
    one.module.ts
    --services

  --two
    two.module.ts
    --services

Create Service with new folder in module ONE

ng g service one/services/myNewServiceFolderName/serviceOne --module one/one

--one
  one.module.ts // service imported and added to providers.
  --services
    --myNewServiceFolderName
      serviceOne.service.ts
      serviceOne.service.spec.ts

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

Edit: The answer marked as "correct" is not correct.

It's easy to do. Try this code, swapping out "ie.jpg" with whatever picture you have handy:

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            var canvas;
            var context;
            var ga = 0.0;
            var timerId = 0;
            
            function init()
            {
                canvas = document.getElementById("myCanvas");
                context = canvas.getContext("2d");
                timerId = setInterval("fadeIn()", 100);
            }
            
            function fadeIn()
            {
                context.clearRect(0,0, canvas.width,canvas.height);
                context.globalAlpha = ga;
                var ie = new Image();
                ie.onload = function()
                {
                    context.drawImage(ie, 0, 0, 100, 100);
                };
                ie.src = "ie.jpg";
                
                ga = ga + 0.1;
                if (ga > 1.0)
                {
                    goingUp = false;
                    clearInterval(timerId);
                }
            }
        </script>
    </head>
    <body onload="init()">
        <canvas height="200" width="300" id="myCanvas"></canvas>
    </body>
</html>

The key is the globalAlpha property.

Tested with IE 9, FF 5, Safari 5, and Chrome 12 on Win7.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

Try:

Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools from an elevated PowerShell (run as Administrator).

https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#environment-setup-and-configuration

In C#, what's the difference between \n and \r\n?

It's about how the operating system recognizes line ends.

  • Windows user \r\n
  • Mac user \r
  • Linux uses \n

Morale: if you are developing for Windows, stick to \r\n. Or even better, use C# string functions to deal with strings which already consider line endings (WriteLine, and such).

"No such file or directory" error when executing a binary

Well another possible cause of this can be simple line break at end of each line and shebang line If you have been coding in windows IDE its possible that windows has added its own line break at the end of each line and when you try to run it on linux the line break cause problems

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

For me cache invalidation and restart didn't work. I removed the .idea and .gradle folders. If you do that, don't forget that things like build logs or something might go away though.

How do I get the SharedPreferences from a PreferenceActivity in Android?

If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.

Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.

String preferencesName = this.getPreferenceManager().getSharedPreferencesName();

The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.

Changing user agent on urllib2.urlopen

For urllib you can use:

from urllib import FancyURLopener

class MyOpener(FancyURLopener, object):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

myopener = MyOpener()
myopener.retrieve('https://www.google.com/search?q=test', 'useragent.html')

How to remove leading and trailing whitespace in a MySQL field?

If you need to use trim in select query, you can also use regular expressions

SELECT * FROM table_name WHERE field RLIKE ' * query-string *'

return rows with field like '      query-string   '

How to test which port MySQL is running on and whether it can be connected to?

Both URLs are incorrect - should be

jdbc:mysql://host:port/database

I thought it went without saying, but connecting to a database with Java requires a JDBC driver. You'll need the MySQL JDBC driver.

Maybe you can connect using a socket over TCP/IP. Check out the MySQL docs.

See http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

UPDATE:

I tried to telnet into MySQL (telnet ip 3306), but it doesn't work:

http://lists.mysql.com/win32/253

I think this is what you had in mind.

Pagination on a list using ng-repeat

I just made a JSFiddle that show pagination + search + order by on each column using Build with Twitter Bootstrap code: http://jsfiddle.net/SAWsA/11/

Using jquery to delete all elements with a given id

id of dom element shout be unique. Use class instead (<span class='myclass'>). To remove all span with this class:

$('.myclass').remove()

MySQL create stored procedure syntax with delimiter

Here is my code to create procedure in MySQL :

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `procedureName`(IN comId int)
BEGIN
select * from tableName 
         (add joins OR sub query as per your requirement)
         Where (where condition here)
END $$
DELIMITER ;

To call this procedure use this query :

call procedureName(); // without parameter
call procedureName(id,pid); // with parameter

Detail :

1) DEFINER : root is the user name and change it as per your username of mysql localhost is the host you can change it with ip address of the server if you are execute this query on hosting server.

Read here for more detail

How to fix warning from date() in PHP"

error_reporting(E_ALL ^ E_WARNING);

:)

You should change subject to "How to fix warning from date() in PHP"...

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

Different from text-rendering: optimizeLegibility;, it takes care of kerning problems when scaling fonts, while the last enables kerning and ligatures.

When to use dynamic vs. static libraries

For an excellent discussion of this topic have a read of this article from Sun.

It goes into all the benefits including being able to insert interposing libraries. More detail on interposing can be found in this article here.

momentJS date string add 5 days

To get an actual working example going that returns what one would expect:

var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)

What is the maximum number of edges in a directed graph with n nodes?

If the graph is not a multi graph then it is clearly n * (n - 1), as each node can at most have edges to every other node. If this is a multigraph, then there is no max limit.

Performing user authentication in Java EE / JSF using j_security_check

It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.

Why is the default value of the string type null instead of an empty string?

You could also use the following, as of C# 6.0

string myString = null;
string result = myString?.ToUpper();

The string result will be null.

Config Error: This configuration section cannot be used at this path

For Windows Server 2012 and IIS 8, the procedure is similar.

The Web Server (IIS) and Application Server should be installed, and you should also have the optional Web Server (IIS) Support under Application Server.

Windows Server 2012 and IIS 8 Requirements for MVC

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

How do I obtain the frequencies of each value in an FFT?

Your kth FFT result's frequency is 2*pi*k/N.

configuring project ':app' failed to find Build Tools revision

In my case issue was with wrong path to NDK.

If your project requires it please check it in menu File -> Project Structure -> SDK Location:

enter image description here

mysql: get record count between two date-time

select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 

Ternary operator (?:) in Bash

This is much like Vladimir's fine answer. If your "ternary" is a case of "if true, string, if false, empty", then you can simply do:

$ c="it was five"
$ b=3
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a

$ b=5
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a
it was five

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)

update package.json version automatically

To give a more up-to-date approach.

package.json

  "scripts": {
    "eslint": "eslint index.js",
    "pretest": "npm install",
    "test": "npm run eslint",
    "preversion": "npm run test",
    "version": "",
    "postversion": "git push && git push --tags && npm publish"
  }

Then you run it:

npm version minor --force -m "Some message to commit"

Which will:

  1. ... run tests ...

  2. change your package.json to a next minor version (e.g: 1.8.1 to 1.9.0)

  3. push your changes

  4. create a new git tag release and

  5. publish your npm package.

--force is to show who is the boss! Jokes aside see https://github.com/npm/npm/issues/8620

Delete first character of a string in Javascript

Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...

TL;DR : Remove first character from the string:

str = str.substring(1);

...yes it is that simple...

Removing some particular character(s):

As @Shaded suggested, just loop this while first character of your string is the "unwanted" character...

var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"

.slice() vs .substring() vs .substr()

EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)

Quote from (and more on that in) What is the difference between String.slice and String.substring?

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn´t.

Build and Install unsigned apk on device without the development server?

Please follow those steps.

Bundle your js:

if you have index.android.js in project root then run

react-native bundle --dev false --platform android --entry-file index.android.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug

if you have index.js in project root then run

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Create debug apk:

cd android/
./gradlew assembleDebug

Then You can find your apk here:

cd app/build/outputs/apk/

Check empty string in Swift?

For optional Strings how about:

if let string = string where !string.isEmpty
{
    print(string)
}

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
{
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;
}

Delete column from SQLite table

Just in case if it could help someone like me.

Based on the Official website and the Accepted answer, I made a code using C# that uses System.Data.SQLite NuGet package.

This code also preserves the Primary key and Foreign key.

CODE in C#:

void RemoveColumnFromSqlite (string tableName, string columnToRemove) {
 try {
    var mSqliteDbConnection = new SQLiteConnection ("Data Source=db_folder\\MySqliteBasedApp.db;Version=3;Page Size=1024;");
    mSqliteDbConnection.Open ();             
    // Reads all columns definitions from table
    List<string> columnDefinition = new List<string> ();
    var mSql = $"SELECT type, sql FROM sqlite_master WHERE tbl_name='{tableName}'";
    var mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    string sqlScript = "";
    using (mSqliteReader = mSqliteCommand.ExecuteReader ()) {
       while (mSqliteReader.Read ()) {
          sqlScript = mSqliteReader["sql"].ToString ();
          break;
       }
    }
    if (!string.IsNullOrEmpty (sqlScript)) {
       // Gets string within first '(' and last ')' characters
       int firstIndex = sqlScript.IndexOf ("(");
       int lastIndex = sqlScript.LastIndexOf (")");
       if (firstIndex >= 0 && lastIndex <= sqlScript.Length - 1) {
          sqlScript = sqlScript.Substring (firstIndex, lastIndex - firstIndex + 1);
       }
       string[] scriptParts = sqlScript.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
       foreach (string s in scriptParts) {
          if (!s.Contains (columnToRemove)) {
             columnDefinition.Add (s);
          }
       }
    }
    string columnDefinitionString = string.Join (",", columnDefinition);
    // Reads all columns from table
    List<string> columns = new List<string> ();
    mSql = $"PRAGMA table_info({tableName})";
    mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    using (mSqliteReader = mSqliteCommand.ExecuteReader ()) {
       while (mSqliteReader.Read ()) columns.Add (mSqliteReader["name"].ToString ());
    }
    columns.Remove (columnToRemove);
    string columnString = string.Join (",", columns);
    mSql = "PRAGMA foreign_keys=OFF";
    mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    int n = mSqliteCommand.ExecuteNonQuery ();
    // Removes a column from the table
    using (SQLiteTransaction tr = mSqliteDbConnection.BeginTransaction ()) {
       using (SQLiteCommand cmd = mSqliteDbConnection.CreateCommand ()) {
          cmd.Transaction = tr;
          string query = $"CREATE TEMPORARY TABLE {tableName}_backup {columnDefinitionString}";
          cmd.CommandText = query;
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"INSERT INTO {tableName}_backup SELECT {columnString} FROM {tableName}";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"DROP TABLE {tableName}";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"CREATE TABLE {tableName} {columnDefinitionString}";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"INSERT INTO {tableName} SELECT {columnString} FROM {tableName}_backup;";
          cmd.ExecuteNonQuery ();
          cmd.CommandText = $"DROP TABLE {tableName}_backup";
          cmd.ExecuteNonQuery ();
       }
       tr.Commit ();
    }
    mSql = "PRAGMA foreign_keys=ON";
    mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
    n = mSqliteCommand.ExecuteNonQuery ();
 } catch (Exception ex) {
    HandleExceptions (ex);
 }
}

How to Make A Chevron Arrow Using CSS?

I needed to change an input to an arrow in my project. Below is final work.

_x000D_
_x000D_
#in_submit {_x000D_
  background-color: white;_x000D_
  border-left: #B4C8E9;_x000D_
  border-top: #B4C8E9;_x000D_
  border-right: 3px solid black;_x000D_
  border-bottom: 3px solid black;_x000D_
  width: 15px;_x000D_
  height: 15px;_x000D_
  transform: rotate(-45deg);_x000D_
  margin-top: 4px;_x000D_
  margin-left: 4px;_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<input id="in_submit" type="button" class="convert_btn">
_x000D_
_x000D_
_x000D_

Here Fiddle

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

force css grid container to fill full screen of device

Two important CSS properties to set for full height pages are these:

  1. Allow the body to grow as high as the content in it requires.

    html { height: 100%; }
    
  2. Force the body not to get any smaller than then window height.

    body { min-height: 100%; }
    

What you do with your gird is irrelevant as long as you use fractions or percentages you should be safe in all cases.

Have a look at this common dashboard layout.

'dependencies.dependency.version' is missing error, but version is managed in parent

Make sure the value in the child's project/parent/version node matches its parent's project/version value

explicit casting from super class to subclass

Elaborating the answer given by Michael Berry.

Dog d = (Dog)Animal; //Compiles but fails at runtime

Here you are saying to the compiler "Trust me. I know d is really referring to a Dog object" although it's not. Remember compiler is forced to trust us when we do a downcast.

The compiler only knows about the declared reference type. The JVM at runtime knows what the object really is.

So when the JVM at the runtime figures out that the Dog d is actually referring to an Animal and not a Dog object it says. Hey... you lied to the compiler and throws a big fat ClassCastException.

So if you are downcasting you should use instanceof test to avoid screwing up.

if (animal instanceof Dog) { Dog dog = (Dog) animal; }

Now a question comes to our mind. Why the hell compiler is allowing the downcast when eventually it is going to throw a java.lang.ClassCastException?

The answer is that all the compiler can do is verify that the two types are in the same inheritance tree, so depending on whatever code might have come before the downcast, it's possible that animal is of type dog.

The compiler must allow things that might possible work at runtime.

Consider the following code snipet:

public static void main(String[] args) 
{   
    Dog d = getMeAnAnimal();// ERROR: Type mismatch: cannot convert Animal to Dog
    Dog d = (Dog)getMeAnAnimal(); // Downcast works fine. No ClassCastException :)
    d.eat();

}

private static Animal getMeAnAnimal()
{
    Animal animal = new Dog();
    return animal;
}

However, if the compiler is sure that the cast would not possible work, compilation will fail. I.E. If you try to cast objects in different inheritance hierarchies

String s = (String)d; // ERROR : cannot cast for Dog to String

Unlike downcasting, upcasting works implicitly because when you upcast you are implicitly restricting the number of method you can invoke, as opposite to downcasting, which implies that later on, you might want to invoke a more specific method.

Dog d = new Dog(); Animal animal1 = d; // Works fine with no explicit cast Animal animal2 = (Animal) d; // Works fine with n explicit cast

Both of the above upcast will work fine without any exception because a Dog IS-A Animal, anithing an Animal can do, a dog can do. But it's not true vica-versa.

Decompile an APK, modify it and then recompile it

  1. First download the dex2jar tool from Following link http://code.google.com/p/dex2jar/downloads/list

  2. Extract the file it create dex2jar folder

  3. Now you pick your apk file and change its extension .apk to .zip after changing extension it seems to be zip file then extract this zip file you found classes.dex file

  4. Now pick classes.dex file and put it into dex2jar folder

  5. Now open cmd window and type the path of dex2jar folder

  6. Now type the command dex2jar.bat classes.dex and press Enter

  7. Now Open the dex2jar folder you found classes_dex2jar.jar file

  8. Next you download the java decompiler tool from the following link http://java.decompiler.free.fr/?q=jdgui

  9. Last Step Open the file classes_dex2jar.jar in java decompiler tool now you can see apk code

Model summary in pytorch

Simplest to remember (not as pretty as Keras):

print(model)

This also work:

repr(model)

If you just want the number of parameters:

sum([param.nelement() for param in model.parameters()])

From: Is there similar pytorch function as model.summary() as keras? (forum.PyTorch.org)

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

How to add key,value pair to dictionary?

Add a key, value pair to dictionary

aDict = {}
aDict[key] = value

What do you mean by dynamic addition.

node.js + mysql connection pooling

You will find this wrapper usefull :)

var pool = mysql.createPool(config.db);

exports.connection = {
    query: function () {
        var queryArgs = Array.prototype.slice.call(arguments),
            events = [],
            eventNameIndex = {};

        pool.getConnection(function (err, conn) {
            if (err) {
                if (eventNameIndex.error) {
                    eventNameIndex.error();
                }
            }
            if (conn) { 
                var q = conn.query.apply(conn, queryArgs);
                q.on('end', function () {
                    conn.release();
                });

                events.forEach(function (args) {
                    q.on.apply(q, args);
                });
            }
        });

        return {
            on: function (eventName, callback) {
                events.push(Array.prototype.slice.call(arguments));
                eventNameIndex[eventName] = callback;
                return this;
            }
        };
    }
};

Require it, use it like this:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
          .on('result', function (row) {
            setData(row);
          })
          .on('error', function (err) {
            callback({error: true, err: err});
          });

illegal character in path

I usualy would enter the path like this ....

FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe"); 

Did you register the @ at the beginning of the string? ;-)

"message failed to fetch from registry" while trying to install any module

This problem is due to the https protocol, which is why the other solution works (by switching to the non-secure protocol).

For me, the best solution was to compile the latest version of node, which includes npm

apt-get purge nodejs npm
git clone https://github.com/nodejs/node ~/local/node
cd ~/local/node
./configure
make
make install

How to find a Java Memory Leak

Checkout this screen cast about finding memory leaks with JProfiler. It's visual explanation of @Dima Malenko Answer.

Note: Though JProfiler is not freeware, But Trial version can deal with current situation.

Bootstrap: Open Another Modal in Modal

I went kind of a different route all together, I decided to "De-Nest" them. Maybe someone will find this handy...

var $m1 = $('#Modal1');
var $innermodal = $m1.find(".modal");     //get reference to nested modal
$m1.after($innermodal);                  // snatch it out of inner modal and put it after.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

in my case

my platform is x64

the Dll library(sdk) and the redistributable package is x64

so

  1. in the solution explorer navigate to your project

  2. open Properties

  3. change the Platform target from AnyCPU to x64

enter image description here

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

  1. Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

  2. Using a double quote password: "your password" <-- this one also solved my problem.

Why is there no ForEach extension method on IEnumerable?

I would like to expand on Aku's answer.

If you want to call a method for the sole purpose of it's side-effect without iterating the whole enumerable first you can use this:

private static IEnumerable<T> ForEach<T>(IEnumerable<T> xs, Action<T> f) {
    foreach (var x in xs) {
        f(x); yield return x;
    }
}

How to link to a <div> on another page?

Create an anchor:

<a name="anchor" id="anchor"></a> 

then link to it:

<a href="http://server/page.html#anchor">Link text</a>

Android; Check if file exists without creating a new one

When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().

Sample code (in an Activity):

public void onCreate(...) {
    super.onCreate(...);
    String[] files = fileList();
    for (String file : files) {
        if (file.equals(myFileName)) {
            //file exits
        }
    }
}

How do I add 1 day to an NSDate?

A working Swift 3+ implementation based on highmaintenance's answer and vikingosegundo's comment. This Date extension also has additional options to change year, month and time:

extension Date {

    /// Returns a Date with the specified amount of components added to the one it is called with
    func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
        let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
        return Calendar.current.date(byAdding: components, to: self)
    }

    /// Returns a Date with the specified amount of components subtracted from the one it is called with
    func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
        return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
    }

}

Usage for only adding a day as asked by OP would then be:

let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)

How to shift a column in Pandas DataFrame

This is how I do it:

df_ext = pd.DataFrame(index=pd.date_range(df.index[-1], periods=8, closed='right'))
df2 = pd.concat([df, df_ext], axis=0, sort=True)
df2["forecast"] = df2["some column"].shift(7)

Basically I am generating an empty dataframe with the desired index and then just concatenate them together. But I would really like to see this as a standard feature in pandas so I have proposed an enhancement to pandas.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I solved this by assigning a ref to the component and then checking if the ref exists before setting the state:

myMethod(){
  if (this.refs.myRef) 
   this.setState({myVar: true});
}

render() {
  return (
    <div ref="myRef">
      {this.state.myVar}
    </div>
  );
}

And lately, since I am using mostly functional components, I am using this pattern:

const Component = () => {
  const ref = React.useRef(null);
  const [count, setCount] = React.useState(0);

  const increment = () => {
    setTimeout(() => { // usually fetching API data here
      if (ref.current !== null) {
        setCount((count) => count + 1);
      }
    }, 100);
  };

  return (
    <button onClick={increment} ref={ref}>
      Async Increment {count}
    </button>
  );
};

Make browser window blink in task Bar

AFAIK, there is no good way to do this with consistency. I was writing an IE only web-based IM client. We ended up using window.focus(), which works most of the time. Sometimes it will actually cause the window to steal focus from the foreground app, which can be really annoying.

Visual Studio Code open tab in new window

You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.

I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.

Is it ok to use `any?` to check if an array is not empty?

any? isn't the same as not empty? in some cases.

>> [nil, 1].any?
=> true
>> [nil, nil].any?
=> false

From the documentation:

If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil).

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I ran into this in IntelliJ and fixed it by adding the following to my pom:

<!-- logging dependencies -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
        <exclusions>
            <exclusion>
                <!-- Defined below -->
                <artifactId>slf4j-api</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

Install tkinter for Python

For python 3.7 on ubuntu I had to use sudo apt-get install python3.7-tk to make it work

Share link on Google+

No, you cannot. Google Plus has been discontinued. Clicking any link for any answer here brings me to this text:

Google+ is no longer available for consumer (personal) and brand accounts

From all of us on the Google+ team,

thank you for making Google+ such a special place.

There is one section that reads that the product is continued for "G Suite," but as of Feb., 2020, the chat and social service listed for G Suite is Hangouts, not Google+.

The format https://plus.google.com/share?url=YOUR_URL_HERE was documented at https://developers.google.com/+/web/share/, but this documentation has since been removed, probably because no part of Google+ continues in development. If you are feeling nostalgic, you can see what the API used to say with an Archive.org link.

Implements vs extends: When to use? What's the difference?

A class can only "implement" an interface. A class only "extends" a class. Likewise, an interface can extend another interface.

A class can only extend one other class. A class can implement several interfaces.

If instead you are more interested in knowing when to use abstract classes and interfaces, refer to this thread: Interface vs Abstract Class (general OO)

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

How do I enable --enable-soap in php on linux?

Getting SOAP working usually does not require compiling PHP from source. I would recommend trying that only as a last option.

For good measure, check to see what your phpinfo says, if anything, about SOAP extensions:

$ php -i | grep -i soap

to ensure that it is the PHP extension that is missing.

Assuming you do not see anything about SOAP in the phpinfo, see what PHP SOAP packages might be available to you.

In Ubuntu/Debian you can search with:

$ apt-cache search php | grep -i soap

or in RHEL/Fedora you can search with:

$ yum search php | grep -i soap

There are usually two PHP SOAP packages available to you, usually php-soap and php-nusoap. php-soap is typically what you get with configuring PHP with --enable-soap.

In Ubuntu/Debian you can install with:

$ sudo apt-get install php-soap

Or in RHEL/Fedora you can install with:

$ sudo yum install php-soap

After the installation, you might need to place an ini file and restart Apache.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

The same thing happened to me. Here is what I did in order to get it successfully installed. I downloaded KB2999226 update from Microsofts website here: https://www.microsoft.com/en-us/download/details.aspx?id=49093

After installing this package, I started the installation process again. That worked for me.

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

Getting SyntaxError for print with keyword argument end=' '

Compatible with both Python 2 & 3:

sys.stdout.write('mytext')

Compatible with only Python 2

print 'mytext',

Compatible with only Python 3

print('mytext', end='')

The following untracked working tree files would be overwritten by merge, but I don't care

The only commands that worked for me were:

git fetch --all
git reset --hard origin/{{your branch name}}

Setting timezone to UTC (0) in PHP

List of entire available timezones.

$time_zones = array (
  0 => 'Africa/Abidjan',
  1 => 'Africa/Accra',
  2 => 'Africa/Addis_Ababa',
  3 => 'Africa/Algiers',
  4 => 'Africa/Asmara',
  5 => 'Africa/Asmera',
  6 => 'Africa/Bamako',
  7 => 'Africa/Bangui',
  8 => 'Africa/Banjul',
  9 => 'Africa/Bissau',
  10 => 'Africa/Blantyre',
  11 => 'Africa/Brazzaville',
  12 => 'Africa/Bujumbura',
  13 => 'Africa/Cairo',
  14 => 'Africa/Casablanca',
  15 => 'Africa/Ceuta',
  16 => 'Africa/Conakry',
  17 => 'Africa/Dakar',
  18 => 'Africa/Dar_es_Salaam',
  19 => 'Africa/Djibouti',
  20 => 'Africa/Douala',
  21 => 'Africa/El_Aaiun',
  22 => 'Africa/Freetown',
  23 => 'Africa/Gaborone',
  24 => 'Africa/Harare',
  25 => 'Africa/Johannesburg',
  26 => 'Africa/Juba',
  27 => 'Africa/Kampala',
  28 => 'Africa/Khartoum',
  29 => 'Africa/Kigali',
  30 => 'Africa/Kinshasa',
  31 => 'Africa/Lagos',
  32 => 'Africa/Libreville',
  33 => 'Africa/Lome',
  34 => 'Africa/Luanda',
  35 => 'Africa/Lubumbashi',
  36 => 'Africa/Lusaka',
  37 => 'Africa/Malabo',
  38 => 'Africa/Maputo',
  39 => 'Africa/Maseru',
  40 => 'Africa/Mbabane',
  41 => 'Africa/Mogadishu',
  42 => 'Africa/Monrovia',
  43 => 'Africa/Nairobi',
  44 => 'Africa/Ndjamena',
  45 => 'Africa/Niamey',
  46 => 'Africa/Nouakchott',
  47 => 'Africa/Ouagadougou',
  48 => 'Africa/Porto-Novo',
  49 => 'Africa/Sao_Tome',
  50 => 'Africa/Timbuktu',
  51 => 'Africa/Tripoli',
  52 => 'Africa/Tunis',
  53 => 'Africa/Windhoek',
  54 => 'America/Adak',
  55 => 'America/Anchorage',
  56 => 'America/Anguilla',
  57 => 'America/Antigua',
  58 => 'America/Araguaina',
  59 => 'America/Argentina/Buenos_Aires',
  60 => 'America/Argentina/Catamarca',
  61 => 'America/Argentina/ComodRivadavia',
  62 => 'America/Argentina/Cordoba',
  63 => 'America/Argentina/Jujuy',
  64 => 'America/Argentina/La_Rioja',
  65 => 'America/Argentina/Mendoza',
  66 => 'America/Argentina/Rio_Gallegos',
  67 => 'America/Argentina/Salta',
  68 => 'America/Argentina/San_Juan',
  69 => 'America/Argentina/San_Luis',
  70 => 'America/Argentina/Tucuman',
  71 => 'America/Argentina/Ushuaia',
  72 => 'America/Aruba',
  73 => 'America/Asuncion',
  74 => 'America/Atikokan',
  75 => 'America/Atka',
  76 => 'America/Bahia',
  77 => 'America/Bahia_Banderas',
  78 => 'America/Barbados',
  79 => 'America/Belem',
  80 => 'America/Belize',
  81 => 'America/Blanc-Sablon',
  82 => 'America/Boa_Vista',
  83 => 'America/Bogota',
  84 => 'America/Boise',
  85 => 'America/Buenos_Aires',
  86 => 'America/Cambridge_Bay',
  87 => 'America/Campo_Grande',
  88 => 'America/Cancun',
  89 => 'America/Caracas',
  90 => 'America/Catamarca',
  91 => 'America/Cayenne',
  92 => 'America/Cayman',
  93 => 'America/Chicago',
  94 => 'America/Chihuahua',
  95 => 'America/Coral_Harbour',
  96 => 'America/Cordoba',
  97 => 'America/Costa_Rica',
  98 => 'America/Creston',
  99 => 'America/Cuiaba',
  100 => 'America/Curacao',
  101 => 'America/Danmarkshavn',
  102 => 'America/Dawson',
  103 => 'America/Dawson_Creek',
  104 => 'America/Denver',
  105 => 'America/Detroit',
  106 => 'America/Dominica',
  107 => 'America/Edmonton',
  108 => 'America/Eirunepe',
  109 => 'America/El_Salvador',
  110 => 'America/Ensenada',
  111 => 'America/Fort_Nelson',
  112 => 'America/Fort_Wayne',
  113 => 'America/Fortaleza',
  114 => 'America/Glace_Bay',
  115 => 'America/Godthab',
  116 => 'America/Goose_Bay',
  117 => 'America/Grand_Turk',
  118 => 'America/Grenada',
  119 => 'America/Guadeloupe',
  120 => 'America/Guatemala',
  121 => 'America/Guayaquil',
  122 => 'America/Guyana',
  123 => 'America/Halifax',
  124 => 'America/Havana',
  125 => 'America/Hermosillo',
  126 => 'America/Indiana/Indianapolis',
  127 => 'America/Indiana/Knox',
  128 => 'America/Indiana/Marengo',
  129 => 'America/Indiana/Petersburg',
  130 => 'America/Indiana/Tell_City',
  131 => 'America/Indiana/Vevay',
  132 => 'America/Indiana/Vincennes',
  133 => 'America/Indiana/Winamac',
  134 => 'America/Indianapolis',
  135 => 'America/Inuvik',
  136 => 'America/Iqaluit',
  137 => 'America/Jamaica',
  138 => 'America/Jujuy',
  139 => 'America/Juneau',
  140 => 'America/Kentucky/Louisville',
  141 => 'America/Kentucky/Monticello',
  142 => 'America/Knox_IN',
  143 => 'America/Kralendijk',
  144 => 'America/La_Paz',
  145 => 'America/Lima',
  146 => 'America/Los_Angeles',
  147 => 'America/Louisville',
  148 => 'America/Lower_Princes',
  149 => 'America/Maceio',
  150 => 'America/Managua',
  151 => 'America/Manaus',
  152 => 'America/Marigot',
  153 => 'America/Martinique',
  154 => 'America/Matamoros',
  155 => 'America/Mazatlan',
  156 => 'America/Mendoza',
  157 => 'America/Menominee',
  158 => 'America/Merida',
  159 => 'America/Metlakatla',
  160 => 'America/Mexico_City',
  161 => 'America/Miquelon',
  162 => 'America/Moncton',
  163 => 'America/Monterrey',
  164 => 'America/Montevideo',
  165 => 'America/Montreal',
  166 => 'America/Montserrat',
  167 => 'America/Nassau',
  168 => 'America/New_York',
  169 => 'America/Nipigon',
  170 => 'America/Nome',
  171 => 'America/Noronha',
  172 => 'America/North_Dakota/Beulah',
  173 => 'America/North_Dakota/Center',
  174 => 'America/North_Dakota/New_Salem',
  175 => 'America/Ojinaga',
  176 => 'America/Panama',
  177 => 'America/Pangnirtung',
  178 => 'America/Paramaribo',
  179 => 'America/Phoenix',
  180 => 'America/Port-au-Prince',
  181 => 'America/Port_of_Spain',
  182 => 'America/Porto_Acre',
  183 => 'America/Porto_Velho',
  184 => 'America/Puerto_Rico',
  185 => 'America/Rainy_River',
  186 => 'America/Rankin_Inlet',
  187 => 'America/Recife',
  188 => 'America/Regina',
  189 => 'America/Resolute',
  190 => 'America/Rio_Branco',
  191 => 'America/Rosario',
  192 => 'America/Santa_Isabel',
  193 => 'America/Santarem',
  194 => 'America/Santiago',
  195 => 'America/Santo_Domingo',
  196 => 'America/Sao_Paulo',
  197 => 'America/Scoresbysund',
  198 => 'America/Shiprock',
  199 => 'America/Sitka',
  200 => 'America/St_Barthelemy',
  201 => 'America/St_Johns',
  202 => 'America/St_Kitts',
  203 => 'America/St_Lucia',
  204 => 'America/St_Thomas',
  205 => 'America/St_Vincent',
  206 => 'America/Swift_Current',
  207 => 'America/Tegucigalpa',
  208 => 'America/Thule',
  209 => 'America/Thunder_Bay',
  210 => 'America/Tijuana',
  211 => 'America/Toronto',
  212 => 'America/Tortola',
  213 => 'America/Vancouver',
  214 => 'America/Virgin',
  215 => 'America/Whitehorse',
  216 => 'America/Winnipeg',
  217 => 'America/Yakutat',
  218 => 'America/Yellowknife',
  219 => 'Antarctica/Casey',
  220 => 'Antarctica/Davis',
  221 => 'Antarctica/DumontDUrville',
  222 => 'Antarctica/Macquarie',
  223 => 'Antarctica/Mawson',
  224 => 'Antarctica/McMurdo',
  225 => 'Antarctica/Palmer',
  226 => 'Antarctica/Rothera',
  227 => 'Antarctica/South_Pole',
  228 => 'Antarctica/Syowa',
  229 => 'Antarctica/Troll',
  230 => 'Antarctica/Vostok',
  231 => 'Arctic/Longyearbyen',
  232 => 'Asia/Aden',
  233 => 'Asia/Almaty',
  234 => 'Asia/Amman',
  235 => 'Asia/Anadyr',
  236 => 'Asia/Aqtau',
  237 => 'Asia/Aqtobe',
  238 => 'Asia/Ashgabat',
  239 => 'Asia/Ashkhabad',
  240 => 'Asia/Baghdad',
  241 => 'Asia/Bahrain',
  242 => 'Asia/Baku',
  243 => 'Asia/Bangkok',
  244 => 'Asia/Beirut',
  245 => 'Asia/Bishkek',
  246 => 'Asia/Brunei',
  247 => 'Asia/Calcutta',
  248 => 'Asia/Chita',
  249 => 'Asia/Choibalsan',
  250 => 'Asia/Chongqing',
  251 => 'Asia/Chungking',
  252 => 'Asia/Colombo',
  253 => 'Asia/Dacca',
  254 => 'Asia/Damascus',
  255 => 'Asia/Dhaka',
  256 => 'Asia/Dili',
  257 => 'Asia/Dubai',
  258 => 'Asia/Dushanbe',
  259 => 'Asia/Gaza',
  260 => 'Asia/Harbin',
  261 => 'Asia/Hebron',
  262 => 'Asia/Ho_Chi_Minh',
  263 => 'Asia/Hong_Kong',
  264 => 'Asia/Hovd',
  265 => 'Asia/Irkutsk',
  266 => 'Asia/Istanbul',
  267 => 'Asia/Jakarta',
  268 => 'Asia/Jayapura',
  269 => 'Asia/Jerusalem',
  270 => 'Asia/Kabul',
  271 => 'Asia/Kamchatka',
  272 => 'Asia/Karachi',
  273 => 'Asia/Kashgar',
  274 => 'Asia/Kathmandu',
  275 => 'Asia/Katmandu',
  276 => 'Asia/Khandyga',
  277 => 'Asia/Kolkata',
  278 => 'Asia/Krasnoyarsk',
  279 => 'Asia/Kuala_Lumpur',
  280 => 'Asia/Kuching',
  281 => 'Asia/Kuwait',
  282 => 'Asia/Macao',
  283 => 'Asia/Macau',
  284 => 'Asia/Magadan',
  285 => 'Asia/Makassar',
  286 => 'Asia/Manila',
  287 => 'Asia/Muscat',
  288 => 'Asia/Nicosia',
  289 => 'Asia/Novokuznetsk',
  290 => 'Asia/Novosibirsk',
  291 => 'Asia/Omsk',
  292 => 'Asia/Oral',
  293 => 'Asia/Phnom_Penh',
  294 => 'Asia/Pontianak',
  295 => 'Asia/Pyongyang',
  296 => 'Asia/Qatar',
  297 => 'Asia/Qyzylorda',
  298 => 'Asia/Rangoon',
  299 => 'Asia/Riyadh',
  300 => 'Asia/Saigon',
  301 => 'Asia/Sakhalin',
  302 => 'Asia/Samarkand',
  303 => 'Asia/Seoul',
  304 => 'Asia/Shanghai',
  305 => 'Asia/Singapore',
  306 => 'Asia/Srednekolymsk',
  307 => 'Asia/Taipei',
  308 => 'Asia/Tashkent',
  309 => 'Asia/Tbilisi',
  310 => 'Asia/Tehran',
  311 => 'Asia/Tel_Aviv',
  312 => 'Asia/Thimbu',
  313 => 'Asia/Thimphu',
  314 => 'Asia/Tokyo',
  315 => 'Asia/Ujung_Pandang',
  316 => 'Asia/Ulaanbaatar',
  317 => 'Asia/Ulan_Bator',
  318 => 'Asia/Urumqi',
  319 => 'Asia/Ust-Nera',
  320 => 'Asia/Vientiane',
  321 => 'Asia/Vladivostok',
  322 => 'Asia/Yakutsk',
  323 => 'Asia/Yekaterinburg',
  324 => 'Asia/Yerevan',
  325 => 'Atlantic/Azores',
  326 => 'Atlantic/Bermuda',
  327 => 'Atlantic/Canary',
  328 => 'Atlantic/Cape_Verde',
  329 => 'Atlantic/Faeroe',
  330 => 'Atlantic/Faroe',
  331 => 'Atlantic/Jan_Mayen',
  332 => 'Atlantic/Madeira',
  333 => 'Atlantic/Reykjavik',
  334 => 'Atlantic/South_Georgia',
  335 => 'Atlantic/St_Helena',
  336 => 'Atlantic/Stanley',
  337 => 'Australia/ACT',
  338 => 'Australia/Adelaide',
  339 => 'Australia/Brisbane',
  340 => 'Australia/Broken_Hill',
  341 => 'Australia/Canberra',
  342 => 'Australia/Currie',
  343 => 'Australia/Darwin',
  344 => 'Australia/Eucla',
  345 => 'Australia/Hobart',
  346 => 'Australia/LHI',
  347 => 'Australia/Lindeman',
  348 => 'Australia/Lord_Howe',
  349 => 'Australia/Melbourne',
  350 => 'Australia/North',
  351 => 'Australia/NSW',
  352 => 'Australia/Perth',
  353 => 'Australia/Queensland',
  354 => 'Australia/South',
  355 => 'Australia/Sydney',
  356 => 'Australia/Tasmania',
  357 => 'Australia/Victoria',
  358 => 'Australia/West',
  359 => 'Australia/Yancowinna',
  360 => 'Europe/Amsterdam',
  361 => 'Europe/Andorra',
  362 => 'Europe/Athens',
  363 => 'Europe/Belfast',
  364 => 'Europe/Belgrade',
  365 => 'Europe/Berlin',
  366 => 'Europe/Bratislava',
  367 => 'Europe/Brussels',
  368 => 'Europe/Bucharest',
  369 => 'Europe/Budapest',
  370 => 'Europe/Busingen',
  371 => 'Europe/Chisinau',
  372 => 'Europe/Copenhagen',
  373 => 'Europe/Dublin',
  374 => 'Europe/Gibraltar',
  375 => 'Europe/Guernsey',
  376 => 'Europe/Helsinki',
  377 => 'Europe/Isle_of_Man',
  378 => 'Europe/Istanbul',
  379 => 'Europe/Jersey',
  380 => 'Europe/Kaliningrad',
  381 => 'Europe/Kiev',
  382 => 'Europe/Lisbon',
  383 => 'Europe/Ljubljana',
  384 => 'Europe/London',
  385 => 'Europe/Luxembourg',
  386 => 'Europe/Madrid',
  387 => 'Europe/Malta',
  388 => 'Europe/Mariehamn',
  389 => 'Europe/Minsk',
  390 => 'Europe/Monaco',
  391 => 'Europe/Moscow',
  392 => 'Europe/Nicosia',
  393 => 'Europe/Oslo',
  394 => 'Europe/Paris',
  395 => 'Europe/Podgorica',
  396 => 'Europe/Prague',
  397 => 'Europe/Riga',
  398 => 'Europe/Rome',
  399 => 'Europe/Samara',
  400 => 'Europe/San_Marino',
  401 => 'Europe/Sarajevo',
  402 => 'Europe/Simferopol',
  403 => 'Europe/Skopje',
  404 => 'Europe/Sofia',
  405 => 'Europe/Stockholm',
  406 => 'Europe/Tallinn',
  407 => 'Europe/Tirane',
  408 => 'Europe/Tiraspol',
  409 => 'Europe/Uzhgorod',
  410 => 'Europe/Vaduz',
  411 => 'Europe/Vatican',
  412 => 'Europe/Vienna',
  413 => 'Europe/Vilnius',
  414 => 'Europe/Volgograd',
  415 => 'Europe/Warsaw',
  416 => 'Europe/Zagreb',
  417 => 'Europe/Zaporozhye',
  418 => 'Europe/Zurich',
  419 => 'Indian/Antananarivo',
  420 => 'Indian/Chagos',
  421 => 'Indian/Christmas',
  422 => 'Indian/Cocos',
  423 => 'Indian/Comoro',
  424 => 'Indian/Kerguelen',
  425 => 'Indian/Mahe',
  426 => 'Indian/Maldives',
  427 => 'Indian/Mauritius',
  428 => 'Indian/Mayotte',
  429 => 'Indian/Reunion',
  430 => 'Pacific/Apia',
  431 => 'Pacific/Auckland',
  432 => 'Pacific/Bougainville',
  433 => 'Pacific/Chatham',
  434 => 'Pacific/Chuuk',
  435 => 'Pacific/Easter',
  436 => 'Pacific/Efate',
  437 => 'Pacific/Enderbury',
  438 => 'Pacific/Fakaofo',
  439 => 'Pacific/Fiji',
  440 => 'Pacific/Funafuti',
  441 => 'Pacific/Galapagos',
  442 => 'Pacific/Gambier',
  443 => 'Pacific/Guadalcanal',
  444 => 'Pacific/Guam',
  445 => 'Pacific/Honolulu',
  446 => 'Pacific/Johnston',
  447 => 'Pacific/Kiritimati',
  448 => 'Pacific/Kosrae',
  449 => 'Pacific/Kwajalein',
  450 => 'Pacific/Majuro',
  451 => 'Pacific/Marquesas',
  452 => 'Pacific/Midway',
  453 => 'Pacific/Nauru',
  454 => 'Pacific/Niue',
  455 => 'Pacific/Norfolk',
  456 => 'Pacific/Noumea',
  457 => 'Pacific/Pago_Pago',
  458 => 'Pacific/Palau',
  459 => 'Pacific/Pitcairn',
  460 => 'Pacific/Pohnpei',
  461 => 'Pacific/Ponape',
  462 => 'Pacific/Port_Moresby',
  463 => 'Pacific/Rarotonga',
  464 => 'Pacific/Saipan',
  465 => 'Pacific/Samoa',
  466 => 'Pacific/Tahiti',
  467 => 'Pacific/Tarawa',
  468 => 'Pacific/Tongatapu',
  469 => 'Pacific/Truk',
  470 => 'Pacific/Wake',
  471 => 'Pacific/Wallis',
  472 => 'Pacific/Yap',
  473 => 'Brazil/Acre',
  474 => 'Brazil/DeNoronha',
  475 => 'Brazil/East',
  476 => 'Brazil/West',
  477 => 'Canada/Atlantic',
  478 => 'Canada/Central',
  479 => 'Canada/East-Saskatchewan',
  480 => 'Canada/Eastern',
  481 => 'Canada/Mountain',
  482 => 'Canada/Newfoundland',
  483 => 'Canada/Pacific',
  484 => 'Canada/Saskatchewan',
  485 => 'Canada/Yukon',
  486 => 'CET',
  487 => 'Chile/Continental',
  488 => 'Chile/EasterIsland',
  489 => 'CST6CDT',
  490 => 'Cuba',
  491 => 'EET',
  492 => 'Egypt',
  493 => 'Eire',
  494 => 'EST',
  495 => 'EST5EDT',
  496 => 'Etc/GMT',
  497 => 'Etc/GMT+0',
  498 => 'Etc/GMT+1',
  499 => 'Etc/GMT+10',
  500 => 'Etc/GMT+11',
  501 => 'Etc/GMT+12',
  502 => 'Etc/GMT+2',
  503 => 'Etc/GMT+3',
  504 => 'Etc/GMT+4',
  505 => 'Etc/GMT+5',
  506 => 'Etc/GMT+6',
  507 => 'Etc/GMT+7',
  508 => 'Etc/GMT+8',
  509 => 'Etc/GMT+9',
  510 => 'Etc/GMT-0',
  511 => 'Etc/GMT-1',
  512 => 'Etc/GMT-10',
  513 => 'Etc/GMT-11',
  514 => 'Etc/GMT-12',
  515 => 'Etc/GMT-13',
  516 => 'Etc/GMT-14',
  517 => 'Etc/GMT-2',
  518 => 'Etc/GMT-3',
  519 => 'Etc/GMT-4',
  520 => 'Etc/GMT-5',
  521 => 'Etc/GMT-6',
  522 => 'Etc/GMT-7',
  523 => 'Etc/GMT-8',
  524 => 'Etc/GMT-9',
  525 => 'Etc/GMT0',
  526 => 'Etc/Greenwich',
  527 => 'Etc/UCT',
  528 => 'Etc/Universal',
  529 => 'Etc/UTC',
  530 => 'Etc/Zulu',
  531 => 'Factory',
  532 => 'GB',
  533 => 'GB-Eire',
  534 => 'GMT',
  535 => 'GMT+0',
  536 => 'GMT-0',
  537 => 'GMT0',
  538 => 'Greenwich',
  539 => 'Hongkong',
  540 => 'HST',
  541 => 'Iceland',
  542 => 'Iran',
  543 => 'Israel',
  544 => 'Jamaica',
  545 => 'Japan',
  546 => 'Kwajalein',
  547 => 'Libya',
  548 => 'MET',
  549 => 'Mexico/BajaNorte',
  550 => 'Mexico/BajaSur',
  551 => 'Mexico/General',
  552 => 'MST',
  553 => 'MST7MDT',
  554 => 'Navajo',
  555 => 'NZ',
  556 => 'NZ-CHAT',
  557 => 'Poland',
  558 => 'Portugal',
  559 => 'PRC',
  560 => 'PST8PDT',
  561 => 'ROC',
  562 => 'ROK',
  563 => 'Singapore',
  564 => 'Turkey',
  565 => 'UCT',
  566 => 'Universal',
  567 => 'US/Alaska',
  568 => 'US/Aleutian',
  569 => 'US/Arizona',
  570 => 'US/Central',
  571 => 'US/East-Indiana',
  572 => 'US/Eastern',
  573 => 'US/Hawaii',
  574 => 'US/Indiana-Starke',
  575 => 'US/Michigan',
  576 => 'US/Mountain',
  577 => 'US/Pacific',
  578 => 'US/Pacific-New',
  579 => 'US/Samoa',
  580 => 'UTC',
  581 => 'W-SU',
  582 => 'WET',
  583 => 'Zulu',
)

Regex match text between tags

/<b>(.*?)<\/b>/g

Regular expression visualization

Add g (global) flag after:

/<b>(.*?)<\/b>/g.exec(str)
             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

AJAX Mailchimp signup form integration

For anyone looking for a solution on a modern stack:

import jsonp from 'jsonp';
import queryString from 'query-string';

// formData being an object with your form data like:
// { EMAIL: '[email protected]' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How to show current user name in a cell?

Based on the instructions at the link below, do the following.

In VBA insert a new module and paste in this code:

Public Function UserName()
    UserName = Environ$("UserName")
End Function

Call the function using the formula:

=Username()

Based on instructions at:

https://support.office.com/en-us/article/Create-Custom-Functions-in-Excel-2007-2f06c10b-3622-40d6-a1b2-b6748ae8231f

What is a "callback" in C and how are they implemented?

A callback in C is a function that is provided to another function to "call back to" at some point when the other function is doing its task.

There are two ways that a callback is used: synchronous callback and asynchronous callback. A synchronous callback is provided to another function which is going to do some task and then return to the caller with the task completed. An asynchronous callback is provided to another function which is going to start a task and then return to the caller with the task possibly not completed.

A synchronous callback is typically used to provide a delegate to another function to which the other function delegates some step of the task. Classic examples of this delegation are the functions bsearch() and qsort() from the C Standard Library. Both of these functions take a callback which is used during the task the function is providing so that the type of the data being searched, in the case of bsearch(), or sorted, in the case of qsort(), does not need to be known by the function being used.

For instance here is a small sample program with bsearch() using different comparison functions, synchronous callbacks. By allowing us to delegate the data comparison to a callback function, the bsearch() function allows us to decide at run time what kind of comparison we want to use. This is synchronous because when the bsearch() function returns the task is complete.

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

typedef struct {
    int iValue;
    int kValue;
    char label[6];
} MyData;

int cmpMyData_iValue (MyData *item1, MyData *item2)
{
    if (item1->iValue < item2->iValue) return -1;
    if (item1->iValue > item2->iValue) return 1;
    return 0;
}

int cmpMyData_kValue (MyData *item1, MyData *item2)
{
    if (item1->kValue < item2->kValue) return -1;
    if (item1->kValue > item2->kValue) return 1;
    return 0;
}

int cmpMyData_label (MyData *item1, MyData *item2)
{
    return strcmp (item1->label, item2->label);
}

void bsearch_results (MyData *srch, MyData *found)
{
        if (found) {
            printf ("found - iValue = %d, kValue = %d, label = %s\n", found->iValue, found->kValue, found->label);
        } else {
            printf ("item not found, iValue = %d, kValue = %d, label = %s\n", srch->iValue, srch->kValue, srch->label);
        }
}

int main ()
{
    MyData dataList[256] = {0};

    {
        int i;
        for (i = 0; i < 20; i++) {
            dataList[i].iValue = i + 100;
            dataList[i].kValue = i + 1000;
            sprintf (dataList[i].label, "%2.2d", i + 10);
        }
    }

//  ... some code then we do a search
    {
        MyData srchItem = { 105, 1018, "13"};
        MyData *foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_iValue );

        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_kValue );
        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_label );
        bsearch_results (&srchItem, foundItem);
    }
}

An asynchronous callback is different in that when the called function to which we provide a callback returns, the task may not be completed. This type of callback is often used with asynchronous I/O in which an I/O operation is started and then when it is completed, the callback is invoked.

In the following program we create a socket to listen for TCP connection requests and when a request is received, the function doing the listening then invokes the callback function provided. This simple application can be exercised by running it in one window while using the telnet utility or a web browser to attempt to connect in another window.

I lifted most of the WinSock code from the example Microsoft provides with the accept() function at https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx

This application starts a listen() on the local host, 127.0.0.1, using port 8282 so you could use either telnet 127.0.0.1 8282 or http://127.0.0.1:8282/.

This sample application was created as a console application with Visual Studio 2017 Community Edition and it is using the Microsoft WinSock version of sockets. For a Linux application the WinSock functions would need to be replaced with the Linux alternatives and the Windows threads library would use pthreads instead.

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

#include <Windows.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

// function for the thread we are going to start up with _beginthreadex().
// this function/thread will create a listen server waiting for a TCP
// connection request to come into the designated port.
// _stdcall modifier required by _beginthreadex().
int _stdcall ioThread(void (*pOutput)())
{
    //----------------------
    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed with error: %ld\n", iResult);
        return 1;
    }
    //----------------------
    // Create a SOCKET for listening for
    // incoming connection requests.
    SOCKET ListenSocket;
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    struct sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(8282);

    if (bind(ListenSocket, (SOCKADDR *)& service, sizeof(service)) == SOCKET_ERROR) {
        printf("bind failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Listen for incoming connection requests.
    // on the created socket
    if (listen(ListenSocket, 1) == SOCKET_ERROR) {
        printf("listen failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Create a SOCKET for accepting incoming requests.
    SOCKET AcceptSocket;
    printf("Waiting for client to connect...\n");

    //----------------------
    // Accept the connection.
    AcceptSocket = accept(ListenSocket, NULL, NULL);
    if (AcceptSocket == INVALID_SOCKET) {
        printf("accept failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    else
        pOutput ();   // we have a connection request so do the callback

    // No longer need server socket
    closesocket(ListenSocket);

    WSACleanup();
    return 0;
}

// our callback which is invoked whenever a connection is made.
void printOut(void)
{
    printf("connection received.\n");
}

#include <process.h>

int main()
{
     // start up our listen server and provide a callback
    _beginthreadex(NULL, 0, ioThread, printOut, 0, NULL);
    // do other things while waiting for a connection. In this case
    // just sleep for a while.
    Sleep(30000);
}

pytest cannot import module while python can

I had the same problem but for another reason than the ones mentioned:

I had py.test installed globally, while the packages were installed in a virtual environment.

The solution was to install pytest in the virtual environment. (In case your shell hashes executables, as Bash does, use hash -r, or use the full path to py.test)

Rotate label text in seaborn factorplot

If anyone wonders how to this for clustermap CorrGrids (part of a given seaborn example):

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")

# Load the datset of correlations between cortical brain networks
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(12, 9))

# Draw the heatmap using seaborn
g=sns.clustermap(corrmat, vmax=.8, square=True)
rotation = 90 
for i, ax in enumerate(g.fig.axes):   ## getting all axes of the fig object
     ax.set_xticklabels(ax.get_xticklabels(), rotation = rotation)


g.fig.show()

How to Troubleshoot Intermittent SQL Timeout Errors

Since I do troubleshooting everyday as a part of my job, here is what I would like to do:

  1. Since it's SQL Server 2008 R2, you can run SQLDiag which comes as a part of the product. You can refer books online for more details. In brief, capture Server Side trace and blocker script.

  2. Once trace is captured, look for "Attention" event. That would be the spid which has received the error. If you filter by SPID, you would see RPC:Completed event before "Attention". Check the time over there. Is that time 30 seconds? If yes, then client waited for 30 second to get response from SQL and got "timed out" [This is client setting as SQL would never stop and connection]

  3. Now, check if the query which was running really should take 30 seconds?

  4. If yes then tune the query or increase the timeout setting from the client.

  5. If no then this query must be waiting for some resources (blocked)

  6. At this point go back to Blocker Script and check the time frame when "Attention" came

Above is assuming that issue is with SQL Server not network related!

How to enable loglevel debug on Apache2 server

You need to use LogLevel rewrite:trace3 to your httpd.conf in newer version http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================
// BASE SETUP

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Logger
app.use(morgan('dev'));

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 
        res.send(200);
    else 
        next();
}

// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------


// =================================================
// ROUTES FOR OUR API

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");


// ======================================================
// REGISTER OUR ROUTES with app

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

app.use(allowCrossDomain);

// -------------------------------------------------------------
//  STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================
// START THE SERVER

var port = process.env.PORT || 8080;        // set our port
app.listen(port);
console.log('API Active on port ' + port);

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

I was also faced by the posted issue when I used python 2.7. It is working very fine with python 3.4

To make it work in python 2.7 I have added the __metaclass__ = type attribute at the top of my program and it worked.

__metaclass__ : It eases the transition from old-style classes and new-style classes.

byte[] to file in Java

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}

Fundamental difference between Hashing and Encryption algorithms

Cryptography deals with numbers and strings. Basically every digital thing in the entire universe are numbers. When I say numbers, its 0 & 1. You know what they are, binary. The images you see on screen, the music that you listen through your earphone, everything are binaries. But our ears and eyes will not understand binaries right? Only brain could understand that, and even if it could understand binaries, it can’t enjoy binaries. So we convert the binaries to human understandable formats such as mp3,jpg,etc. Let’s term the process as Encoding. It’s two way process and can be easily decoded back to its original form.

Hashing

Hashing is another cryptography technique in which a data once converted to some other form can never be recovered back. In Layman’s term, there is no process called de-hashing. There are many hash functions to do the job such as sha-512, md5 and so on.

If the original value cannot be recovered, then where do we use this? Passwords! When you set up a password for your mobile or PC, a hash of your password is created and stored in a secure place. When you make a login attempt next time, the entered string is again hashed with the same algorithm (hash function) and the output is matched with the stored value. If it’s the same, you get logged in. Otherwise you are thrown out.

Credits: wikimedia By applying hash to the password, we can ensure that an attacker will never get our password even if he steal the stored password file. The attacker will have the hash of the password. He can probably find a list of most commonly used passwords and apply sha-512 to each of it and compare it with the value in his hand. It is called the dictionary attack. But how long would he do this? If your password is random enough, do you think this method of cracking would work? All the passwords in the databases of Facebook, Google and Amazon are hashed, or at least they are supposed to be hashed.

Then there is Encryption

Encryption lies in between hashing and encoding. Encoding is a two way process and should not be used to provide security. Encryption is also a two way process, but original data can be retrieved if and only if the encryption key is known. If you don’t know how encryption works, don’t worry, we will discuss the basics here. That would be enough to understand the basics of SSL. So, there are two types of Encryption namely Symmetric and Asymmetric encryption.

Symmetric Key Encryption

I am trying to keep things as simple as I could. So, let’s understand the symmetric encryption by means of a shift algorithm. This algorithm is used to encrypt alphabets by shifting the letters to either left or right. Let’s take a string CRYPTO and consider a number +3. Then, the encrypted format of CRYPTO will be FUBSWR. That means each letter is shifted to right by 3 places. Here, the word CRYPTO is called Plaintext, the output FUBSWR is called the Ciphertext, the value +3 is called the Encryption key (symmetric key) and the whole process is a cipher. This is one of the oldest and basic symmetric key encryption algorithm and its first usage was reported during the time of Julius Caesar. So, it was named after him and it is the famous Caesar Cipher. Anyone who knows the encryption key and can apply the reverse of Caesar’s algorithm and retrieve the original Plaintext. Hence it is called a Symmetric Encryption.

Asymmetric Key Encryption

We know that, in Symmetric encryption same key is used for both encryption and decryption. Once that key is stolen, all the data is gone. That’s a huge risk and we need more complex technique. In 1976, Whitfield Diffie and Martin Hellman first published the concept of Asymmetric encryption and the algorithm was known as Diffie–Hellman key exchange. Then in 1978, Ron Rivest, Adi Shamir and Leonard Adleman of MIT published the RSA algorithm. These can be considered as the foundation of Asymmetric cryptography.

As compared to Symmetric encryption, in Asymmetric encryption, there will be two keys instead of one. One is called the Public key, and the other one is the Private key. Theoretically, during initiation we can generate the Public-Private key pair to our machine. Private key should be kept in a safe place and it should never be shared with anyone. Public key, as the name indicates, can be shared with anyone who wish to send encrypted text to you. Now, those who have your public key can encrypt the secret data with it. If the key pair were generated using RSA algorithm, then they should use the same algorithm while encrypting the data. Usually the algorithm will be specified in the public key. The encrypted data can only be decrypted with the private key which is owned by you.

Source: SSL/TLS for dummies part 1 : Ciphersuite, Hashing,Encryption | WST (https://www.wst.space/ssl-part1-ciphersuite-hashing-encryption/)

What's in an Eclipse .classpath/.project file?

Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.

The .project file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)

The .classpath file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings directory inside the project); the .classpath file is just one of them. Specifically, the .classpath file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).

Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath file portability.

How to get names of classes inside a jar file?

Mac OS: On Terminal:

vim <your jar location>

after jar gets opened, press / and pass your class name and hit enter

Usage of the backtick character (`) in JavaScript

ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.

let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };

let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
  "<p>I am " + person.age + " old</p>\n" +
  "<strong>\"" + person.greeting + "\" is what I usually say</strong>";

let newHtmlStr =
 `<p>My name is ${person.name},</p>
  <p>I am ${person.age} old</p>
  <p>"${person.greeting}" is what I usually say</strong>`;

console.log(usualHtmlStr);
console.log(newHtmlStr);

As you can see, we used the ` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..} are parsed and evaluated inline immediately.

One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:

var Actor = {"name": "RajiniKanth"};

var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log(text);
// Now is the time for all good men like RajiniKanth
// to come to the aid of their
// country!

Interpolated Expressions

Any valid expression is allowed to appear inside ${..} in an interpolated string literal, including function calls, inline function expression calls, and even other interpolated string literals!

function upper(s) {
  return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper("warm")} welcome
to all of you ${upper(`${who}s`)}!`;
console.log(text);
// A very WARM welcome
// to all of you READERS!

Here, the inner `${who}s` interpolated string literal was a little bit nicer convenience for us when combining the who variable with the "s" string, as opposed to who + "s". Also to keep an note is an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way:

function foo(str) {
  var name = "foo";
  console.log(str);
}
function bar() {
  var name = "bar";
  foo(`Hello from ${name}!`);
}
var name = "global";
bar(); // "Hello from bar!"

Using the template literal for the HTML is definitely more readable by reducing the annoyance.

The plain old way:

'<div class="' + className + '">' +
  '<p>' + content + '</p>' +
  '<a href="' + link + '">Let\'s go</a>'
'</div>';

With ECMAScript 6:

`<div class="${className}">
  <p>${content}</p>
  <a href="${link}">Let's go</a>
</div>`
  • Your string can span multiple lines.
  • You don't have to escape quotation characters.
  • You can avoid groupings like: '">'
  • You don't have to use the plus operator.

Tagged Template Literals

We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.

function myTaggedLiteral(strings) {
  console.log(strings);
}

myTaggedLiteral`test`; //["test"]

function myTaggedLiteral(strings, value, value2) {
  console.log(strings, value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5

We can use the spread operator here to pass multiple values. The first argument—we called it strings—is an array of all the plain strings (the stuff between any interpolated expressions).

We then gather up all subsequent arguments into an array called values using the ... gather/rest operator, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2, etc.).

function myTaggedLiteral(strings, ...values) {
  console.log(strings);
  console.log(values);
}

let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5

The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal is like a processing step after the interpolations are evaluated, but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating reusable templates.

const Actor = {
  name: "RajiniKanth",
  store: "Landmark"
}

const ActorTemplate = templater`<article>
  <h3>${'name'} is a Actor</h3>
  <p>You can find his movies at ${'store'}.</p>

</article>`;

function templater(strings, ...keys) {
  return function(data) {
    let temp = strings.slice();
    keys.forEach((key, i) => {
      temp[i] = temp[i] + data[key];
    });
    return temp.join('');
  }
};

const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);

Raw Strings

Our tag functions receive a first argument we called strings, which is an array. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw property, like this:

function showraw(strings, ...values) {
  console.log(strings);
  console.log(strings.raw);
}
showraw`Hello\nWorld`;

As you can see, the raw version of the string preserves the escaped \n sequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..). It simply passes through the raw versions of the strings:

console.log(`Hello\nWorld`);
/* "Hello
World" */

console.log(String.raw`Hello\nWorld`);
// "Hello\nWorld"

ALTER TABLE, set null in not null column, PostgreSQL 9.1

ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;

More details in the manual: http://www.postgresql.org/docs/9.1/static/sql-altertable.html

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

  1. Where I work we have 2 Sprints to an Iteration. The Iteration demo is before the business stakeholders that don't want to meet after every Sprint, but that is our interpretation of the terminology. Some places may have the terms having equally meaning, I'm just pointing out that where I work they aren't the same thing.

  2. No, sprints can have varying lengths. Where I work we had a half a Sprint to align our Sprints with the Iterations that others in the project from another department were using.

How to use sed/grep to extract text between two words?

You can use two s commands

$ echo "Here is a String" | sed 's/.*Here//; s/String.*//'
 is a 

Also works

$ echo "Here is a StringHere is a String" | sed 's/.*Here//; s/String.*//'
 is a

$ echo "Here is a StringHere is a StringHere is a StringHere is a String" | sed 's/.*Here//; s/String.*//'
 is a 

Angular ui-grid dynamically calculate height of the grid

I like Tony approach. It works, but I decided to implement in different way. Here my comments:

1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.

By the way, ui-if was removed. Now you have ng-if build-in.

2) I prefer to write a service like this:

angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {

var factory = {};

factory.getGridHeight = function(gridOptions) {

    var length = gridOptions.data.length;
    var rowHeight = 30; // your row height
    var headerHeight = 40; // your header height
    var filterHeight = 40; // your filter height

    return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {

    return value.replace(unit, '');
}
return factory;

});

And then in the controller write the following:

  angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {

  ...

  // Execute this when you have $scope.gridData loaded...
  $scope.gridHeight = uiGridService.getGridHeight($scope.gridData);

And at the HTML file:

  <div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>

When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.

3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.

    $scope.gridData = {
        enableSorting: true,
        multiSelect: false,  
        enableRowSelection: true,
        showFooter: false,
        enableFiltering: true,    
        enableSelectAll: false,
        enableRowHeaderSelection: false, 
        enableGridMenu: true,
        noUnselect: true,
        expandableRowTemplate: 'subGrid.html',
        expandableRowHeight: 380,   // 10 rows * 30px + 40px (header) + 40px (filters)
        onRegisterApi: function(gridApi) {

            gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
                var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
                var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));

                if (row.isExpanded)
                {
                    height += changedRowHeight;                    
                }
                else
                {
                    height -= changedRowHeight;                    
                }

                $scope.jdeNewUserConflictsGridHeight = height + 'px';
            });
        },
        columnDefs :  [
                { field: 'GridField1', name: 'GridField1', enableFiltering: true }
        ]
    }

Installing Bootstrap 3 on Rails App

I use https://github.com/yabawock/bootstrap-sass-rails

Which is pretty much straight forward install, fast gem updates and followups and quick fixes in case is needed.

How to solve javax.net.ssl.SSLHandshakeException Error?

Now I solved this issue in this way,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream; 

// Create a trust manager that does not validate certificate chains like the default 

TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
        }
};

// Install the all-trusting trust manager
try 
{
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} 
catch (Exception e) 
{
    System.out.println(e);
}

Of course this solution should only be used in scenarios, where it is not possible to install the required certifcates using keytool e.g. local testing with temporary certifcates.

jQuery - find table row containing table cell containing specific text

$(function(){
    var search = 'foo';
    $("table tr td").filter(function() {
        return $(this).text() == search;
    }).parent('tr').css('color','red');
});

Will turn the text red for rows which have a cell whose text is 'foo'.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

#case_date= 03/31/2020   

#Above is the value stored in case_date in format(mm/dd/yyyy )

demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it 
print(new_case_date)

Changing capitalization of filenames in Git

You can open the ".git" directory and then edit the "config" file. Under "[core]" set, set "ignorecase = true" and you are done ;)

Shell script not running, command not found

Try chmod u+x MigrateNshell.sh

jQuery $(this) keyword

When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

$('.class-name').on('click', (evt) => {
    $(this).hide(); // does not run a DOM query
    $('.class-name').hide() // runs a DOM query
}); 

$(this) will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

Some more information:

Web Performance with jQuery selectors

Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

Shared folder between MacOSX and Windows on Virtual Box

Edit

4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:

  • Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections 4.1 and 4.2
  • Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section 4.3

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.
  4. After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.

Hope that helps.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

How can I output leading zeros in Ruby?

If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do

str = "file_" + i.to_s.rjust(n, "0")

Finding local maxima/minima with Numpy in a 1D numpy array

In SciPy >= 0.11

import numpy as np
from scipy.signal import argrelextrema

x = np.random.random(12)

# for local maxima
argrelextrema(x, np.greater)

# for local minima
argrelextrema(x, np.less)

Produces

>>> x
array([ 0.56660112,  0.76309473,  0.69597908,  0.38260156,  0.24346445,
    0.56021785,  0.24109326,  0.41884061,  0.35461957,  0.54398472,
    0.59572658,  0.92377974])
>>> argrelextrema(x, np.greater)
(array([1, 5, 7]),)
>>> argrelextrema(x, np.less)
(array([4, 6, 8]),)

Note, these are the indices of x that are local max/min. To get the values, try:

>>> x[argrelextrema(x, np.greater)[0]]

scipy.signal also provides argrelmax and argrelmin for finding maxima and minima respectively.

C# - Create SQL Server table programmatically

You haven't mentioned the Initial catalog name in the connection string. Give your database name as Initial Catalog name.

<add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>

How to convert 1 to true or 0 to false upon model fetch

Assigning Comparison to property value

JavaScript

You could assign the comparison of the property to "1"

obj["isChecked"] = (obj["isChecked"]==="1");

This only evaluates for a String value of "1" though. Other variables evaulate to false like an actual typeof number would be false. (i.e. obj["isChecked"]=1)

If you wanted to be indiscrimate about "1" or 1, you could use:

obj["isChecked"] = (obj["isChecked"]=="1");

Example Outputs

console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false

PHP

Same concept in PHP

$obj["isChecked"] = ($obj["isChecked"] == "1");

The same operator limitations as stated above for JavaScript apply.

Double Not

The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:

JavaScript

!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false

PHP

echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...

or pdb

Compare two dates in Java

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.

Plotting multiple lines, in different colors, with pandas dataframe

Another simple way is to use the pivot function to format the data as you need first.

df.plot() does the rest

df = pd.DataFrame([
    ['red', 0, 0],
    ['red', 1, 1],
    ['red', 2, 2],
    ['red', 3, 3],
    ['red', 4, 4],
    ['red', 5, 5],
    ['red', 6, 6],
    ['red', 7, 7],
    ['red', 8, 8],
    ['red', 9, 9],
    ['blue', 0, 0],
    ['blue', 1, 1],
    ['blue', 2, 4],
    ['blue', 3, 9],
    ['blue', 4, 16],
    ['blue', 5, 25],
    ['blue', 6, 36],
    ['blue', 7, 49],
    ['blue', 8, 64],
    ['blue', 9, 81],
], columns=['color', 'x', 'y'])

df = df.pivot(index='x', columns='color', values='y')

df.plot()

result

pivot effectively turns the data into:

enter image description here

Recover from git reset --hard?

This is what I usually do if I lose some changes.

git reflog
git checkout <commit id> // now you are in where you want but you cannot push from detached branch to master
manually copy and paste changes from detached branch to master or working branch
git reset --hard HEAD // if needed
git add ... > git commit ... > git push ...

to move the pointer back to your previous commits but keeping the changes you made so far in your latest commits checkout git reset --soft dadada

What can I use for good quality code coverage for C#/.NET?

I use the version of NCover that comes with TestDriven.NET. It will allow you to easily right-click on your unit test class library, and hit Test With→Coverage, and it will pull up the report.

Error message Strict standards: Non-static method should not be called statically in php

Instead of using the instance with the scope resolution operator :: because it wasn't defined like static function.

$r=Page::getInstanceByName($page);

change it to :

$r=Page->getInstanceByName($page);

And it will work like a charm.

how to query LIST using linq

Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples

Also, you should really really really change your List into a strongly typed list (List<T>), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.

What does the "$" sign mean in jQuery or JavaScript?

The $ symbol simply invokes the jQuery library's selector functionality. So $("#Text") returns the jQuery object for the Text div which can then be modified.

How to select all records from one table that do not exist in another table?

Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises. Better is:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT ISNULL(name ,'')
     FROM table1)

How to convert a Scikit-learn dataset to a Pandas dataset?

Took me 2 hours to figure this out

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
##iris.keys()


df= pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])

df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

Get back the species for my pandas

'DataFrame' object has no attribute 'sort'

sort() was deprecated for DataFrames in favor of either:

sort() was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values() and sort_index(). It was removed from Pandas with release 0.20 (2017-05-05).

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

The best solution I could find was listening to the scroll event on the window and set the scrollTop to the previous scrollTop if the child div was visible.

prevScrollPos = 0
$(window).scroll (ev) ->
    if $('#mydiv').is(':visible')
        document.body.scrollTop = prevScrollPos
    else
        prevScrollPos = document.body.scrollTop

There is a flicker in the background of the child div if you fire a lot of scroll events, so this could be tweaked, but it is hardly noticed and it was sufficient for my use case.

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

"Parameter not valid" exception loading System.Drawing.Image

Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].

As a more obvious question: does the binary actually contain an image in a sensible format?

For example, the following (although not great code) works fine:

    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);

Resize jqGrid when browser is resized?

Auto resize:

For jQgrid 3.5+

        if (grid = $('.ui-jqgrid-btable:visible')) {
            grid.each(function(index) {
                gridId = $(this).attr('id');
                gridParentWidth = $('#gbox_' + gridId).parent().width();
                $('#' + gridId).setGridWidth(gridParentWidth);
            });
        }

For jQgrid 3.4.x:

       if (typeof $('table.scroll').setGridWidth == 'function') {
            $('table.scroll').setGridWidth(100, true); //reset when grid is wider than container (div)
            if (gridObj) {

            } else {
                $('#contentBox_content .grid_bdiv:reallyvisible').each(function(index) {
                    grid = $(this).children('table.scroll');
                    gridParentWidth = $(this).parent().width() – origami.grid.gridFromRight;
                    grid.setGridWidth(gridParentWidth, true);
                });
            }
        }

async await return Task

Adding the async keyword is just syntactic sugar to simplify the creation of a state machine. In essence, the compiler takes your code;

public async Task MethodName()
{
     return null;
}

And turns it into;

public Task MethodName()
{
     return Task.FromResult<object>(null);
}

If your code has any await keywords, the compiler must take your method and turn it into a class to represent the state machine required to execute it. At each await keyword, the state of variables and the stack will be preserved in the fields of the class, the class will add itself as a completion hook to the task you are waiting on, then return.

When that task completes, your task will be executed again. So some extra code is added to the top of the method to restore the state of variables and jump into the next slab of your code.

See What does async & await generate? for a gory example.

This process has a lot in common with the way the compiler handles iterator methods with yield statements.

Getting Index of an item in an arraylist;

Yes.you have to loop it

public int getIndex(String itemName)
{
    for (int i = 0; i < arraylist.size(); i++)
    {
        AuctionItem auction = arraylist.get(i);
        if (itemName.equals(auction.getname()))
        {
            return i;
        }
    } 

    return -1;
}

Is there a better way to do optional function parameters in JavaScript?

Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...

/**
 * Updates an object's properties with other objects' properties. All
 * additional non-falsy arguments will have their properties copied to the
 * destination object, in the order given.
 */
function extend(dest) {
  for (var i = 1, l = arguments.length; i < l; i++) {
    var src = arguments[i]
    if (!src) {
      continue
    }
    for (var property in src) {
      if (src.hasOwnProperty(property)) {
        dest[property] = src[property]
      }
    }
  }
  return dest
}

/**
 * Inherit another function's prototype without invoking the function.
 */
function inherits(child, parent) {
  var F = function() {}
  F.prototype = parent.prototype
  child.prototype = new F()
  child.prototype.constructor = child
  return child
}

...this can be made a bit nicer.

function Field(kwargs) {
  kwargs = extend({
    required: true, widget: null, label: null, initial: null,
    helpText: null, errorMessages: null
  }, kwargs)
  this.required = kwargs.required
  this.label = kwargs.label
  this.initial = kwargs.initial
  // ...and so on...
}

function CharField(kwargs) {
  kwargs = extend({
    maxLength: null, minLength: null
  }, kwargs)
  this.maxLength = kwargs.maxLength
  this.minLength = kwargs.minLength
  Field.call(this, kwargs)
}
inherits(CharField, Field)

What's nice about this method?

  • You can omit as many arguments as you like - if you only want to override the value of one argument, you can just provide that argument, instead of having to explicitly pass undefined when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.
  • When working with a constructor Function for an object which inherits from another, it's easy to accept any arguments which are required by the constructor of the Object you're inheriting from, as you don't have to name those arguments in your constructor signature, or even provide your own defaults (let the parent Object's constructor do that for you, as seen above when CharField calls Field's constructor).
  • Child objects in inheritance hierarchies can customise arguments for their parent constructor as they see fit, enforcing their own default values or ensuring that a certain value will always be used.

Simple timeout in java

Nowadays you can use

try {
    String s = CompletableFuture.supplyAsync(() -> br.readLine())
                                .get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    System.out.println("Time out has occurred");
} catch (InterruptedException | ExecutionException e) {
    // Handle
}

How to remove class from all elements jquery

You need to select the li tags contained within the .edgetoedge class. .edgetoedge only matches the one ul tag:

$(".edgetoedge li").removeClass("highlight");

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Not sure if this is an issue. Endpoint and binding both have the same name

Creating a new user and password with Ansible

If you read Ansible's manual for user module, it'll direct you to the Ansible-examples github repo for details how to use password parameter.

There you'll see that your password must be hashed.

- hosts: all
  user: root
  vars:
    # created with:
    # python -c 'import crypt; print crypt.crypt("This is my Password", "$1$SomeSalt$")'
    password: $1$SomeSalt$UqddPX3r4kH3UL5jq5/ZI.

  tasks:
    - user: name=tset password={{password}}

If your playbook or ansible command line has your password as-is in plain text, this means your password hash recorded in your shadow file is wrong. That means when you try to authenticate with your password its hash will never match.

Additionally, see Ansible FAQ regarding some nuances of password parameter and how to correctly use it.

jQuery .scrollTop(); + animation

Try this instead:

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}

pop/remove items out of a python tuple

Yes we can do it. First convert the tuple into an list, then delete the element in the list after that again convert back into tuple.

Demo:

my_tuple = (10, 20, 30, 40, 50)

# converting the tuple to the list
my_list = list(my_tuple)
print my_list  # output: [10, 20, 30, 40, 50]

# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position

# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]

# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)


print my_tuple # output: (10, 30, 40)

Thanks

Define css class in django Forms

As it turns out you can do this in form constructor (init function) or after form class was initiated. This is sometimes required if you are not writing your own form and that form is coming from somewhere else -

def some_view(request):
    add_css_to_fields = ['list','of','fields']
    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = SomeForm()

    for key in form.fields.keys():
        if key in add_css_to_fields:
            field = form.fields[key]
            css_addition = 'css_addition '
            css = field.widget.attrs.get('class', '')
            field.widget.attrs['class'] = css_addition + css_classes

    return render(request, 'template_name.html', {'form': form})

Print multiple arguments in Python

Use f-string:

print(f'Total score for {name} is {score}')

Or

Use .format:

print("Total score for {} is {}".format(name, score))

How to update attributes without validation

You can do something like:

object.attribute = value
object.save(:validate => false)

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

Check if value exists in enum in TypeScript

Type assertion is un-avoidable. Following up on

enum Vehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

I found one alternative that wasn't mentioned so thought I'd share my fix for it:

const someString: Vehicle | string = 'car';
const inEnum = (Object.values(Vehicle) as string[]).includes(someString);

I find this more truthful because we usually come in typesafe(with a string) and want to compare it to the enum; it'd be a bit reckless to typecast it to any(reason: never do this) or Vehicle(reason: likely untruthful). Instead, typecasting the Object.values() output to an array of strings is in-fact very much real.

How do I obtain a Query Execution Plan in SQL Server?

Estimated execution plan

The estimated execution plan is generated by the Optimizer without running the SQL query.

In order to get the estimated execution plan, you need to enable the SHOWPLAN_ALL setting prior to executing the query.

SET SHOWPLAN_ALL ON

Now, when executing the following SQL query:

SELECT p.id
FROM post p
WHERE EXISTS (
  SELECT 1
  FROM post_comment pc
  WHERE
    pc.post_id = p.id AND
    pc.review = 'Bingo'
)
ORDER BY p.title
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY

SQL Server will generate the following estimated execution plan:

| NodeId | Parent | LogicalOp            | EstimateRows | EstimateIO  | EstimateCPU | AvgRowSize | TotalSubtreeCost | EstimateExecutions |
|--------|--------|----------------------|--------------|-------------|-------------|------------|------------------|--------------------|
| 1      | 0      | NULL                 | 10           | NULL        | NULL        | NULL       | 0.03374284       | NULL               |
| 2      | 1      | Top                  | 10           | 0           | 3.00E-06    | 15         | 0.03374284       | 1                  |
| 4      | 2      | Distinct Sort        | 30           | 0.01126126  | 0.000504114 | 146        | 0.03373984       | 1                  |
| 5      | 4      | Inner Join           | 46.698       | 0           | 0.00017974  | 146        | 0.02197446       | 1                  |
| 6      | 5      | Clustered Index Scan | 43           | 0.004606482 | 0.0007543   | 31         | 0.005360782      | 1                  |
| 7      | 5      | Clustered Index Seek | 1            | 0.003125    | 0.0001581   | 146        | 0.0161733        | 43                 |

After running the query we are interested in getting the estimated execution plan, you need to disable the SHOWPLAN_ALL as, otherwise, the current database session will only generate estimated execution plan instead of executing the provided SQL queries.

SET SHOWPLAN_ALL OFF

SQL Server Management Studio estimated plan

In the SQL Server Management Studio application, you can easily get the estimated execution plan for any SQL query by hitting the CTRL+L key shortcut.

SQL Server Management Studio estimated plan

Actual execution plan

The actual SQL execution plan is generated by the Optimizer when running the SQL query. If the database table statistics are accurate, the actual plan should not differ significantly from the estimated one.

To get the actual execution plan on SQL Server, you need to enable the STATISTICS IO, TIME, PROFILE settings, as illustrated by the following SQL command:

SET STATISTICS IO, TIME, PROFILE ON

Now, when running the previous query, SQL Server is going to generate the following execution plan:

| Rows | Executes | NodeId | Parent | LogicalOp            | EstimateRows | EstimateIO  | EstimateCPU | AvgRowSize | TotalSubtreeCost |
|------|----------|--------|--------|----------------------|--------------|-------------|-------------|------------|------------------|
| 10   | 1        | 1      | 0      | NULL                 | 10           | NULL        | NULL        | NULL       | 0.03338978       |
| 10   | 1        | 2      | 1      | Top                  | 1.00E+01     | 0           | 3.00E-06    | 15         | 0.03338978       |
| 30   | 1        | 4      | 2      | Distinct Sort        | 30           | 0.01126126  | 0.000478783 | 146        | 0.03338679       |
| 41   | 1        | 5      | 4      | Inner Join           | 44.362       | 0           | 0.00017138  | 146        | 0.02164674       |
| 41   | 1        | 6      | 5      | Clustered Index Scan | 41           | 0.004606482 | 0.0007521   | 31         | 0.005358581      |
| 41   | 41       | 7      | 5      | Clustered Index Seek | 1            | 0.003125    | 0.0001581   | 146        | 0.0158571        |
 
SQL Server parse and compile time:
   CPU time = 8 ms, elapsed time = 8 ms.
 
(10 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'post'. Scan count 0, logical reads 116, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'post_comment'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 
(6 row(s) affected)
 
SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 1 ms.

After running the query we are interested in getting the actual execution plan, you need to disable the STATISTICS IO, TIME, PROFILE ON settings like this:

SET STATISTICS IO, TIME, PROFILE OFF

SQL Server Management Studio actual plan

In the SQL Server Management Studio application, you can easily get the estimated execution plan for any SQL query by hitting the CTRL+M key shortcut.

SQL Server Management Studio actual plan

How can I control the width of a label tag?

Using the inline-block is better because it doesn't force the remaining elements and/or controls to be drawn in a new line.

label {
  width:200px;
  display: inline-block;
}

How to Read from a Text File, Character by Character in C++

Assuming that temp is a char and textFile is a std::fstream derivative...

The syntax you're looking for is

textFile.get( temp );

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

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

The variable mean_data is a nested list, in Python accessing a nested list cannot be done by multi-dimensional slicing, i.e.: mean_data[1,2], instead one would write mean_data[1][2].

This is becausemean_data[2] is a list. Further indexing is done recursively - since mean_data[2] is a list, mean_data[2][0] is the first index of that list.

Additionally, mean_data[:][0] does not work because mean_data[:] returns mean_data.

The solution is to replace the array ,or import the original data, as follows:

mean_data = np.array(mean_data)

numpy arrays (like MATLAB arrays and unlike nested lists) support multi-dimensional slicing with tuples.

Ways to implement data versioning in MongoDB

I have used the below package for a meteor/MongoDB project, and it works well, the main advantage is that it stores history/revisions within an array in the same document, hence no need for an additional publications or middleware to access change-history. It can support a limited number of previous versions (ex. last ten versions), it also supports change-concatenation (so all changes happened within a specific period will be covered by one revision).

nicklozon/meteor-collection-revisions

Another sound option is to use Meteor Vermongo (here)

CSS text-align: center; is not centering things

You can use flex-grow: 1. The default value is 0 and it will cause the text-align: center looks like left.

https://css-tricks.com/almanac/properties/f/flex-grow/

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

Variable interpolation in the shell

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

How to apply an XSLT Stylesheet in C#

Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Load("stylesheet.xsl"); 
myXslTrans.Transform("source.xml", "result.html"); 

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don't even need a variable:

With New XslCompiledTransform()
    .Load("stylesheet.xsl")
    .Transform("source.xml", "result.html")
End With

Error:Cause: unable to find valid certification path to requested target

Switching to the smartphone network & disabling the web security tool installed on my computer solved the problem.

How to create a JSON object

You could json encode a generic object.

$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

How to PUT a json object with an array using curl

Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.

curl: (3) [globbing] nested braces not supported at pos X

This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.

As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing: curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'

Calling startActivity() from outside of an Activity?

I just want to notice that startActivity from outside an activity is valid in some android versions (between N and O-MR1) and the interesting point is that it is a bug in android source code!


This is the comment above startActivity implementation. See here.

Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is generally not allowed, except if the caller specifies the task id the activity should be launched in. A bug was existed between N and O-MR1 which allowed this to work.

Pythonic way to create a long multi-line string

In Python >= 3.6 you can use Formatted string literals (f string)

query= f'''SELECT   action.descr as "action"
    role.id as role_id,
    role.descr as role
    FROM
    public.role_action_def,
    public.role,
    public.record_def,
    public.action
    WHERE role.id = role_action_def.role_id AND
    record_def.id = role_action_def.def_id AND
    action.id = role_action_def.action_id AND
    role_action_def.account_id = {account_id} AND
    record_def.account_id = {account_id} AND
    def_id = {def_id}'''

How to show what a commit did?

This is one way I know of. With git, there always seems to be more than one way to do it.

git log -p commit1 commit2

Notice: Undefined offset: 0 in

You are asking for the value at key 0 of $votes. It is an array that does not contain that key.

The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.

If you have an array:

$votes = array('1','2','3');

We can now access:

$votes[0];
$votes[1];
$votes[2];

If we try and access:

$votes[3];

We will get the error "Notice: Undefined offset: 3"

Replacing objects in array

function getMatch(elem) {
    function action(ele, val) {
        if(ele === val){ 
            elem = arr2[i]; 
        }
    }

    for (var i = 0; i < arr2.length; i++) {
        action(elem.id, Object.values(arr2[i])[0]);
    }
    return elem;
}

var modified = arr1.map(getMatch);

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How do you access the value of an SQL count () query in a Java program

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

How you would solve it is by going to

  1. Settings

  2. Search"Network"

  3. Choose "Use IDEA general proxy settings as default Subversion"

Calculating difference between two timestamps in Oracle in milliseconds

I know that this has been exhaustively answered, but I wanted to share my FUNCTION with everyone. It gives you the option to choose if you want your answer to be in days, hours, minutes, seconds, or milliseconds. You can modify it to fit your needs.

CREATE OR REPLACE FUNCTION Return_Elapsed_Time (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
    FUNCTION Core (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
        day_ VARCHAR2(7); /* This means this FUNCTION only supports up to 99 days */
        hour_ VARCHAR2(9); /* This means this FUNCTION only supports up to 999 hours, which is over 41 days */
        minute_ VARCHAR2(12); /* This means this FUNCTION only supports up to 9999 minutes, which is over 17 days */
        second_ VARCHAR2(18); /* This means this FUNCTION only supports up to 999999 seconds, which is over 11 days */
        msecond_ VARCHAR2(22); /* This means this FUNCTION only supports up to 999999999 milliseconds, which is over 11 days */
        d1_ NUMBER;
        h1_ NUMBER;
        m1_ NUMBER;
        s1_ NUMBER;
        ms_ NUMBER;
        /* If you choose 1, you only get seconds. If you choose 2, you get minutes and seconds etc. */
        precision_ NUMBER; /* 0 => milliseconds; 1 => seconds; 2 => minutes; 3 => hours; 4 => days */
        format_ VARCHAR2(2) := ', ';
        return_ VARCHAR2(50);
    BEGIN
        IF (syntax_ IS NULL) THEN
            precision_ := 0;
        ELSE
            IF (syntax_ = 0) THEN
                precision_ := 0;
            ELSIF (syntax_ = 1) THEN
                precision_ := 1;
            ELSIF (syntax_ = 2) THEN
                precision_ := 2;
            ELSIF (syntax_ = 3) THEN
                precision_ := 3;
            ELSIF (syntax_ = 4) THEN
                precision_ := 4;
            ELSE 
                precision_ := 0;
            END IF;
        END IF;
        SELECT EXTRACT(DAY FROM (end_ - start_)) INTO d1_ FROM DUAL;
        SELECT EXTRACT(HOUR FROM (end_ - start_)) INTO h1_ FROM DUAL;
        SELECT EXTRACT(MINUTE FROM (end_ - start_)) INTO m1_ FROM DUAL;
        SELECT EXTRACT(SECOND FROM (end_ - start_)) INTO s1_ FROM DUAL;
        IF (precision_ = 4) THEN
            IF (d1_ = 1) THEN
                day_ := ' day';
            ELSE
                day_ := ' days';
            END IF;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := d1_ || day_ || format_ || h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 3) THEN
            h1_ := (d1_ * 24) + h1_;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 2) THEN
            m1_ := (((d1_ * 24) + h1_) * 60) + m1_;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 1) THEN
            s1_ := (((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := s1_ || second_;
            RETURN return_;
        ELSE
            ms_ := ((((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_) * 1000;
            IF (ms_ = 1) THEN
                msecond_ := ' millisecond';
            ELSE
                msecond_ := ' milliseconds';
            END IF;
            return_ := ms_ || msecond_;
            RETURN return_;
        END IF;
    END Core;
BEGIN
    RETURN(Core(start_, end_, syntax_));
END Return_Elapsed_Time;

For example, if I called this function right now (12.10.2018 11:17:00.00) using Return_Elapsed_Time(TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'),SYSTIMESTAMP), it should return something like:

47344620000 milliseconds

How to install maven on redhat linux

Pretty much what others said, but using "~/.bash_profile" and step by step (for beginners):

  1. Move to home folder and create a new folder for maven artifacts:
    • cd ~ && mkdir installed-packages
  2. Go to https://maven.apache.org/download.cgi and wget the latest artifact:
    • If you don't have wget installed: sudo yum install -y wget
    • cd ~/installed-packages
    • wget http://www-eu.apache.org/dist/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz
  3. Uncompress the downloaded file:
    • tar -xvf apache-maven-3.5.0-bin.tar.gz
  4. Create a symbolic link of the uncompressed file:
    • ln -s ~/installed-packages/apache-maven-3.5.0 /usr/local/apache-maven
  5. Edit ~/.bash_profile (This is where environment variables are commonly stored):
    • vi ~/.bash_profile
    • Add the variable: MVN_HOME=/usr/local/apache-maven (do this before PATH variable is defined)
      • (For those who don't know vi tool: Press i key to enable insert mode)
    • Go to the end of the line where PATH variable is defined and append the following: :$MVN_HOME:$MVN_HOME/bin
    • Save changes
      • (For those who don't know vi tool: Press esc key to exit insert mode and :wq! to save and quit file)
  6. Reload environment variables:
    • source ~/.bash_profile
  7. Confirm that maven command now works properly:
    • mvn --help

How do I give ASP.NET permission to write to a folder in Windows 7?

I know this is an old thread but to further expand the answer here, by default IIS 7.5 creates application pool identity accounts to run the worker process under. You can't search for these accounts like normal user accounts when adding file permissions. To add them into NTFS permission ACL you can type the entire name of the application pool identity and it will work.

It is just a slight difference in the way the application pool identity accounts are handle as they are seen to be virtual accounts.

Also the username of the application pool identity is "IIS AppPool\application pool name" so if it was the application pool DefaultAppPool the user account would be "IIS AppPool\DefaultAppPool".

These can be seen if you open computer management and look at the members of the local group IIS_IUSRS. The SID appended to the end of them is not need when adding the account into an NTFS permission ACL.

Hope that helps

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Error "The connection to adb is down, and a severe error has occurred."

I've deleted all my tasks from HTC task manager and now it's working.

npm ERR! network getaddrinfo ENOTFOUND

First I check whether proxy is set for me or not using this :

npm config get proxy

It returned null then I run this command

npm config set strict-ssl=false

It disable strict-ssl for that cmd session.

You can see complete list of config using this

npm config list ls -l

Get Android shared preferences value in activity/normal class

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

Prevent typing non-numeric in input type number

Update on the accepted answer:

Because of many properties becoming deprecated

(property) KeyboardEvent.which: number @deprecated

you should just rely on the key property and create the rest of the logic by yourself:

The code allows Enter, Backspace and all numbers [0-9], every other character is disallowed.

document.querySelector("input").addEventListener("keypress", (e) => {
  if (isNaN(parseInt(e.key, 10)) && e.key !== "Backspace" && e.key !== "Enter") {
      e.preventDefault();
    }
});

NOTE This will disable paste action

Calling multiple JavaScript functions on a button click

Change

OnClientClick="return validateView();ShowDiv1();">

to

OnClientClick="javascript: if(validateView()) ShowDiv1();">

How can I find a file/directory that could be anywhere on linux command line?

I hope this comment will help you to find out your local & server file path using terminal

 find "$(cd ..; pwd)" -name "filename"

Or just you want to see your Current location then run

 pwd "filename"

Determine the size of an InputStream

If you know that your InputStream is a FileInputStream or a ByteArrayInputStream, you can use a little reflection to get at the stream size without reading the entire contents. Here's an example method:

static long getInputLength(InputStream inputStream) {
    try {
        if (inputStream instanceof FilterInputStream) {
            FilterInputStream filtered = (FilterInputStream)inputStream;
            Field field = FilterInputStream.class.getDeclaredField("in");
            field.setAccessible(true);
            InputStream internal = (InputStream) field.get(filtered);
            return getInputLength(internal);
        } else if (inputStream instanceof ByteArrayInputStream) {
            ByteArrayInputStream wrapper = (ByteArrayInputStream)inputStream;
            Field field = ByteArrayInputStream.class.getDeclaredField("buf");
            field.setAccessible(true);
            byte[] buffer = (byte[])field.get(wrapper);
            return buffer.length;
        } else if (inputStream instanceof FileInputStream) {
            FileInputStream fileStream = (FileInputStream)inputStream;
            return fileStream.getChannel().size();
        }
    } catch (NoSuchFieldException | IllegalAccessException | IOException exception) {
        // Ignore all errors and just return -1.
    }
    return -1;
}

This could be extended to support additional input streams, I am sure.

Uri not Absolute exception getting while calling Restful Webservice

Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:

enter image description here

The order of keys in dictionaries

Python 3.7+

In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

Python 3.6 (CPython)

As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.

Python >=2.7 and <3.6

Use the collections.OrderedDict class when you need a dict that remembers the order of items inserted.

Error You must specify a region when running command aws ecs list-container-instances

Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add

"--profile" option.

For example:

Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,

[profile playground] region=us-east-1

then, use something like below

aws ecs list-container-instances --cluster default --profile playground

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.

/**
 * @author       Rob W <[email protected]>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Usage:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

Possible questions (& answers):

Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.

Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.

  • IE 8+
  • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
  • Opera 10.50+
  • Safari 4+
  • Chrome 3+

Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference

Revision history

  • 17 may 2012
    Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
    Functions are automatically queued when the player is not ready yet.
  • 24 july 2012
    Updated and successully tested in the supported browsers (look ahead).
  • 10 october 2013 When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
  • 12 Dec 2013, recommended to add &origin=* in the URL.
  • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
  • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.

Task.Run with Parameter(s)?

Just use Task.Run

var task = Task.Run(() =>
{
    //this will already share scope with rawData, no need to use a placeholder
});

Or, if you would like to use it in a method and await the task later

public Task<T> SomethingAsync<T>()
{
    var task = Task.Run(() =>
    {
        //presumably do something which takes a few ms here
        //this will share scope with any passed parameters in the method
        return default(T);
    });

    return task;
}

"Could not find acceptable representation" using spring-boot-starter-web

I had this issue when accessing actuator. Putting following configuration class solved the issue:

@Configuration
@EnableWebMvc
public class MediaConverterConfiguration implements WebMvcConfigurer {
    @Bean
    public MappingJackson2HttpMessageConverter jacksonConverter() {
        MappingJackson2HttpMessageConverter mc =
                new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes =
                new ArrayList<>(mc.getSupportedMediaTypes());
        supportedMediaTypes
                .add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        supportedMediaTypes.add(
            MediaType.valueOf("application/vnd.spring-boot.actuator.v2+json"));
        mc.setSupportedMediaTypes(supportedMediaTypes);
        return mc;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jacksonConverter());
    }
}

How do I display todays date on SSRS report?

  1. Inset Test box in the design area of the SSRS report.
  2. Right-click on the Textbox and scroll down and click on the Expression tab
  3. just type the given expression in the expression area: =format(Today,"dd/MM/yyyy")

Converting a year from 4 digit to 2 digit and back again in C#

This seems to work okay for me. yourDateTime.ToString().Substring(2);

Upgrading Node.js to latest version

Its very simple in Windows OS.

You do not have to do any uninstallation of the old node or npm or anything else.

Just go to nodejs.org

And then look for Downloads for Windows option and below that click on Current... Latest Feature Tab and follow automated instructions

It will download the latest node & npm for you & discarding the old one.

Combining COUNT IF AND VLOOK UP EXCEL

You can combine this all into one formula, but you need to use a regular IF first to find out if the VLOOKUP came back with something, then use your COUNTIF if it did.

=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))

In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

Unrecognized escape sequence for path string containing backslashes

You can either use a double backslash each time

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

or use the @ symbol

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";