Programs & Examples On #Token name resolution

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

In WCF serive project this issue may be due to Reference of System.Web.Mvc.dll 's different version or may be any other DLL's different version issue. So this may be compatibility issue of DLL's different version

When I use

System.Web.Mvc.dll version 5.2.2.0 -> it thorows the Error The content type text/html; charset=utf-8 of the response message

but when I use

System.Web.Mvc.dll version 4.0.0.0 or lower -> That's works fine in my project and not have an Error.

I don't know the reason of this different version of DLL's issue but when I change the DLL's verison which is compatible with your WCF Project than it works fine.

This Error even generate when you add reference of other Project in your WCF Project and this reference project has different version of System.Web.Mvc DLL or could be any other DLL.

C# Create New T()

Take a look at new Constraint

public class MyClass<T> where T : new()
{
    protected T GetObject()
    {
        return new T();
    }
}

T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

You can apply the same constraint to a generic method:

public static T GetObject<T>() where T : new()
{
    return new T();
}

If you need to pass parameters:

protected T GetObject(params object[] args)
{
    return (T)Activator.CreateInstance(typeof(T), args);
}

Connect to external server by using phpMyAdmin

in the config.inc.php, remove all lines with "$cfg['Servers']" , and keep ONLY the "$cfg['Servers'][$i]['host']"

Java String new line

You can also use System.lineSeparator():

String x = "Hello," + System.lineSeparator() + "there";

CocoaPods Errors on Project Build

If you have a watchOS target: I found that suddenly, having pods in the watch extension but not in the watch target itself broke things with this same error. The solution was to add the pods to the watch target also.

How to make primary key as autoincrement for Room Persistence lib

Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.

@Entity(tableName = "employments")
data class Employment(
    @PrimaryKey(autoGenerate = true) val id: Long,
    @ColumnInfo(name = "code") val code: String,
    @ColumnInfo(name = "title") val name: String
){
    constructor(code: String, name: String) : this(0, code, name)
}

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

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

 switch(KEYEVENT.getKeyCode()){
      case KeyEvent.VK_ENTER:
           // I was trying to use case 13 from the ascii table.
           //Krewn Generated method stub... 
           break;
 }

HttpContext.Current.User.Identity.Name is Empty

As @PaulTheCyclist says, If using IISExpress anonymous authentication is enabled by default, windows authentication is disabled.

This can be changed in what I'm sure used to be called PropertyPages (NOT right-click -> properties). Select the web project

Is it possible to Turn page programmatically in UIPageViewController?

As @samwize pointed out, the way of paginating is by using

setViewControllers:array

Here's the way I did it: I have my datasource and the delegate separate. You can call this method and only change the "next" view. Previously you have to apply the paging rules. That is, you have to check direction and the next controller. If you use that method with your custom datasource the array of controllers that you're displaying won't change (since you'll use a custom array on a NSObject subclass).

Using your own datasource the method just sets a new view (with specific direction). Since you will still controll the pages that will display when normally swiping.

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

What is the difference between up-casting and down-casting with respect to class variable

1.- Upcasting.

Doing an upcasting, you define a tag of some type, that points to an object of a subtype (Type and subtype may be called class and subclass, if you feel more comfortable...).

Animal animalCat = new Cat();

What means that such tag, animalCat, will have the functionality (the methods) of type Animal only, because we've declared it as type Animal, not as type Cat.

We are allowed to do that in a "natural/implicit/automatic" way, at compile-time or at a run-time, mainly because Cat inherits some of its functionality from Animal; for example, move(). (At least, cat is an animal, isn't it?)

2.- Downcasting.

But, what would happen if we need to get the functionality of Cat, from our type Animal tag?.

As we have created the animalCat tag pointing to a Cat object, we need a way to call the Cat object methods, from our animalCat tag in a some smart pretty way.

Such procedure is what we call Downcasting, and we can do it only at the run-time.

Time for some code:

public class Animal {
    public String move() {
        return "Going to somewhere";
    }
}

public class Cat extends Animal{
    public String makeNoise() {
        return "Meow!";
    }   
}

public class Test {

    public static void main(String[] args) {
        
    //1.- Upcasting 
    //  __Type_____tag________object
        Animal animalCat = new Cat();
    //Some animal movement
        System.out.println(animalCat.move());
        //prints "Going to somewhere"
        
    //2.- Downcasting   
    //Now you wanna make some Animal noise.
        //First of all: type Animal hasn't any makeNoise() functionality.
        //But Cat can do it!. I wanna be an Animal Cat now!!
        
        //___________________Downcast__tag_____ Cat's method
        String animalNoise = ( (Cat) animalCat ).makeNoise();
        
        System.out.println(animalNoise);
        //Prints "Meow!", as cats usually done.
        
    //3.- An Animal may be a Cat, but a Dog or a Rhinoceros too.
        //All of them have their own noises and own functionalities.
        //Uncomment below and read the error in the console:
        
    //  __Type_____tag________object
        //Cat catAnimal = new Animal();
        
    }

}

Git blame -- prior commits?

git blame -L 10,+1 fe25b6d^ -- src/options.cpp

You can specify a revision for git blame to look back starting from (instead of the default of HEAD); fe25b6d^ is the parent of fe25b6d.


Edit: New to Git 2.23, we have the --ignore-rev option added to git blame:

git blame --ignore-rev fe25b6d

While this doesn't answer OP's question of giving the stack of commits (you'll use git log for that, as per the other answer), it is a better way of this solution, as you won't potentially misblame the other lines.

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

Making a PowerShell POST request if a body param starts with '@'

Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

$JSON = @'
{"@type":"login",
 "username":"[email protected]",
 "password":"yyy"
}
'@

$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

$JSON = @{
    "@type" = "login"
    "username" = "[email protected]"
    "password" = "yyy"
} | ConvertTo-Json

How to model type-safe enum types?

There are many ways of doing.

1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:

def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case 'row => replaceRow(where, newValue)
    case 'col | 'column => replaceCol(where, newValue)
    case _ => throw new IllegalArgumentException
  }

// At REPL:   
scala> val a = unitMatrixInt(3)
a: teste7.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a('row, 1) = a.row(0)
res41: teste7.MatrixInt =
/ 1 0 0 \
| 1 0 0 |
\ 0 0 1 /

scala> a('column, 2) = a.row(0)
res42: teste7.MatrixInt =
/ 1 0 1 \
| 0 1 0 |
\ 0 0 0 /

2) Using class Enumeration:

object Dimension extends Enumeration {
  type Dimension = Value
  val Row, Column = Value
}

or, if you need to serialize or display it:

object Dimension extends Enumeration("Row", "Column") {
  type Dimension = Value
  val Row, Column = Value
}

This can be used like this:

def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case Row => replaceRow(where, newValue)
    case Column => replaceCol(where, newValue)
  }

// At REPL:
scala> a(Row, 2) = a.row(1)
<console>:13: error: not found: value Row
       a(Row, 2) = a.row(1)
         ^

scala> a(Dimension.Row, 2) = a.row(1)
res1: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

scala> import Dimension._
import Dimension._

scala> a(Row, 2) = a.row(1)
res2: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.

3) Case objects:

sealed abstract class Dimension
case object Row extends Dimension
case object Column extends Dimension

Now, if I leave out a case on a match, the compiler will warn me:

MatrixInt.scala:70: warning: match is not exhaustive!
missing combination         Column

    what match {
    ^
one warning found

It's used pretty much the same way, and doesn't even need an import:

scala> val a = unitMatrixInt(3)
a: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a(Row,2) = a.row(0)
res15: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 1 0 0 /

You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.

This answer is essentially a selected parts from this article in my blog.

Substring with reverse index

you can just split it up and get the last element

var string="xxx_456";
var a=string.split("_");
alert(a[1]); #or a.pop

WiX tricks and tips

Setting the IIS enable32BitAppOnWin64 flag http://trycatchfail.com/blog/post/WiX-Snippet-change-enable32BitAppOnWin64.aspx

<InstallExecuteSequence>
   <RemoveExistingProducts After="InstallFinalize" />
   <Custom Action="ConfigureAppPool" After="InstallFinalize" >
     <![CDATA[NOT Installed AND VersionNT64 >= 600]]>         
   </Custom>
</InstallExecuteSequence>

<CustomAction Id="ConfigureAppPool" Return="check" Directory="TARGETDIR" ExeCommand="[SystemFolder]inetsrv\appcmd set apppool /apppool.name:[APPPOOLNAME] /enable32BitAppOnWin64:false" />

Convert LocalDate to LocalDateTime or java.sql.Timestamp

JodaTime

To convert JodaTime's org.joda.time.LocalDate to java.sql.Timestamp, just do

Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());

To convert JodaTime's org.joda.time.LocalDateTime to java.sql.Timestamp, just do

Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());

JavaTime

To convert Java8's java.time.LocalDate to java.sql.Timestamp, just do

Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());

To convert Java8's java.time.LocalDateTime to java.sql.Timestamp, just do

Timestamp timestamp = Timestamp.valueOf(localDateTime);

Docker how to change repository name or rename image?

To rename an image, you give it a new tag, and then remove the old tag using the ‘rmi’ command:

$ docker tag $ docker rmi

This second step is scary, as ‘rmi’ means “remove image”. However, docker won’t actually remove the image if it has any other tags. That is, if you were to immediately follow this with: docker rmi , then it would actually remove the image (assuming there are no other tags assigned to the image)

Create a mocked list by mockito

When dealing with mocking lists and iterating them, I always use something like:

@Spy
private List<Object> parts = new ArrayList<>();

How to output only captured groups with sed?

run(s) of digits

This answer works with any count of digit groups. Example:

$ echo 'Num123that456are7899900contained0018166intext' \
   | sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'

123 456 7899900 0018166

Expanded answer.

Is there any way to tell sed to output only captured groups?

Yes. replace all text by the capture group:

$ echo 'Number 123 inside text' \
   | sed 's/[^0-9]*\([0-9]\{1,\}\)[^0-9]*/\1/'

123
s/[^0-9]*                           # several non-digits
         \([0-9]\{1,\}\)            # followed by one or more digits
                        [^0-9]*     # and followed by more non-digits.
                               /\1/ # gets replaced only by the digits.

Or with extended syntax (less backquotes and allow the use of +):

$ echo 'Number 123 in text' \
   | sed -E 's/[^0-9]*([0-9]+)[^0-9]*/\1/'

123

To avoid printing the original text when there is no number, use:

$ echo 'Number xxx in text' \
   | sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1/p'
  • (-n) Do not print the input by default.
  • (/p) print only if a replacement was done.

And to match several numbers (and also print them):

$ echo 'N 123 in 456 text' \
  | sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1 /gp'

123 456

That works for any count of digit runs:

$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" \
   | sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'

123 456 7899900 0018166

Which is very similar to the grep command:

$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" | grep -Po '\d+'
123
456
7899900
0018166

About \d

and pattern: /([\d]+)/

Sed does not recognize the '\d' (shortcut) syntax. The ascii equivalent used above [0-9] is not exactly equivalent. The only alternative solution is to use a character class: '[[:digit:]]`.

The selected answer use such "character classes" to build a solution:

$ str='This is a sample 123 text and some 987 numbers'
$ echo "$str" | sed -rn 's/[^[:digit:]]*([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)[^[:digit:]]*/\1 \2/p'

That solution only works for (exactly) two runs of digits.

Of course, as the answer is being executed inside the shell, we can define a couple of variables to make such answer shorter:

$ str='This is a sample 123 text and some 987 numbers'
$ d=[[:digit:]]     D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D+($d+)$D*/\1 \2/p"

But, as has been already explained, using a s/…/…/gp command is better:

$ str='This is 75577 a sam33ple 123 text and some 987 numbers'
$ d=[[:digit:]]     D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D*/\1 /gp"
75577 33 123 987

That will cover both repeated runs of digits and writing a short(er) command.

What's the C# equivalent to the With statement in VB?

The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}

How to generate java classes from WSDL file

You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.

It creates the complete source files that you would need.

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

Syntax error: Illegal return statement in JavaScript

In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.

Example:

function a() {
    if (global_block) //syntax error is actually here - missing opening brace
       return;
    } //this unintentionally ends the function

    if (global_somethingelse) {
       //Chrome will show the error occurring here, 
       //but actually the error is in the previous statement
       return; 
    }

    //do something
}

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

You can directly set the content type like below:

res.writeHead(200, {'Content-Type': 'text/plain'});

For reference go through the nodejs Docs link.

Why write <script type="text/javascript"> when the mime type is set by the server?

Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:

if (@type not set or empty) {
   if (@language not set or empty) {
     // Treat as default script language; what this is depends on the
     // content-script-type HTTP header or equivalent META tag
   } else {
     if (@language is one of "javascript", "livescript", "mocha",
                             "javascript1.0", "javascript1.1",
                             "javascript1.2", "javascript1.3",
                             "javascript1.4", "javascript1.5",
                             "javascript1.6", "javascript1.7",
                             "javascript1.8") {
       // Treat as javascript
     } else {
       // Treat as unknown script language; do not execute
     }
   }
} else {
   if (@type is one of "text/javascript", "text/ecmascript",
                       "application/javascript",
                       "application/ecmascript",
                       "application/x-javascript") {
     // Treat as javascript
   } else {
     // Treat as specified (e.g. if pyxpcom is installed and
     // python script is allowed in this context and the type
     // is one that the python runtime claims to handle, use that).
     // If we don't have a runtime for this type, do not execute.
   }
}

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

asp.net mvc @Html.CheckBoxFor

Html.CheckBoxFor expects a Func<TModel, bool> as the first parameter. Therefore your lambda must return a bool, you are currently returning an instance of List<Checkboxes>:

model => model.EmploymentType

You need to iterate over the List<Checkboxes> to output each checkbox:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, 
              new { id = string.Format("employmentType_{0}", i) })
}

oracle plsql: how to parse XML and insert into table

You can load an XML document into an XMLType, then query it, e.g.:

DECLARE
  x XMLType := XMLType(
    '<?xml version="1.0" ?> 
<person>
   <row>
       <name>Tom</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
   <row>
       <name>Jim</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
</person>');
BEGIN
  FOR r IN (
    SELECT ExtractValue(Value(p),'/row/name/text()') as name
          ,ExtractValue(Value(p),'/row/Address/State/text()') as state
          ,ExtractValue(Value(p),'/row/Address/City/text()') as city
    FROM   TABLE(XMLSequence(Extract(x,'/person/row'))) p
    ) LOOP
    -- do whatever you want with r.name, r.state, r.city
  END LOOP;
END;

SQL get the last date time record

Try this:

SELECT filename,Dates,Status 
FROM TableName 
WHERE Dates In (SELECT MAX(Dates) FROM TableName GROUP BY filename)

uppercase first character in a variable with bash

first-letter-to-lower () {
        str="" 
        space=" " 
        for i in $@
        do
                if [ -z $(echo $i | grep "the\|of\|with" ) ]
                then
                        str=$str"$(echo ${i:0:1} | tr  '[A-Z]' '[a-z]')${i:1}$space" 
                else
                        str=$str${i}$space 
                fi
        done
        echo $str
}
first-letter-to-upper-xc () {
        v-first-letter-to-upper | xclip -selection clipboard
}
first-letter-to-upper () {
        str="" 
        space=" " 
        for i in $@
        do
                if [ -z $(echo $i | grep "the\|of\|with" ) ]
                then
                        str=$str"$(echo ${i:0:1} | tr  '[a-z]' '[A-Z]')${i:1}$space" 
                else
                        str=$str${i}$space 
                fi
        done
        echo $str
}

first-letter-to-lower-xc(){ v-first-letter-to-lower | xclip -selection clipboard }

What is C# analog of C++ std::pair?

Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

and access values through t.Item1 and t.Item2, you can simply do it like that:

(string message, int count) = ("Hello", 4);

or even:

(var message, var count) = ("Hello", 4);

Add custom header in HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
    {
        const string WEBSERVICE_URL = "<<Web service URL>>";
        try
        {
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            if (webRequest != null)
            {
                webRequest.Method = "GET";
                webRequest.Timeout = 12000;
                webRequest.ContentType = "application/json";
                webRequest.Headers.Add("Authorization", "Basic dchZ2VudDM6cGFdGVzC5zc3dvmQ=");

                using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        var jsonResponse = sr.ReadToEnd();
                        Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

When should I use the new keyword in C++?

The short answer is: if you're a beginner in C++, you should never be using new or delete yourself.

Instead, you should use smart pointers such as std::unique_ptr and std::make_unique (or less often, std::shared_ptr and std::make_shared). That way, you don't have to worry nearly as much about memory leaks. And even if you're more advanced, best practice would usually be to encapsulate the custom way you're using new and delete into a small class (such as a custom smart pointer) that is dedicated just to object lifecycle issues.

Of course, behind the scenes, these smart pointers are still performing dynamic allocation and deallocation, so code using them would still have the associated runtime overhead. Other answers here have covered these issues, and how to make design decisions on when to use smart pointers versus just creating objects on the stack or incorporating them as direct members of an object, well enough that I won't repeat them. But my executive summary would be: don't use smart pointers or dynamic allocation until something forces you to.

Inserting values into tables Oracle SQL

INSERT
INTO    Employee 
        (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT  '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM    dual
JOIN    state s
ON      s.state_name = 'New York'
JOIN    positions p
ON      p.position_name = 'Sales Executive'
JOIN    manager m
ON      m.manager_name = 'Barry Green'

Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.

What type of hash does WordPress use?

include_once('../../../wp-config.php');

global $wpdb;

$password = wp_hash_password("your password");

Sublime Text 2 multiple line edit

I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.

  1. Cmd + F (Find)
  2. Regexp: [^ ]+ (or \d+, or whatever you prefer)
  3. Option + F (Find All)
  4. Edit it

Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).

How to fill color in a cell in VBA?

  1. Use conditional formatting instead of VBA to highlight errors.

  2. Using a VBA loop like the one you posted will take a long time to process

  3. the statement If cell.Value = "#N/A" Then will never work. If you insist on using VBA to highlight errors, try this instead.

    Sub ColorCells()

    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Comparison")
    Set Data = currentsheet.Range("A2:AW1048576")
    
    For Each cell In Data
    
    If IsError(cell.Value) Then
       cell.Interior.ColorIndex = 3
    End If
    Next
    
    End Sub
    
  4. Be prepared for a long wait, since the procedure loops through 51 million cells

  5. There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.

How to recursively list all the files in a directory in C#?

Here is a version of B. Clay Shannon's code not static for excel-files:

class ExcelSearcher
{
    private List<string> _fileNames;

    public ExcelSearcher(List<string> filenames)
    {
        _fileNames = filenames;
    }
    public List<string> GetExcelFiles(string dir, List<string> filenames = null)
    {

        string dirName = dir;
        var dirNames = new List<string>();
        if (filenames != null)
        {
            _fileNames.Concat(filenames);
        }
        try
        {
            foreach (string f in Directory.GetFiles(dirName))
            {
                if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
                {
                    _fileNames.Add(f);
                }
            }
            dirNames = Directory.GetDirectories(dirName).ToList();
            foreach (string d in dirNames)
            {
                GetExcelFiles(d, _fileNames);
            }
        }
        catch (Exception ex)
        {
            //Bam
        }
        return _fileNames;
    }

Multiple returns from a function

Or you can pass by reference:

function byRef($x, &$a, &$b)
{
    $a = 10 * $x;
    $b = 100 * $x;
}

$a = 0;
$b = 0;

byRef(10, $a, $b);

echo $a . "\n";
echo $b;

This would output

100
1000

Force encode from US-ASCII to UTF-8 (iconv)

ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded. The bytes in the ASCII file and the bytes that would result from "encoding it to UTF-8" would be exactly the same bytes. There's no difference between them, so there's no need to do anything.

It looks like your problem is that the files are not actually ASCII. You need to determine what encoding they are using, and transcode them properly.

Select SQL results grouped by weeks

This should do it for you:

Declare @DatePeriod datetime

Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'

From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
        Sale as 'Sale'

From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod variable is used to fetch only rows relative to the month (in this example only for the month of May)

Output using my sample data:

enter image description here

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

This one specifically works for javascript's regular expression parser /[^[\]]+(?=])/g

just run this in the console

var regex = /[^[\]]+(?=])/g;
var str = "This is a test string [more or less]";
var match = regex.exec(str);
match;

How to get unique values in an array

If you don't need to worry so much about older browsers, this is exactly what Sets are designed for.

The Set object lets you store unique values of any type, whether primitive values or object references.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

const set1 = new Set([1, 2, 3, 4, 5, 1]);
// returns Set(5) {1, 2, 3, 4, 5}

What are the advantages of NumPy over regular Python lists?

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

Convert a Pandas DataFrame to a dictionary

For my use (node names with xy positions) I found @user4179775's answer to the most helpful / intuitive:

import pandas as pd

df = pd.read_csv('glycolysis_nodes_xy.tsv', sep='\t')

df.head()
    nodes    x    y
0  c00033  146  958
1  c00031  601  195
...

xy_dict_list=dict([(i,[a,b]) for i, a,b in zip(df.nodes, df.x,df.y)])

xy_dict_list
{'c00022': [483, 868],
 'c00024': [146, 868],
 ... }

xy_dict_tuples=dict([(i,(a,b)) for i, a,b in zip(df.nodes, df.x,df.y)])

xy_dict_tuples
{'c00022': (483, 868),
 'c00024': (146, 868),
 ... }

Addendum

I later returned to this issue, for other, but related, work. Here is an approach that more closely mirrors the [excellent] accepted answer.

node_df = pd.read_csv('node_prop-glycolysis_tca-from_pg.tsv', sep='\t')

node_df.head()
   node  kegg_id kegg_cid            name  wt  vis
0  22    22       c00022   pyruvate        1   1
1  24    24       c00024   acetyl-CoA      1   1
...

Convert Pandas dataframe to a [list], {dict}, {dict of {dict}}, ...

Per accepted answer:

node_df.set_index('kegg_cid').T.to_dict('list')

{'c00022': [22, 22, 'pyruvate', 1, 1],
 'c00024': [24, 24, 'acetyl-CoA', 1, 1],
 ... }

node_df.set_index('kegg_cid').T.to_dict('dict')

{'c00022': {'kegg_id': 22, 'name': 'pyruvate', 'node': 22, 'vis': 1, 'wt': 1},
 'c00024': {'kegg_id': 24, 'name': 'acetyl-CoA', 'node': 24, 'vis': 1, 'wt': 1},
 ... }

In my case, I wanted to do the same thing but with selected columns from the Pandas dataframe, so I needed to slice the columns. There are two approaches.

  1. Directly:

(see: Convert pandas to dictionary defining the columns used fo the key values)

node_df.set_index('kegg_cid')[['name', 'wt', 'vis']].T.to_dict('dict')

{'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1},
 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1},
 ... }
  1. "Indirectly:" first, slice the desired columns/data from the Pandas dataframe (again, two approaches),
node_df_sliced = node_df[['kegg_cid', 'name', 'wt', 'vis']]

or

node_df_sliced2 = node_df.loc[:, ['kegg_cid', 'name', 'wt', 'vis']]

that can then can be used to create a dictionary of dictionaries

node_df_sliced.set_index('kegg_cid').T.to_dict('dict')

{'c00022': {'name': 'pyruvate', 'vis': 1, 'wt': 1},
 'c00024': {'name': 'acetyl-CoA', 'vis': 1, 'wt': 1},
 ... }

How to generate a HTML page dynamically using PHP?

It looks funny but it works.

<?php 
$file = 'newpage.html';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "<!doctype html><html>
<head><meta charset='utf-8'>
<title>new file</title>
</head><body><h3>New HTML file</h3>
</body></html>
";
// Write the contents back to the file
file_put_contents($file, $current);
?>

Rails - passing parameters in link_to

link_to "+ Service", controller_action_path(:account_id => acct.id)

If it is still not working check the path:

$ rake routes

Adding calculated column(s) to a dataframe in pandas

You could have is_hammer in terms of row["Open"] etc. as follows

def is_hammer(rOpen,rLow,rClose,rHigh):
    return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
       and closed_in_top_half_of_range(rHigh,rLow,rClose)

Then you can use map:

df["isHammer"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])

How to get all options of a select using jQuery?

Some answers uses each, but map is a better alternative here IMHO:

$("select#example option").map(function() {return $(this).val();}).get();

There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).

It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Have you tried adding a magic comment in the script where you use non-ASCII chars? It should go on top of the script.

#!/bin/env ruby
# encoding: utf-8

It worked for me like a charm.

How to add color to Github's README.md file

Unfortunately, this is currently not possible.

The GitHub Markdown documentation has no mention of 'color', 'css', 'html', or 'style'.

While some Markdown processors (e.g. the one used in Ghost) allow for HTML, such as <span style="color:orange;">Word up</span>, GitHub's discards any HTML.

If it's imperative that you use color in your readme, your README.md could simply refer users to a README.html. The trade-off for this, of course, is accessibility.

Read values into a shell variable from a pipe

The following code:

echo "hello world" | ( test=($(< /dev/stdin)); echo test=$test )

will work too, but it will open another new sub-shell after the pipe, where

echo "hello world" | { test=($(< /dev/stdin)); echo test=$test; }

won't.


I had to disable job control to make use of chepnars' method (I was running this command from terminal):

set +m;shopt -s lastpipe
echo "hello world" | read test; echo test=$test
echo "hello world" | test="$(</dev/stdin)"; echo test=$test

Bash Manual says:

lastpipe

If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.

Note: job control is turned off by default in a non-interactive shell and thus you don't need the set +m inside a script.

Get position/offset of element relative to a parent container?

Sure is easy with pure JS, just do this, work for fixed and animated HTML 5 panels too, i made and try this code and it works for any brower (include IE 8):

<script type="text/javascript">
    function fGetCSSProperty(s, e) {
        try { return s.currentStyle ? s.currentStyle[e] : window.getComputedStyle(s)[e]; }
        catch (x) { return null; } 
    }
    function fGetOffSetParent(s) {
        var a = s.offsetParent || document.body;

        while (a && a.tagName && a != document.body && fGetCSSProperty(a, 'position') == 'static')
            a = a.offsetParent;
        return a;
    }
    function GetPosition(s) {
        var b = fGetOffSetParent(s);

        return { Left: (b.offsetLeft + s.offsetLeft), Top: (b.offsetTop + s.offsetTop) };
    }    
</script>

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

Query an XDocument for elements by name at any depth

An example indicating the namespace:

String TheDocumentContent =
@"
<TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' >
   <TheNamespace:GrandParent>
      <TheNamespace:Parent>
         <TheNamespace:Child theName = 'Fred'  />
         <TheNamespace:Child theName = 'Gabi'  />
         <TheNamespace:Child theName = 'George'/>
         <TheNamespace:Child theName = 'Grace' />
         <TheNamespace:Child theName = 'Sam'   />
      </TheNamespace:Parent>
   </TheNamespace:GrandParent>
</TheNamespace:root>
";

XDocument TheDocument = XDocument.Parse( TheDocumentContent );

//Example 1:
var TheElements1 =
from
    AnyElement
in
    TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
select
    AnyElement;

ResultsTxt.AppendText( TheElements1.Count().ToString() );

//Example 2:
var TheElements2 =
from
    AnyElement
in
    TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
where
    AnyElement.Attribute( "theName" ).Value.StartsWith( "G" )
select
    AnyElement;

foreach ( XElement CurrentElement in TheElements2 )
{
    ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value );
}

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

Doing an ordering and then selecting the first item is wasting a lot of time ordering the items after the first one. You don't care about the order of those.

Instead you can use the aggregate function to select the best item based on what you're looking for.

var maxHeight = dimensions
    .Aggregate((agg, next) => 
        next.Height > agg.Height ? next : agg);

var maxHeightAndWidth = dimensions
    .Aggregate((agg, next) => 
        next.Height >= agg.Height && next.Width >= agg.Width ? next: agg);

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew command as:

brew uninstall --force postgresql

ASP.NET MVC - Getting QueryString values

Actually you can capture Query strings in MVC in two ways.....

public ActionResult CrazyMVC(string knownQuerystring)
{

  // This is the known query string captured by the Controller Action Method parameter above
  string myKnownQuerystring = knownQuerystring;

  // This is what I call the mysterious "unknown" query string
  // It is not known because the Controller isn't capturing it
  string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];

  return Content(myKnownQuerystring + " - " + myUnknownQuerystring);

}

This would capture both query strings...for example:

/CrazyMVC?knownQuerystring=123&unknownQuerystring=456

Output: 123 - 456

Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?

Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.

Twitter Bootstrap button click to toggle expand/collapse text section above button

Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.

You would replace his .btn with the following:

<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>

And add a small CSS for when the content is displayed:

.in.collapse+a.btn.showdetails:before { 
    content:'Hide details «';
}
.collapse+a.btn.showdetails:before { 
    content:'Show details »'; 
}

Here is his modified example

Can anonymous class implement interface?

Casting anonymous types to interfaces has been something I've wanted for a while but unfortunately the current implementation forces you to have an implementation of that interface.

The best solution around it is having some type of dynamic proxy that creates the implementation for you. Using the excellent LinFu project you can replace

select new
{
  A = value.A,
  B = value.C + "_" + value.D
};

with

 select new DynamicObject(new
 {
   A = value.A,
   B = value.C + "_" + value.D
 }).CreateDuck<DummyInterface>();

Select All checkboxes using jQuery

I have seen many answers to this question and found some answer is lengthy and some answer is a little bit wrong. I have created my own code by using the above IDs and class.

$('#ckbCheckAll').click(function(){
        if($(this).prop("checked")) {
            $(".checkBoxClass").prop("checked", true);
        } else {
            $(".checkBoxClass").prop("checked", false);
        }                
    });


    $('.checkBoxClass').click(function(){
        if($(".checkBoxClass").length == $(".checkBoxClass:checked").length) { 
            $("#ckbCheckAll").prop("checked", true);
        }else {
            $("#ckbCheckAll").prop("checked", false);            
        }
    });

In the above code, where user clicks on select all checkbox and all checkbox will be selected and vice versa and second code will work when the user selects checkbox one by one then select all checkbox will be checked or unchecked according to a number of checkboxes checked.

ReferenceError: describe is not defined NodeJs

Assuming you are testing via mocha, you have to run your tests using the mocha command instead of the node executable.

So if you haven't already, make sure you do npm install mocha -g. Then just run mocha in your project's root directory.

What does %s mean in a python format string?

In answer to your second question: What does this code do?...

This is fairly standard error-checking code for a Python script that accepts command-line arguments.

So the first if statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:

Usage: myscript.py database-name

The next if statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:

ERROR: Database database-name was not found!

From the documentation:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

What is the advantage of using heredoc in PHP?

The heredoc syntax is much cleaner to me and it is really useful for multi-line strings and avoiding quoting issues. Back in the day I used to use them to construct SQL queries:

$sql = <<<SQL
select *
  from $tablename
 where id in [$order_ids_list]
   and product_name = "widgets"
SQL;

To me this has a lower probability of introducing a syntax error than using quotes:

$sql = "
select *
  from $tablename
 where id in [$order_ids_list]
   and product_name = \"widgets\"
";

Another point is to avoid escaping double quotes in your string:

$x = "The point of the \"argument" was to illustrate the use of here documents";

The problem with the above is the syntax error (the missing escaped quote) I just introduced as opposed to here document syntax:

$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;

It is a bit of style, but I use the following as rules for single, double and here documents for defining strings:

  • Single quotes are used when the string is a constant like 'no variables here'
  • Double quotes when I can put the string on a single line and require variable interpolation or an embedded single quote "Today is ${user}'s birthday"
  • Here documents for multi-line strings that require formatting and variable interpolation.

Inserting HTML elements with JavaScript

As others said the convenient jQuery prepend functionality can be emulated:

var html = '<div>Hello prepended</div>';
document.body.innerHTML = html + document.body.innerHTML;

While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:

If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as &amp, &lt and &gt respectively. Use Node.textContent to get a correct copy of these text nodes' contents.

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Or:

var html = '<div>Hello prepended</div>';
document.body.insertAdjacentHTML('afterbegin', html)

insertAdjacentHTML is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

Sockets: Discover port availability using Java

The following solution is inspired by the SocketUtils implementation of Spring-core (Apache license).

Compared to other solutions using Socket(...) it is pretty fast (testing 1000 TCP ports in less than a second):

public static boolean isTcpPortAvailable(int port) {
    try (ServerSocket serverSocket = new ServerSocket()) {
        // setReuseAddress(false) is required only on OSX, 
        // otherwise the code will not work correctly on that platform          
        serverSocket.setReuseAddress(false);
        serverSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), port), 1);
        return true;
    } catch (Exception ex) {
        return false;
    }
}       

Simple example of threading in C++

When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:

Class.h

class DataManager
{
public:
    bool hasData;
    void getData();
    bool dataAvailable();
};

Class.cpp

#include "DataManager.h"

void DataManager::getData()
{
    // perform background data munging
    hasData = true;
    // be sure to notify on the main thread
}

bool DataManager::dataAvailable()
{
    if (hasData)
    {
        return true;
    }
    else
    {
        std::thread t(&DataManager::getData, this);
        t.detach(); // as opposed to .join, which runs on the current thread
    }
}

Note that this example doesn't get into mutex or locking.

How can I send an Ajax Request on button click from a form with 2 buttons?

Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

$("#button_1, #button_2").on("click", function(e) {
    e.preventDefault();
    $.ajax({type: "POST",
        url: "/pages/test/",
        data: { id: $(this).val(), access_token: $("#access_token").val() },
        success:function(result) {
          alert('ok');
        },
        error:function(result) {
          alert('error');
        }
    });
});

jQuery datepicker years shown

Why not show the year or month selection boxes?

$( ".datefield" ).datepicker({
    changeMonth: true,
    changeYear: true,
    yearRange:'-90:+0'
});

How do I perform an IF...THEN in an SQL SELECT?

From SQL Server 2012 you can use the IIF function for this.

SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *
FROM   Product

This is effectively just a shorthand (albeit not standard SQL) way of writing CASE.

I prefer the conciseness when compared with the expanded CASE version.

Both IIF() and CASE resolve as expressions within a SQL statement and can only be used in well-defined places.

The CASE expression cannot be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures.

If your needs can not be satisfied by these limitations (for example, a need to return differently shaped result sets dependent on some condition) then SQL Server does also have a procedural IF keyword.

IF @IncludeExtendedInformation = 1
  BEGIN
      SELECT A,B,C,X,Y,Z
      FROM   T
  END
ELSE
  BEGIN
      SELECT A,B,C
      FROM   T
  END

Care must sometimes be taken to avoid parameter sniffing issues with this approach however.

Using multiple delimiters in awk

If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t directly, you could set the output separator and it will be included automatically:

< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'

embedding image in html email

There's actually a very good blog post that lists pro's and cons of three different approaches to this problem by Martyn Davies. You can read it at https://sendgrid.com/blog/embedding-images-emails-facts/.

I'd like to add a fourth approach using CSS background images.

Add

<div id="myImage"></div>

to your e-mail body and a css class like:

#myImage {
    background-image:  url('data:image/png;base64,iVBOR...[some more encoding]...rkggg==');
    width: [the-actual-image-width];
    height: [the-actual-image-height];
}

Determine .NET Framework version for dll

Load it into Reflector and see what it references?

for example:

enter image description here

Is there a way to make HTML5 video fullscreen?

Many modern web browsers have implemented a FullScreen API that allows you to give full screen focus to certain HTML elements. This is really great for displaying interactive media like videos in a fully immersive environment.

To get the full screen button working you need to set up another event listener that will call the requestFullScreen() function when the button is clicked. To ensure that this will work across all supported browsers you are also going to need to check to see if the requestFullScreen() is available and fallback to the vendor prefixed versions (mozRequestFullScreen and webkitRequestFullscreen) if it is not.

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
  elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
}

Reference:- https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode Reference:- http://blog.teamtreehouse.com/building-custom-controls-for-html5-videos

How do you handle a "cannot instantiate abstract class" error in C++?

If anyone is getting this error from a function, try using a reference to the abstract class in the parameters instead.

void something(Abstract bruh){
}

to

void something(Abstract& bruh){
}

Check whether a path is valid in Python without creating a file at the path's target

try os.path.exists this will check for the path and return True if exists and False if not.

How can I check if a Perl array contains a particular value?

my @badparams = (1,2,5,7,'a','zzz');

my $badparams = join('|',@badparams);   # '|' or any other character not present in params

foreach my $par (4,5,6,7,'a','z','zzz')
{
    if ($badparams =~ /\b$par\b/)
    {
        print "$par is present\n";
    }
    else
    {
        print "$par is not present\n";
    }
}

You may want to check for numerical leading spaces consistancy

JUnit test for System.out.println()

for out

@Test
void it_prints_out() {

    PrintStream save_out=System.out;final ByteArrayOutputStream out = new ByteArrayOutputStream();System.setOut(new PrintStream(out));

    System.out.println("Hello World!");
    assertEquals("Hello World!\r\n", out.toString());

    System.setOut(save_out);
}

for err

@Test
void it_prints_err() {

    PrintStream save_err=System.err;final ByteArrayOutputStream err= new ByteArrayOutputStream();System.setErr(new PrintStream(err));

    System.err.println("Hello World!");
    assertEquals("Hello World!\r\n", err.toString());

    System.setErr(save_err);
}

'Access denied for user 'root'@'localhost' (using password: NO)'

Firstly, go to the folder support-files on terminal, and start the server by mysql.server start, Secondly, go to the folder bin on terminal or type /usr/local/mysql/bin/mysqladmin -u root -p password

It would ask you for the old temporary password which was given to you while installing Mysql, type that and type in your new password and it would work.

Remote Procedure call failed with sql server 2008 R2

I can't comment yet, but make sure you made all the checks in this quide: How to enable remote connections in SQL Server 2008? It should work fine if all steps are made.

How can I draw vertical text with CSS cross-browser?

I adapted this from http://snook.ca/archives/html_and_css/css-text-rotation :

<style>
    .Rotate-90
    {
        display: block;
        position: absolute;
        right: -5px;
        top: 15px;
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
    }
</style>
<!--[if IE]>
    <style>
        .Rotate-90 {
            filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
            right:-15px; top:5px;
        }
    </style>
    <![endif]-->

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Check this example of post the array of different types

function PostArray() {
    var myObj = [
        { 'fstName': 'name 1', 'lastName': 'last name 1', 'age': 32 }
      , { 'fstName': 'name 2', 'lastName': 'last name 1', 'age': 33 }
    ];

    var postData = JSON.stringify({ lst: myObj });
    console.log(postData);

    $.ajax({
        type: "POST",
        url: urlWebMethods + "/getNames",
        data: postData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            alert(response.d);
        },
        failure: function (msg) {
            alert(msg.d);
        }
    });
}

If using a WebMethod in C# you can retrieve the data like this

[WebMethod]
    public static string getNames(IEnumerable<object> lst)
    {
        string names = "";
        try
        {
            foreach (object item in lst)
            {
                Type myType = item.GetType();
                IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

                foreach (PropertyInfo prop in props)
                {
                    if(prop.Name == "Values")
                    {
                        Dictionary<string, object> dic = item as Dictionary<string, object>;
                        names += dic["fstName"];
                    }
                }
            }
        }
        catch (Exception ex)
        {
             names = "-1";
        }
        return names;
    }

Example in POST an array of objects with $.ajax to C# WebMethod

Saving timestamp in mysql table using php

If I know the database is MySQL, I'll use the NOW() function like this:

INSERT INTO table_name
   (id, name, created_at) 
VALUES 
   (1, 'Gordon', NOW()) 

How can I set up an editor to work with Git on Windows?

I've had difficulty getting Git to cooperate with WordPad, Komodo Edit and pretty much every other editor I give it. Most open for editing, but Git clearly doesn't wait for the save/close to happen.

As a crutch, I've just been doing i.e.

git commit -m "Fixed the LoadAll method"

to keep things moving. It tends to keep my commit messages a little shorter than they probably should be, but clearly there's some work to be done on the Windows version of Git.

The GitGUI also isn't that bad. It takes a little bit of orientation, but after that, it works fairly well.

COUNT / GROUP BY with active record?

I believe you'll want something like this:

 $this->db->select('user_id, COUNT(user_id) as total');
 $this->db->group_by('user_id'); 
 $this->db->order_by('total', 'desc'); 
 $this->db->get('tablename', 10);

This will produce a result like

|  USER_ID |  TOTAL  |
|    12    |    3    |
|    15    |    2    |
|    18    |    1    |

UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.

Generate HTML table from 2D JavaScript array

Based on the accepted solution:

function createTable (tableData) {
  const table = document.createElement('table').appendChild(
    tableData.reduce((tbody, rowData) => {
      tbody.appendChild(
        rowData.reduce((tr, cellData) => {
          tr.appendChild(
            document
              .createElement('td')
              .appendChild(document.createTextNode(cellData))
          )
          return tr
        }, document.createElement('tr'))
      )
      return tbody
    }, document.createElement('tbody'))
  )

  document.body.appendChild(table)
}

createTable([
  ['row 1, cell 1', 'row 1, cell 2'],
  ['row 2, cell 1', 'row 2, cell 2']
])

With a simple change it is possible to return the table as HTML element.

"rm -rf" equivalent for Windows?

First, let’s review what rm -rf does:

C:\Users\ohnob\things>touch stuff.txt

C:\Users\ohnob\things>rm -rf stuff.txt

C:\Users\ohnob\things>mkdir stuff.txt

C:\Users\ohnob\things>rm -rf stuff.txt

C:\Users\ohnob\things>ls -l
total 0

C:\Users\ohnob\things>rm -rf stuff.txt

There are three scenarios where rm -rf is commonly used where it is expected to return 0:

  1. The specified path does not exist.
  2. The specified path exists and is a directory.
  3. The specified path exists and is a file.

I’m going to ignore the whole permissions thing, but nobody uses permissions or tries to deny themselves write access on things in Windows anyways (OK, that’s meant to be a joke…).

First set ERRORLEVEL to 0 and then delete the path only if it exists, using different commands depending on whether or not it is a directory. IF EXIST does not set ERRORLEVEL to 0 if the path does not exist, so setting the ERRORLEVEL to 0 first is necessary to properly detect success in a way that mimics normal rm -rf usage. Guarding the RD with IF EXIST is necessary because RD, unlike rm -f, will throw an error if the target does not exist.

The following script snippet assumes that DELPATH is prequoted. (This is safe when you do something like SET DELPATH=%1. Try putting ECHO %1 in a .cmd and passing it an argument with spaces in it and see what happens for yourself). After the snippet completes, you can check for failure with IF ERRORLEVEL 1.

: # Determine whether we need to invoke DEL or RD or do nothing.
SET DELPATH_DELMETHOD=RD
PUSHD %DELPATH% 2>NUL
IF ERRORLEVEL 1 (SET DELPATH_DELMETHOD=DEL) ELSE (POPD)
IF NOT EXIST %DELPATH% SET DELPATH_DELMETHOD=NOOP
: # Reset ERRORLEVEL so that the last command which
: # otherwise set it does not cause us to falsely detect
: # failure.
CMD /C EXIT 0
IF %DELPATH_DELMETHOD%==DEL DEL /Q %DELPATH%
IF %DELPATH_DELMETHOD%==RD RD /S /Q %DELPATH%

Point is, everything is simpler when the environment just conforms to POSIX. Or if you install a minimal MSYS and just use that.

How can I change the language (to english) in Oracle SQL Developer?

On MAC High Sierra (10.13.6)

cd /Users/vkrishna/.sqldeveloper/18.2.0

nano product.conf

on the last line add

AddVMOption -Duser.language=en

Save the file and restart.

=======================================

If you are using standalone Oracle Data Modeller

find ~/ -name "datamodeler.conf"

and edit this file

cd /Users/vkrishna//Desktop/OracleDataModeler-18.2.0.179.0756.app/Contents/Resources/datamodeler/datamodeler/bin/

Add somewhere in the last

AddVMOption -Duser.language=en

save and restart, done!

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

CSS3 opacity gradient?

Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip to text.

Create proper gradient:

background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);

Then clip the backgroud with text:

background-clip: text;
color: transparent;

Demo

https://jsfiddle.net/simonmysun/2h61Ljbn/4/

Tested under Chrome 75 under Windows 10.

Supported platforms:

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

How to implement __iter__(self) for a container object (Python)

usually __iter__() just return self if you have already define the next() method (generator object):

here is a Dummy example of a generator :

class Test(object):

    def __init__(self, data):
       self.data = data

    def next(self):
        if not self.data:
           raise StopIteration
        return self.data.pop()

    def __iter__(self):
        return self

but __iter__() can also be used like this: http://mail.python.org/pipermail/tutor/2006-January/044455.html

Eclipse error "Could not find or load main class"

Happened to me when I changed installed JREs to JDK7 instead of JRE7. Everything compiled but I couldn't run anything from Eclipse "eclipse-error-could-not-find-or-load-main-class"

Fix; going back to previous JRE7.

Disable sorting for a particular column in jQuery DataTables

Using Datatables 1.9.4 I've disabled the sorting for the first column with this code:

/* Table initialisation */
$(document).ready(function() {
    $('#rules').dataTable({
        "sDom" : "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
        "sPaginationType" : "bootstrap",
        "oLanguage" : {
            "sLengthMenu" : "_MENU_ records per page"
        },
        // Disable sorting on the first column
        "aoColumnDefs" : [ {
            'bSortable' : false,
            'aTargets' : [ 0 ]
        } ]
    });
});

EDIT:

You can disable even by using the no-sort class on your <th>,

and use this initialization code:

// Disable sorting on the no-sort class
"aoColumnDefs" : [ {
    "bSortable" : false,
    "aTargets" : [ "no-sort" ]
} ]

EDIT 2

In this example I'm using Datables with Bootstrap, following an old blog post. Now there is one link with updated material about styling Datatables with bootstrap.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

For API 23:

Top level build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
    }
}
...

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"
    useLibrary 'org.apache.http.legacy'
    ...
}

Official docs (for preview though): http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client

Latest android gradle plugin changelog: http://tools.android.com/tech-docs/new-build-system

How to import/include a CSS file using PHP code and not HTML code?

You have to surround the CSS with a <style> tag:

<?php include 'header.php'; ?>
<style>
<?php include 'CSS/main.css'; ?>
</style>
...

PHP include works fine with .css ending too. In this way you can even use PHP in your CSS file. That can be really helpful to organize e.g. colors as variables.

CSS rotation cross browser with jquery.animate()

this is my solution:

var matrixRegex = /(?:matrix\(|\s*,\s*)([-+]?[0-9]*\.?[0-9]+(?:[e][-+]?[0-9]+)?)/gi;

var getMatches = function(string, regex) {
    regex || (regex = matrixRegex);
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match[1]);
    }
    return matches;
};

$.cssHooks['rotation'] = {
    get: function(elem) {
        var $elem = $(elem);
        var matrix = getMatches($elem.css('transform'));
        if (matrix.length != 6) {
            return 0;
        }
        return Math.atan2(parseFloat(matrix[1]), parseFloat(matrix[0])) * (180/Math.PI);
    }, 
    set: function(elem, val){
        var $elem = $(elem);
        var deg = parseFloat(val);
        if (!isNaN(deg)) {
            $elem.css({ transform: 'rotate(' + deg + 'deg)' });
        }
    }
};
$.cssNumber.rotation = true;
$.fx.step.rotation = function(fx) {
    $.cssHooks.rotation.set(fx.elem, fx.now + fx.unit);
};

then you can use it in the default animate fkt:

//rotate to 90 deg cw
$('selector').animate({ rotation: 90 });

//rotate to -90 deg ccw
$('selector').animate({ rotation: -90 });

//rotate 90 deg cw from current rotation
$('selector').animate({ rotation: '+=90' });

//rotate 90 deg ccw from current rotation
$('selector').animate({ rotation: '-=90' });

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..

So every visitor to my site helps in killing the sleeping processes..

<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>

regex for zip-code

I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.

In a previous answer from @kennytm:

^\d{5}(?:[-\s]\d{4})?$

…? = The pattern before it is optional (for condition 1)

If you want to allow both standard 5 digit and +4 zip codes, this is a great example.

To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ? so it will always match the last 5 character group.

A useful tool I recommend for tinkering with RegEx is linked below:

https://regexr.com/

I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.

If I got anything wrong or missed an important piece of information, please correct me.

How to load assemblies in PowerShell?

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

Eclipse: How do I add the javax.servlet package to a project?

When you define a server in server view, then it will create you a server runtime library with server libs (including servlet api), that can be assigned to your project. However, then everybody that uses your project, need to create the same type of runtime in his/her eclipse workspace even for compiling.

If you directly download the servlet api jar, than it could lead to problems, since it will be included into the artifacts of your projects, but will be also present in servlet container.

In Maven it is much nicer, since you can define the servlet api interfaces as a "provided" dependency, that means it is present in the "to be production" environment.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

What does 'x packages are looking for funding' mean when running `npm install`?

npm fund [<pkg>]

This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund

How do I merge my local uncommitted changes into another Git branch?

The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.

How to Commit to a Different Branch in git

You have uncommited changes on my_branch that you want to commit to master, without committing all the changes from my_branch.

Example

git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop

Explanation

Start by merging master into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.

The -u option (aka --include-untracked) in git stash -u prevents you from losing untracked files when you later do git clean -f -d within master.

After git checkout master it is important that you do NOT git stash pop, because you will need this stash later. If you pop the stash created in my_branch and then do git stash in master, you will cause needless merge conflicts when you later apply that stash in my_branch.

git reset unstages everything resulting from git stash apply. For example, files that have been modified in the stash but do not exist in master get staged as "deleted by us" conflicts.

git checkout . and git clean -f -d discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master would cause needless merge conflicts when switching back to my_branch.

The last git stash pop will be based on the original my_branch, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop, git add ., and git reset.

equivalent of rm and mv in windows .cmd

If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.

From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.

Windows command     Unix command
rmdir               rmdir
rmdir /s            rm -r
move                mv

I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".

All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.

(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\

gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt

dirwithsubdirs, Are you sure (Y/N)?

and that when I typed Y, the result was that my top directory and its constituent files and subdirectories went away.


Edit

I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.

Windows command     Unix command
rmdir               rmdir
rmdir /s /q         rm -r
rmdir /s /q         rm -rf
rmdir /s            rm -ri
move                mv
del <file>          rm <file>

If you want the equivalent for

rm -rf

you can use

rmdir /s /q

or, as the author of the answer I sourced described,

But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

echo y | rmdir /s


Details about Differences

I tested each of the commands using Windows CMD and Cygwin (with its bash).

Before each test, I made the following setup.

Windows CMD

>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory

Cygwin bash

$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory

That resulted in the following file structure for both.

base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

Here are the results. Note that I'll not mark each as CMD or bash; the CMD will have a > in front, and the bash will have a $ in front.

RMDIR

>rmdir this_directory
The directory is not empty.

>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
|       some.txt
|
\---this_empty_directory

> rmdir this_empty_directory

>tree /a /f .
base
\---this_directory
        some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty

$ tree --charset=ascii
base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

2 directories, 1 file

$ rmdir this_empty_directory

$ tree --charset=ascii
base
`-- this_directory
    `-- some.txt

RMDIR /S /Q and RM -R ; RM -RF

>rmdir /s /q this_directory

>tree /a /f
base
\---this_empty_directory

>rmdir /s /q this_empty_directory

>tree /a /f
base
No subfolders exist
$ rm -r this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -r this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -rf this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files

RMDIR /S AND RM -RI Here, we have a bit of a difference, but they're pretty close.

>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y

>tree /a /f
base
\---this_empty_directory

>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y

>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y

$ tree --charset=ascii
base
0 directories, 0 files

I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST


Notes

  1. I know almost nothing about the LeMoDa website, other than the fact that the info is

Copyright © Ben Bullock 2009-2018. All rights reserved.

(archived copyright notice)

and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.

I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.

I will include the disclaimer (archived) from the site:

Disclaimer Please read the following disclaimer before using any of the computer program code on this site.

There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.

In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.


  1. Actually, I found the information with a Google search for "cmd equivalent of rm"

https://www.google.com/search?q=cmd+equivalent+of+rm

The information I'm sharing came up first.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

REMOTE_ADDR can not be trusted.

Anyway, try

$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}

Edit: Also, does your server's router have port forwarding enabled? It may be possible that it's messing with the packets.

Security warning: REMOTE_ADDR can be fully trusted! It comes from your own webserver and contains the IP that was used to access it. You don't even need to quote() it for SQL inserts.
But HTTP_X_FORWARDED_FOR is taken directly from the HTTP headers, it can contain the picture of a cat, malicious code, any content. Treat it like that, never trust it.

How can I get the full/absolute URL (with domain) in Django?

If you can't get access to request then you can't use get_current_site(request) as recommended in some solutions here. You can use a combination of the native Sites framework and get_absolute_url instead. Set up at least one Site in the admin, make sure your model has a get_absolute_url() method, then:

>>> from django.contrib.sites.models import Site
>>> domain = Site.objects.get_current().domain
>>> obj = MyModel.objects.get(id=3)
>>> path = obj.get_absolute_url()

>>> url = 'http://{domain}{path}'.format(domain=domain, path=path)
>>> print(url)
'http://example.com/mymodel/objects/3/'

https://docs.djangoproject.com/en/dev/ref/contrib/sites/#getting-the-current-domain-for-full-urls

How can I get the current network interface throughput statistics on Linux/UNIX?

I find dstat to be quite good. Has to be installed though. Gives you way more information than you need. Netstat will give you packet rates but not bandwith also. netstat -s

How to convert answer into two decimal point

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

Mapping over values in a python dictionary

Just came accross this use case. I implemented gens's answer, adding a recursive approach for handling values that are also dicts:

def mutate_dict_in_place(f, d):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            mutate_dict_in_place(f, v)
        else:
            d[k] = f(v)

# Exemple handy usage
def utf8_everywhere(d):
    mutate_dict_in_place((
        lambda value:
            value.decode('utf-8')
            if isinstance(value, bytes)
            else value
        ),
        d
    )

my_dict = {'a': b'byte1', 'b': {'c': b'byte2', 'd': b'byte3'}}
utf8_everywhere(my_dict)
print(my_dict)

This can be useful when dealing with json or yaml files that encode strings as bytes in Python 2

Taskkill /f doesn't kill a process

Native tskill <pid> (or tskill.exe <pid> ) worked for me on Windows 10 where no other native answer did.

In my case, I had some chrome.exe processes for which task manager's 'End Task' was working, but neither taskkill /F /T /PID <pid> nor powershell's kill -id <pid> worked (even with both shells run as admin).

This is very strange as taskkill is purported to be a better-api-and-does-more version of tskill.

In my case to kill all instances of a certain task I used FOR /F "usebackq tokens=2 skip=2" %i IN (`TASKLIST /FI "IMAGENAME eq name_of_task.exe"`) DO tskill %i

curl error 18 - transfer closed with outstanding read data remaining

I've solved this error by this way.

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;

Error still occurs, but I can handle response data in variable.

When do I have to use interfaces instead of abstract classes?

Many cases can be implemented in both class types.

Interfaces are usefull when you want to define a class that has to have at least basic functions. Like a real interface for example USB.

interface USB {
    public function sendPower(); //charge iphone for example
    public function sendData(); //itunes
    public function recieveData();
}

Use abstract classes when there are several ways to to implement an object.

abstract class MobilePhone {
    public function isIphone();

    public function charge() {
        //get some power, all phones need that
    }
}

class iPhone extends MobilePhone {
    public function isIphone() { return true; }
}

Remove 'b' character do in front of a string literal in Python 3

Decoding is redundant

You only had this "error" in the first place, because of a misunderstanding of what's happening.

You get the b because you encoded to utf-8 and now it's a bytes object.

 >> type("text".encode("utf-8"))
 >> <class 'bytes'>

Fixes:

  1. You can just print the string first
  2. Redundantly decode it after encoding

How to reload the datatable(jquery) data?

Simpler solution:

var dt = $('#table_scroll').dataTable();

$.getJSON(url, null, function (json) {
    dt.fnClearTable();
    dt.fnAddData(json.aaData);
    dt.fnDraw();
});

UIScrollView not scrolling

If you cannot scroll the view even after you set contentSize correctly, make sure you uncheck "Use AutoLayout" in Interface Builder -> File Inspector.

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Unfortunately, modules aren't supported by many browsers right now.

This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.

Found on MDN

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

.htaccess file to allow access to images folder to view pictures?

Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:

Options -Indexes

Or try:

Options All -Indexes

When to use Hadoop, HBase, Hive and Pig?

Let me try to answer in few words.

Hadoop is an eco-system which comprises of all other tools. So, you can't compare Hadoop but you can compare MapReduce.

Here are my few cents:

  1. Hive: If your need is very SQLish meaning your problem statement can be catered by SQL, then the easiest thing to do would be to use Hive. The other case, when you would use hive is when you want a server to have certain structure of data.
  2. Pig: If you are comfortable with Pig Latin and you need is more of the data pipelines. Also, your data lacks structure. In those cases, you could use Pig. Honestly there is not much difference between Hive & Pig with respect to the use cases.
  3. MapReduce: If your problem can not be solved by using SQL straight, you first should try to create UDF for Hive & Pig and then if the UDF is not solving the problem then getting it done via MapReduce makes sense.

How can I hash a password in Java?

While the NIST recommendation PBKDF2 has already been mentioned, I'd like to point out that there was a public password hashing competition that ran from 2013 to 2015. In the end, Argon2 was chosen as the recommended password hashing function.

There is a fairly well adopted Java binding for the original (native C) library that you can use.

In the average use-case, I don't think it does matter from a security perspective if you choose PBKDF2 over Argon2 or vice-versa. If you have strong security requirements, I recommend considering Argon2 in your evaluation.

For further information on the security of password hashing functions see security.se.

random number generator between 0 - 1000 in c#

Have you tried this

Random integer between 0 and 1000(1000 not included):

Random random = new Random();
int randomNumber = random.Next(0, 1000);

Loop it as many times you want

Select row with most recent date per user

Try this query:

  select id,user, max(time), io 
  FROM lms_attendance group by user;

Check if cookies are enabled

JavaScript

You could create a cookie using JavaScript and check if it exists:

//Set a Cookie`
document.cookie="testcookie"`

//Check if cookie exists`
cookiesEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false`

Or you could use a jQuery Cookie plugin

//Set a Cookie`
$.cookie("testcookie", "testvalue")

//Check if cookie exists`
cookiesEnabled=( $.cookie("testcookie") ) ? true : false`

Php

setcookie("testcookie", "testvalue");

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

}

Not sure if the Php will work as I'm unable to test it.

Find the day of a week

This should do the trick

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df

#Returns:
        date       day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02  Thursday

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

How do I run SSH commands on remote system using Java?

I created solution based on JSch library:

import com.google.common.io.CharStreams
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session

import static java.util.Arrays.asList

class RunCommandViaSsh {

    private static final String SSH_HOST = "test.domain.com"
    private static final String SSH_LOGIN = "username"
    private static final String SSH_PASSWORD = "password"

    public static void main() {
        System.out.println(runCommand("pwd"))
        System.out.println(runCommand("ls -la"));
    }

    private static List<String> runCommand(String command) {
        Session session = setupSshSession();
        session.connect();

        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        try {
            channel.setCommand(command);
            channel.setInputStream(null);
            InputStream output = channel.getInputStream();
            channel.connect();

            String result = CharStreams.toString(new InputStreamReader(output));
            return asList(result.split("\n"));

        } catch (JSchException | IOException e) {
            closeConnection(channel, session)
            throw new RuntimeException(e)

        } finally {
            closeConnection(channel, session)
        }
    }

    private static Session setupSshSession() {
        Session session = new JSch().getSession(SSH_LOGIN, SSH_HOST, 22);
        session.setPassword(SSH_PASSWORD);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig("StrictHostKeyChecking", "no"); // disable check for RSA key
        return session;
    }

    private static void closeConnection(ChannelExec channel, Session session) {
        try {
            channel.disconnect()
        } catch (Exception ignored) {
        }
        session.disconnect()
    }
}

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

Auto-indent spaces with C in vim?

A lot of vim's features (like autoindent and cindent) are turned off by default. To really see what vim can do for you, you need a decent ~/.vimrc.

A good starter one is in $VIMRUNTIME/vimrc_example.vim. If you want to try it out, use

:source $VIMRUNTIME/vimrc_example.vim

when in vim.

I'd actually suggest just copying the contents to your ~/.vimrc as it's well commented, and a good place to start learning how to use vim. You can do this by

:e $VIMRUNTIME/vimrc_example.vim
:w! ~/.vimrc

This will overwrite your current ~/.vimrc, but if all you have in there is the indent settings Davr suggested, I wouldn't sweat it, as the example vimrc will take care of that for you as well. For a complete walkthrough of the example, and what it does for you, see :help vimrc-intro.

How can I get a specific field of a csv file?

import csv

def read_cell(x, y):
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
        y_count = 0
        for n in reader:
            if y_count == y:
                cell = n[x]
                return cell
            y_count += 1

print (read_cell(4, 8)) 

This example prints cell 4, 8 in Python 3.

How do I check which version of NumPy I'm using?

import numpy
print numpy.__version__

Adding text to ImageView in Android

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_weight="30" >

        <ImageButton
            android:id="@+id/imgbtnUploadPendingPods"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/hello_world"
            android:src="@drawable/upload_icon" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingTop="30dp"
            android:text="@string/pendingpods"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </FrameLayout>

HintPath vs ReferencePath in Visual Studio

My own experience has been that it's best to stick to one of two kinds of assembly references:

  • A 'local' assembly in the current build directory
  • An assembly in the GAC

I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.

Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).

This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D

Hope that helps!

custom facebook share button

Well, I use this method on my site:

<a class="share-btn" href="https://www.facebook.com/sharer/sharer.php?app_id=[your_app_id]&sdk=joey&u=[full_article_url]&display=popup&ref=plugin&src=share_button" onclick="return !window.open(this.href, 'Facebook', 'width=640,height=580')">

Works perfectly.

Batch file to delete files older than N days

Expanding on aku's answer, I see a lot of people asking about UNC paths. Simply mapping the unc path to a drive letter will make forfiles happy. Mapping and unmapping of drives can be done programmatically in a batch file, for example.

net use Z: /delete
net use Z: \\unc\path\to\my\folder
forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"

This will delete all files with a .gz extension that are older than 7 days. If you want to make sure Z: isn't mapped to anything else before using it you could do something simple as

net use Z: \\unc\path\to\my\folder
if %errorlevel% equ 0 (
    forfiles /p Z: /s /m *.gz /D -7 /C "cmd /c del @path"
) else (
    echo "Z: is already in use, please use another drive letter!"
)

Can I multiply strings in Java to repeat sequences?

Two ways comes to mind:

int i = 3;
String someNum = "123";

// Way 1:
char[] zeroes1 = new char[i];
Arrays.fill(zeroes1, '0');
String newNum1 = someNum + new String(zeroes1);
System.out.println(newNum1); // 123000

// Way 2:
String zeroes2 = String.format("%0" + i + "d", 0);
String newNum2 = someNum + zeroes2;
System.out.println(newNum2); // 123000

Way 2 can be shortened to:

someNum += String.format("%0" + i + "d", 0);
System.out.println(someNum); // 123000

More about String#format() is available in its API doc and the one of java.util.Formatter.

WCF change endpoint address at runtime

app.config

<client>
    <endpoint address="" binding="basicHttpBinding" 
    bindingConfiguration="LisansSoap" 
    contract="Lisans.LisansSoap" 
    name="LisansSoap" />
</client>

program

 Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
                         "http://webservis.uzmanevi.com/Lisans/Lisans.asmx");

 MessageBox.Show(test.LisansKontrol("","",""));

"for" vs "each" in Ruby

This is the only difference:

each:

irb> [1,2,3].each { |x| }
  => [1, 2, 3]
irb> x
NameError: undefined local variable or method `x' for main:Object
    from (irb):2
    from :0

for:

irb> for x in [1,2,3]; end
  => [1, 2, 3]
irb> x
  => 3

With the for loop, the iterator variable still lives after the block is done. With the each loop, it doesn't, unless it was already defined as a local variable before the loop started.

Other than that, for is just syntax sugar for the each method.

When @collection is nil both loops throw an exception:

Exception: undefined local variable or method `@collection' for main:Object

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

What's the fastest way to convert String to Number in JavaScript?

Here is simple way to do it: var num = Number(str); in this example str is the variable that contains the string. You can tested and see how it works open: Google chrome developer tools, then go to the console and paste the following code. read the comments to understand better how the conversion is done.

// Here Im creating my variable as a string
var str = "258";


// here im printing the string variable: str
console.log ( str );


// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);


// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);

How to update large table with millions of rows in SQL Server?

This is a more efficient version of the solution from @Kramb. The existence check is redundant as the update where clause already handles this. Instead you just grab the rowcount and compare to batchsize.

Also note @Kramb solution didn't filter out already updated rows from the next iteration hence it would be an infinite loop.

Also uses the modern batch size syntax instead of using rowcount.

DECLARE @batchSize INT, @rowsUpdated INT
SET @batchSize = 1000;
SET @rowsUpdated = @batchSize; -- Initialise for the while loop entry

WHILE (@batchSize = @rowsUpdated)
BEGIN
    UPDATE TOP (@batchSize) TableName
    SET Value = 'abc1'
    WHERE Parameter1 = 'abc' AND Parameter2 = 123 and Value <> 'abc1';

    SET @rowsUpdated = @@ROWCOUNT;
END

What is setup.py?

If you downloaded package that has "setup.py" in root folder, you can install it by running

python setup.py install

If you are developing a project and are wondering what this file is useful for, check Python documentation on writing the Setup Script

Android Studio was unable to find a valid Jvm (Related to MAC OS)

"On Mac OS, run Android Studio with Java Runtime Environment (JRE) 6 for optimized font rendering. You can then configure your project to use Java Development Kit (JDK) 6 or JDK 7."

This was listed in http://developer.android.com/sdk/index.html under the system requirements for Mac OS X.

Once you install Java 6 (not the JDK) from Apple as per Alonso C. Licks, you should be able to open Android Studio and reconfigure as you wish without having to mess around in the terminal, info.plist file, or other libraries.

Item frequency count in Python

The answer below takes some extra cycles, but it is another method

def func(tup):
    return tup[-1]


def print_words(filename):
    f = open("small.txt",'r')
    whole_content = (f.read()).lower()
    print whole_content
    list_content = whole_content.split()
    dict = {}
    for one_word in list_content:
        dict[one_word] = 0
    for one_word in list_content:
        dict[one_word] += 1
    print dict.items()
    print sorted(dict.items(),key=func)

std::enable_if to conditionally compile a member function

I made this short example which also works.

#include <iostream>
#include <type_traits>

class foo;
class bar;

template<class T>
struct is_bar
{
    template<class Q = T>
    typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
    {
        return true;
    }

    template<class Q = T>
    typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
    {
        return false;
    }
};

int main()
{
    is_bar<foo> foo_is_bar;
    is_bar<bar> bar_is_bar;
    if (!foo_is_bar.check() && bar_is_bar.check())
        std::cout << "It works!" << std::endl;

    return 0;
}

Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)

You can see it in action here.

Binding a list in @RequestParam

Change hidden field value with checkbox toggle like below...

HTML:

<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox"  onclick="toggle(this)"/> Delete All

Script:

function toggle(obj) {`var $input = $(obj);
    if ($input.prop('checked')) {

    $('#deleteAll').attr( 'value','Checked');

    } else {

    $('#deleteAll').attr( 'value','Unchecked');

    }

}

How to find out the location of currently used MySQL configuration file in linux

If you are using terminal just type the following:

locate my.cnf

jquery: get id from class selector

As of jQuery 1.6, you could (and some would say should) use .prop instead of .attr

$('.test').click(function(){
    alert($(this).prop('id'));
});

It is discussed further in this post: .prop() vs .attr()

Flatten an irregular list of lists

If you like recursion, this might be a solution of interest to you:

def f(E):
    if E==[]: 
        return []
    elif type(E) != list: 
        return [E]
    else:
        a = f(E[0])
        b = f(E[1:])
        a.extend(b)
        return a

I actually adapted this from some practice Scheme code that I had written a while back.

Enjoy!

What is the difference between .*? and .* regular expressions?

It is the difference between greedy and non-greedy quantifiers.

Consider the input 101000000000100.

Using 1.*1, * is greedy - it will match all the way to the end, and then backtrack until it can match 1, leaving you with 1010000000001.
.*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1, eventually matching 101.

All quantifiers have a non-greedy mode: .*?, .+?, .{2,6}?, and even .??.

In your case, a similar pattern could be <([^>]*)> - matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than > in-between < and >).

See Quantifier Cheat Sheet.

Chaining multiple filter() in Django, is this a bug?

Sometimes you don't want to join multiple filters together like this:

def your_dynamic_query_generator(self, event: Event):
    qs \
    .filter(shiftregistrations__event=event) \
    .filter(shiftregistrations__shifts=False)

And the following code would actually not return the correct thing.

def your_dynamic_query_generator(self, event: Event):
    return Q(shiftregistrations__event=event) & Q(shiftregistrations__shifts=False)

What you can do now is to use an annotation count-filter.

In this case we count all shifts which belongs to a certain event.

qs: EventQuerySet = qs.annotate(
    num_shifts=Count('shiftregistrations__shifts', filter=Q(shiftregistrations__event=event))
)

Afterwards you can filter by annotation.

def your_dynamic_query_generator(self):
    return Q(num_shifts=0)

This solution is also cheaper on large querysets.

Hope this helps.

Need to perform Wildcard (*,?, etc) search on a string using Regex

The correct regular expression formulation of the glob expression d* is ^d, which means match anything that starts with d.

    string input = "Message";
    string pattern = @"^d";
    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

(The @ quoting is not necessary in this case, but good practice since many regexes use backslash escapes that need to be left alone, and it also indicates to the reader that this string is special).

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

Sometimes you don't have a local REF for pushing that branch back to the origin.
Try

git push origin master:master

This explicitly indicates which branch to push to (and from)

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

tooltips for Button

The title attribute is meant to give more information. It's not useful for SEO so it's never a good idea to have the same text in the title and alt which is meant to describe the image or input is vs. what it does. for instance:

<button title="prints out hello world">Sample Buttons</button>

<img title="Hms beagle in the straits of magellan" alt="HMS Beagle painting" src="hms-beagle.jpg" />

The title attribute will make a tool tip, but it will be controlled by the browser as far as where it shows up and what it looks like. If you want more control there are third party jQuery options, many css templates such as Bootstrap have built in solutions, and you can also write a simple css solution if you want. check out this w3schools solution.

How to set custom favicon in Express?

Install express-favicon middleware:

npm install express-favicon --save

Use it like this:

const favicon = require('express-favicon');
app.use(favicon(__dirname + 'favicon.ico'));

Python pip install module is not found. How to link python to pip location?

As a quick workaround, and assuming that you are on a bash-like terminal (Linux/OSX), you can try to export the PYTHONPATH environment variable:

export PYTHONPATH="${PYTHONPATH}:/usr/local/lib/python2.7/site-packages:/usr/lib/python2.7/site-packages"

For Python 2.7

npm - how to show the latest version of a package

You can see all the version of a module with npm view. eg: To list all versions of bootstrap including beta.

npm view bootstrap versions

But if the version list is very big it will truncate. An --json option will print all version including beta versions as well.

npm view bootstrap versions --json

If you want to list only the stable versions not the beta then use singular version

npm view bootstrap@* versions

Or

npm view bootstrap@* versions --json

And, if you want to see only latest version then here you go.

npm view bootstrap version

Is the order of elements in a JSON list preserved?

Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

This means that if you run either of the following:

var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
  if (animals.hasOwnProperty(animal)) {
    $('<li>').text(animal).appendTo('#animals');
  }
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
  $('<li>').text(animal).appendTo('#animals');
}

You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

Demo here and here.

Change color and appearance of drop down arrow

We have used YUI, Chosen, and are currently using the jQuery Select2 plugin: https://select2.github.io/

It's pretty robust, the arrow is just the tip of the iceberg.

As soon as stylized selects becomes a requirement, I agree with the others, go with a plugin. Don't kill yourself reinventing the wheel.

Null pointer Exception on .setOnClickListener

I too got similar error when i misplaced the code

text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

I got it working on placing the code in right order as shown below

setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
 text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Remove lines that contain certain string

You can make your code simpler and more readable like this

bad_words = ['bad', 'naughty']

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

using a Context Manager and any.

Xcode - Warning: Implicit declaration of function is invalid in C99

The function has to be declared before it's getting called. This could be done in various ways:

  • Write down the prototype in a header
    Use this if the function shall be callable from several source files. Just write your prototype
    int Fibonacci(int number);
    down in a .h file (e.g. myfunctions.h) and then #include "myfunctions.h" in the C code.

  • Move the function before it's getting called the first time
    This means, write down the function
    int Fibonacci(int number){..}
    before your main() function

  • Explicitly declare the function before it's getting called the first time
    This is the combination of the above flavors: type the prototype of the function in the C file before your main() function

As an additional note: if the function int Fibonacci(int number) shall only be used in the file where it's implemented, it shall be declared static, so that it's only visible in that translation unit.

Problems with a PHP shell script: "Could not open input file"

When you use php CLI argument -q doesn't exist.

I had the same problem when I wrote script in the Windows (eclipse) and I tried run them on Linux. Every line in file from Windows is ended by \r\n. I had to delete \r in first line that contained parser path:

When \r was deleted from first line (mcedit shown \r as ^M) script ran correctly.

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

How to connect to remote Oracle DB with PL/SQL Developer?

I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.

Next, simply add an entry like this:

MYDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
    (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
  )

You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.

Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.

If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.

What is the default root pasword for MySQL 5.7

There's so many answers out there saying to reinstall mysql or use some combo of

mysqld_safe --skip-grant-tables

and / or

UPDATE mysql.user SET Password=PASSWORD('password')

and / or something else ...

... None of it was working for me


Here's what worked for me, on Ubuntu 18.04, from the top

With special credit to this answer for digging me out of the frustration on this ...

$ sudo apt install mysql-server
$ sudo cat /etc/mysql/debian.cnf

Note the lines which read:

user     = debian-sys-maint
password = blahblahblah

Then:

$ mysql -u debian-sys-maint -p
Enter password: // type 'blahblahblah', ie. password from debian.cnf

mysql> USE mysql
mysql> SELECT User, Host, plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| User             | Host      | plugin                |
+------------------+-----------+-----------------------+
| root             | localhost | auth_socket           |
| mysql.session    | localhost | mysql_native_password |
| mysql.sys        | localhost | mysql_native_password |
| debian-sys-maint | localhost | mysql_native_password |
+------------------+-----------+-----------------------+
4 rows in set (0.00 sec)

mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> COMMIT;  // When you don't have auto-commit switched on

Either:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Or:

// For MySQL 5.7+
UPDATE mysql.user SET authentication_string=PASSWORD('new_password') where user='root';

Then:

mysql> FLUSH PRIVILEGES;
mysql> COMMIT;  // When you don't have auto-commit switched on
mysql> EXIT

$ sudo service mysql restart
$ mysql -u root -p
Enter password: // Yay! 'new_password' now works!

Open Facebook Page in Facebook App (if installed) on Android

Okay I modifed @AndroidMechanics Code, because on devices were facebook is disabled the app crashes!

here is the modifed getFacebookUrl:

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) { 
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else { 
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
         } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; 
        }
    }

The only added thing is to look if the app is disabled or not if it is disabled the app will call the webbrowser!

How to automatically generate unique id in SQL like UID12345678?

If you want to add the id manually you can use,

PadLeft() or String.Format() method.

string id;
char x='0';
id=id.PadLeft(6, x);
//Six character string id with left 0s e.g 000012

int id;
id=String.Format("{0:000000}",id);
//Integer length of 6 with the id. e.g 000012

Then you can append this with UID.

How to check if mysql database exists

Be careful when checking for existence with a like statement!

If in a series of unfortunate events your variable ends up being empty, and you end up executing this:

SHOW DATABASES like '' -- dangerous!

It will return ALL databases, thus telling the calling script that it exists since some rows were returned.

It's much safer and better practice to use an "=" equal sign to test for existence.

The correct and safe way to test for existence should be:

SHOW DATABASES WHERE `database` = 'xxxxx' -- safe way to test for existence

Note that you have to wrap the column name database with backticks, it can't use relaxed syntax in this case.

This way, if the code creating the variable 'xxxxx' returned blank, then SHOW DATABASES will not return ALL databases, but will return an empty set.

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

Just to add my own opinion, in case it might be useful to someone. This is what I used.

<div th:class="${request.read ? 'mdl-color-text--grey-800 w500' : ''}"> </div>

How to delete a line from a text file in C#?

I extended what Markus Olsson suggested, and came up with this class that adds multiple search strings and a couple of event:

public static class TextLineRemover
{
    public static void RemoveTextLines(IList<string> linesToRemove, string filename, string tempFilename)
    {
        // Initial values
        int lineNumber = 0;
        int linesRemoved = 0;
        DateTime startTime = DateTime.Now;

        // Read file
        using (var sr = new StreamReader(filename))
        {
            // Write new file
            using (var sw = new StreamWriter(tempFilename))
            {
                // Read lines
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    lineNumber++;
                    // Look for text to remove
                    if (!ContainsString(line, linesToRemove))
                    {
                        // Keep lines that does not match
                        sw.WriteLine(line);
                    }
                    else
                    {
                        // Ignore lines that DO match
                        linesRemoved++;
                        InvokeOnRemovedLine(new RemovedLineArgs { RemovedLine = line, RemovedLineNumber = lineNumber});
                    }
                }
            }
        }
        // Delete original file
        File.Delete(filename);

        // ... and put the temp file in its place.
        File.Move(tempFilename, filename);

        // Final calculations
        DateTime endTime = DateTime.Now;
        InvokeOnFinished(new FinishedArgs {LinesRemoved = linesRemoved, TotalLines = lineNumber, TotalTime = endTime.Subtract(startTime)});
    }

    private static bool ContainsString(string line, IEnumerable<string> linesToRemove)
    {
        foreach (var lineToRemove in linesToRemove)
        {
            if(line.Contains(lineToRemove))
                return true;
        }
        return false;
    }

    public static event RemovedLine OnRemovedLine;
    public static event Finished OnFinished;

    public static void InvokeOnFinished(FinishedArgs args)
    {
        Finished handler = OnFinished;
        if (handler != null) handler(null, args);
    }

    public static void InvokeOnRemovedLine(RemovedLineArgs args)
    {
        RemovedLine handler = OnRemovedLine;
        if (handler != null) handler(null, args);
    }
}

public delegate void Finished(object sender, FinishedArgs args);

public class FinishedArgs
{
    public int TotalLines { get; set; }
    public int LinesRemoved { get; set; }
    public TimeSpan TotalTime { get; set; }
}

public delegate void RemovedLine(object sender, RemovedLineArgs args);

public class RemovedLineArgs
{
    public string RemovedLine { get; set; }
    public int RemovedLineNumber { get; set; }
}

Usage:

TextLineRemover.OnRemovedLine += (o, removedLineArgs) => Console.WriteLine(string.Format("Removed \"{0}\" at line {1}", removedLineArgs.RemovedLine, removedLineArgs.RemovedLineNumber));
TextLineRemover.OnFinished += (o, finishedArgs) => Console.WriteLine(string.Format("{0} of {1} lines removed. Time used: {2}", finishedArgs.LinesRemoved, finishedArgs.TotalLines, finishedArgs.TotalTime.ToString()));
TextLineRemover.RemoveTextLines(new List<string> { "aaa", "bbb" }, fileName, fileName + ".tmp");

Why am I getting the error "connection refused" in Python? (Sockets)

host = socket.gethostname()  # Get the local machine name
port = 12397                 # Reserve a port for your service
s.bind((host,port))          # Bind to the port

I think this error may related to the DNS resolution. This sentence host = socket.gethostname() get the host name, but if the operating system can not resolve the host name to local address, you would get the error. Linux operating system can modify the /etc/hosts file, add one line in it. It looks like below( 'hostname' is which socket.gethostname() got).

127.0.0.1   hostname

When do I need to do "git pull", before or after "git add, git commit"?

Best way for me is:

  1. create new branch, checkout to it
  2. create or modify files, git add, git commit
  3. back to master branch and do pull from remote (to get latest master changes)
  4. merge newly created branch with master
  5. remove newly created branch
  6. push master to remote

Or you can push newly created branch on remote and merge there (if you do it this way, at the end you need to pull from remote master)

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Session timeout in ASP.NET

https://usefulaspandcsharp.wordpress.com/tag/session-timeout/

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" timeout="60" slidingExpiration="true" />
</authentication>

<sessionState mode="InProc" timeout="60" />

Spring @Value is not resolving to value from property file

Please note that if you have multiple application.properties files throughout your codebase, then try adding your value to the parent project's property file.

You can check your project's pom.xml file to identify what the parent project of your current project is.

Alternatively, try using environment.getProperty() instead of @Value.

How to use pip with Python 3.x alongside Python 2.x

If you don't want to have to specify the version every time you use pip:

Install pip:

$ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python3

and export the path:

$ export PATH=/Library/Frameworks/Python.framework/Versions/<version number>/bin:$PATH

Difference between <input type='submit' /> and <button type='submit'>text</button>

Not sure where you get your legends from but:

Submit button with <button>

As with:

<button type="submit">(html content)</button>

IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button> gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.

In your example, IE6 will send text to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.

Button with <input>

As with:

<input type="button" />

By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.

Normal submit button with <input>

As with:

<input type="submit" />

Like the former, but actually submits the surrounding form.

Image submit button with <input>

As with:

<input type="image" />

Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button> is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.

There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button> tag as explained above.

Angular2 - Focusing a textbox on component load

Directive for autoFocus first field

_x000D_
_x000D_
import {_x000D_
  Directive,_x000D_
  ElementRef,_x000D_
  AfterViewInit_x000D_
} from "@angular/core";_x000D_
_x000D_
@Directive({_x000D_
  selector: "[appFocusFirstEmptyInput]"_x000D_
})_x000D_
export class FocusFirstEmptyInputDirective implements AfterViewInit {_x000D_
  constructor(private el: ElementRef) {}_x000D_
  ngAfterViewInit(): void {_x000D_
    const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");_x000D_
    if (invalidControl) {_x000D_
      invalidControl.focus();_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

How do I find out what version of WordPress is running?

On the Admin Panel Dashboard, you can find a box called "Right Now". There you can see the version of the WordPress installation. I have seen this result in WordPress 3.2.1. You can also see this in version 3.7.1

WordPress Version 3.7.1

UPDATE:

In WP Version 3.8.3

WordPress Version 3.8.3

In WP Version 3.9.1 Admin Side, You can see the version by clicking the WP logo which is located at the left-top position.

WordPress Version 3.9.1

You can use yoursitename/readme.html

In the WordPress Admin Footer at the Right side, you will see the version info(Version 3.9.1).

In WP 4

You can get the WordPress version using the following code:

<?php bloginfo('version'); ?>

The below file is having all version details

wp-includes/version.php   

Update for WP 4.1.5

In WP 4.1.5, If it was the latest WP version in the footer right part, it will show the version as it is. If not, it will show the latest WP version with the link to update.

Check the below screenshot.

WP 4.1.5

Using Gradle to build a jar with dependencies

For those who need to build more than one jar from the project.

Create a function in gradle:

void jarFactory(Jar jarTask, jarName, mainClass) {
    jarTask.doFirst {
        println 'Build jar ' + jarTask.name + + ' started'
    }

    jarTask.manifest {
        attributes(
                'Main-Class':  mainClass
        )
    }
    jarTask.classifier = 'all'
    jarTask.baseName = jarName
    jarTask.from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
    {
        exclude "META-INF/*.SF"
        exclude "META-INF/*.DSA"
        exclude "META-INF/*.RSA"
    }
    jarTask.with jar 
    jarTask.doFirst {
        println 'Build jar ' + jarTask.name + ' ended'
    }
}

then call:

task makeMyJar(type: Jar) {
    jarFactory(it, 'MyJar', 'org.company.MainClass')
}

Works on gradle 5.

Jar will be placed at ./build/libs.

CSS - display: none; not working

Check following html I removed display:block from style

<div id="tfl" style="width: 187px; height: 260px; font-family: Verdana, Arial, Helvetica, sans-serif !important; background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/widget-panel.gif) #fff no-repeat; font-size: 11px; border: 1px solid #103994; border-radius: 4px; box-shadow: 2px 2px 3px 1px #ccc;">
        <div style="display: block; padding: 30px 0 15px 0;">
            <h2 style="color: rgb(36, 66, 102); text-align: center; display: block; font-size: 15px; font-family: arial; border: 0; margin-bottom: 1em; margin-top: 0; font-weight: bold !important; background: 0; padding: 0">Journey Planner</h2>
            <form action="http://journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2" id="jpForm" method="post" target="tfl" style="margin: 5px 0 0 0 !important; padding: 0 !important;">
                <input type="hidden" name="language" value="en" />
                <!-- in language = english -->
                <input type="hidden" name="execInst" value="" /><input type="hidden" name="sessionID" value="0" />
                <!-- to start a new session on JP the sessionID has to be 0 -->
                <input type="hidden" name="ptOptionsActive" value="-1" />
                <!-- all pt options are active -->
                <input type="hidden" name="place_origin" value="London" />
                <!-- London is a hidden parameter for the origin location -->
                <input type="hidden" name="place_destination" value="London" /><div style="padding-right: 15px; padding-left: 15px">
                    <input type="text" name="name_origin" style="width: 155px !important; padding: 1px" value="From" /><select style="width: 155px !important; margin: 0 !important;" name="type_origin"><option value="stop">Station or stop</option>
                        <option value="locator">Postcode</option>
                        <option value="address">Address</option>
                        <option value="poi">Place of interest</option>
                    </select>
                </div>
                <div style="margin-top: 10px; margin-bottom: 4px; padding-right: 15px; padding-left: 15px; padding-bottom: 15px; background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/panel-separator.gif) no-repeat bottom;">
                    <input type="text" name="name_destination" style="width: 100% !important; padding: 1px" value="232 Kingsbury Road (NW9)" /><select style="width: 155px !important; margin-top: 0 !important;" name="type_destination"><option value="stop">Station or stop</option>
                        <option value="locator">Postcode</option>
                        <option value="address" selected="selected">Address</option>
                        <option value="poi">Place of interest</option>
                    </select>
                </div>
                <div style="background: url(http://www.tfl.gov.uk/tfl/gettingaround/journeyplanner/banners/images/panel-separator.gif) no-repeat bottom; padding-bottom: 2px; padding-top: 2px; overflow: hidden; margin-bottom: 8px">
                    <div style="clear: both; background: url(http://www.tfl.gov.uk/tfl-global/images/options-icons.gif) no-repeat 9.5em 0; height: 30px; padding-right: 15px; padding-left: 15px"><a style="text-decoration: none; color: #113B92; font-size: 11px; white-space: nowrap; display: inline-block; padding: 4px 0 5px 0; width: 155px" target="tfl" href="http://journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2?language=en&amp;ptOptionsActive=1" onclick="javascript:document.getElementById('jpForm').ptOptionsActive.value='1';document.getElementById('jpForm').execInst.value='readOnly';document.getElementById('jpForm').submit(); return false">More options</a></div>
                </div>
                <div style="text-align: center;">
                    <input type="submit" title="Leave now" value="Leave now" style="border-style: none; background-color: #157DB9; display: inline-block; padding: 4px 11px; color: #fff; text-decoration: none; border-radius: 3px; border-radius: 3px; border-radius: 3px; box-shadow: 0 1px 3px rgba(0,0,0,0.25); box-shadow: 0 1px 3px rgba(0,0,0,0.25); box-shadow: 0 1px 3px rgba(0,0,0,0.25); text-shadow: 0 -1px 1px rgba(0,0,0,0.25); border-bottom: 1px solid rgba(0,0,0,0.25); position: relative; cursor: pointer; font: bold  13px/1 Arial,Helvetica,sans-serif; text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.4); line-height: 1;" />
                </div>
            </form>
        </div>
    </div

How can I disable the Maven Javadoc plugin from the command line?

You can use the maven.javadoc.skip property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:

<properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

or as a command-line argument: -Dmaven.javadoc.skip=true, to skip generation of the Javadocs.

How to refresh the data in a jqGrid?

Try this to reload jqGrid with new data

jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');

Excel formula to get ranking position

You can use the RANK function in Excel without necessarily sorting the data. Type =RANK(C2,$C$2:$C$7). Excel will find the relative position of the data in C2 and display the answer. Copy the formula through to C7 by dragging the small node at the right end of the cell cursor.

Aligning a button to the center

Here is what worked for me:

    <input type="submit" style="margin-left: 50%">

If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended. You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.

Telling Python to save a .txt file to a certain directory on Windows and Mac

If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()

Hope this helps you!