Programs & Examples On #Intrusion detection

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Since late 2012, it is usually under /usr/share/tomcat7.

Prior to that, it was usually found under /opt/tomcat7.

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

Get JSON object from URL

Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
    return false;
}

$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
    return false;
}

utf-8 special characters not displaying

The problem is because your file are not with the same encoding. First run the following command in all your files:

file -i filename.* 

In order to fix the problem you have to change all your files to uft-8. You can do it with the command iconv:

iconv -f fromcode -t tocode filename > newfilename

Example:

iconv -f iso-8859-1 -t utf-8 index.html > fixed/index.html

After this you can run file -i fixedx/index.html and you will see that your file is now in uft-8

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

How to allow download of .json file with ASP.NET

Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config and I was able to add in the correct "mime map" there.

Change keystore password from no password to a non blank password

On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps

enter image description here

Regex AND operator

It is impossible for both (?=foo) and (?=baz) to match at the same time. It would require the next character to be both f and b simultaneously which is impossible.

Perhaps you want this instead:

(?=.*foo)(?=.*baz)

This says that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).

Is it worth using Python's re.compile?

Mostly, there is little difference whether you use re.compile or not. Internally, all of the functions are implemented in terms of a compile step:

def match(pattern, string, flags=0):
    return _compile(pattern, flags).match(string)

def fullmatch(pattern, string, flags=0):
    return _compile(pattern, flags).fullmatch(string)

def search(pattern, string, flags=0):
    return _compile(pattern, flags).search(string)

def sub(pattern, repl, string, count=0, flags=0):
    return _compile(pattern, flags).sub(repl, string, count)

def subn(pattern, repl, string, count=0, flags=0):
    return _compile(pattern, flags).subn(repl, string, count)

def split(pattern, string, maxsplit=0, flags=0):
    return _compile(pattern, flags).split(string, maxsplit)

def findall(pattern, string, flags=0):
    return _compile(pattern, flags).findall(string)

def finditer(pattern, string, flags=0):
    return _compile(pattern, flags).finditer(string)

In addition, re.compile() bypasses the extra indirection and caching logic:

_cache = {}

_pattern_type = type(sre_compile.compile("", 0))

_MAXCACHE = 512
def _compile(pattern, flags):
    # internal: compile pattern
    try:
        p, loc = _cache[type(pattern), pattern, flags]
        if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE):
            return p
    except KeyError:
        pass
    if isinstance(pattern, _pattern_type):
        if flags:
            raise ValueError(
                "cannot process flags argument with a compiled pattern")
        return pattern
    if not sre_compile.isstring(pattern):
        raise TypeError("first argument must be string or compiled pattern")
    p = sre_compile.compile(pattern, flags)
    if not (flags & DEBUG):
        if len(_cache) >= _MAXCACHE:
            _cache.clear()
        if p.flags & LOCALE:
            if not _locale:
                return p
            loc = _locale.setlocale(_locale.LC_CTYPE)
        else:
            loc = None
        _cache[type(pattern), pattern, flags] = p, loc
    return p

In addition to the small speed benefit from using re.compile, people also like the readability that comes from naming potentially complex pattern specifications and separating them from the business logic where there are applied:

#### Patterns ############################################################
number_pattern = re.compile(r'\d+(\.\d*)?')    # Integer or decimal number
assign_pattern = re.compile(r':=')             # Assignment operator
identifier_pattern = re.compile(r'[A-Za-z]+')  # Identifiers
whitespace_pattern = re.compile(r'[\t ]+')     # Spaces and tabs

#### Applications ########################################################

if whitespace_pattern.match(s): business_logic_rule_1()
if assign_pattern.match(s): business_logic_rule_2()

Note, one other respondent incorrectly believed that pyc files stored compiled patterns directly; however, in reality they are rebuilt each time when the PYC is loaded:

>>> from dis import dis
>>> with open('tmp.pyc', 'rb') as f:
        f.read(8)
        dis(marshal.load(f))

  1           0 LOAD_CONST               0 (-1)
              3 LOAD_CONST               1 (None)
              6 IMPORT_NAME              0 (re)
              9 STORE_NAME               0 (re)

  3          12 LOAD_NAME                0 (re)
             15 LOAD_ATTR                1 (compile)
             18 LOAD_CONST               2 ('[aeiou]{2,5}')
             21 CALL_FUNCTION            1
             24 STORE_NAME               2 (lc_vowels)
             27 LOAD_CONST               1 (None)
             30 RETURN_VALUE

The above disassembly comes from the PYC file for a tmp.py containing:

import re
lc_vowels = re.compile(r'[aeiou]{2,5}')

Converting LastLogon to DateTime format

Get-ADUser -Filter {Enabled -eq $true} -Properties Name,Manager,LastLogon | 
Select-Object Name,Manager,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

How do I programmatically "restart" an Android app?

Mikepenz's Alternative Answer needed some changes in my case. https://stackoverflow.com/a/22345538/12021422 Major Credits to Mikepenz's Answer which I could modify.

Here is the Plug and Play static function that worked for me.

Just pass the Context of Application and this function will handle the restart.

    public static void doRestart(Context c) {
        try {
            // check if the context is given
            if (c != null) {
                // fetch the package manager so we can get the default launch activity
                // (you can replace this intent with any other activity if you want
                PackageManager pm = c.getPackageManager();
                // check if we got the PackageManager
                if (pm != null) {
                    // create the intent with the default start activity for your application
                    Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
                    if (mStartActivity != null) {
                        mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        
                        c.getApplicationContext().startActivity(mStartActivity);
                        // kill the application
                        System.exit(0);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("restart", "Could not Restart");
        }
    }

How do I create a GUI for a windows application using C++?

I have used wxWidgets for small project and I loved it. Qt is another good choice but for commercial use you would probably need to buy a licence. If you write in C++ don't use Win32 API as you will end up making it object oriented. This is not easy and time consuming. Also Win32 API has too many macros and feels over complicated for what it offers.

Twitter Bootstrap carousel different height images cause bouncing arrows

The solution given earlier leads to a situation where images may be too small for the carousel box. A proper solution to the problem of bumping controls is to override Bootstraps CSS.

Original code:

.carousel-control {
top: 40%;
}

Override the variable with a fixed value inside your own stylesheet (300px worked in my design):

.carousel-control {
top: 300px;
}

Hopefully this will solve your problem.

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

ClassNotFoundException: org.slf4j.LoggerFactory

Add the following JARs to the build path or lib folder of the project:

  1. slf4j-api-1.7.2.jar
  2. slf4j-jdk14-1.7.2.jar

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions

CSS word-wrapping in div

I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

Unix shell script find out which directory the script file resides?

That should do the trick:

echo `pwd`/`dirname $0`

It might look ugly depending on how it was invoked and the cwd but should get you where you need to go (or you can tweak the string if you care how it looks).

Check if string is neither empty nor space in shell script

To check if a string is empty or contains only whitespace you could use:

shopt -s extglob  # more powerful pattern matching

if [ -n "${str##+([[:space:]])}" ]; then
    echo '$str is not null or space'
fi

See Shell Parameter Expansion and Pattern Matching in the Bash Manual.

How to check variable type at runtime in Go language

The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}. If you use a concrete type it will fail.

An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect package. Chaining TypeOf(x).Kind() together you can get a reflect.Kind value which is a uint type: http://golang.org/pkg/reflect/#Kind

You can then do checks for types outside of a switch block, like so:

import (
    "fmt"
    "reflect"
)

// ....

x := 42
y := float32(43.3)
z := "hello"

xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()

fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)

if xt == reflect.Int {
    println(">> x is int")
}
if yt == reflect.Float32 {
    println(">> y is float32")
}
if zt == reflect.String {
    println(">> z is string")
}

Which prints outs:

reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string

Again, this is probably not the preferred way to do it, but it's good to know alternative options.

Use of Java's Collections.singletonList()?

Here's one view on the singleton methods:

I have found these various "singleton" methods to be useful for passing a single value to an API that requires a collection of that value. Of course, this works best when the code processing the passed-in value does not need to add to the collection.

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

Drag and Drop did not work on my system...

I found a blogpost which describes how you install it with adb:

adb push Genymotion-ARM-Translation_v1.1.zip /sdcard/Download/Genymotion-ARM-Translation_v1.1.zip

adb push gapps-jb-yyyymmdd-signed.zip /sdcard/Download/gapps.zip

adb shell flash-archive.sh /sdcard/Download/Genymotion-ARM-Translation_v1.1.zip

adb reboot

adb shell flash-archive.sh /sdcard/Download/gapps.zip

adb reboot

Set initially selected item in Select list in Angular2

If you use

<select [ngModel]="object">
    <option *ngFor="let object of objects" [ngValue]="object">{{object.name}}</option>
</select>

You need to set the property object in you components class to the item from objects that you want to have pre-selected.

class MyComponent {
  object;
  objects = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
  constructor() {
    this.object = this.objects[1];
  }
}

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

jQuery: value.attr is not a function

You can also use jQuery('.class-name').attr("href"), in my case it works better.

Here more information: "jQuery(...)" instead of "$(...)"

How to check if a URL exists or returns 404 with Java?

Use HttpUrlConnection by calling openConnection() on your URL object.

getResponseCode() will give you the HTTP response once you've read from the connection.

e.g.

   URL u = new URL("http://www.example.com/"); 
   HttpURLConnection huc = (HttpURLConnection)u.openConnection(); 
   huc.setRequestMethod("GET"); 
   huc.connect() ; 
   OutputStream os = huc.getOutputStream(); 
   int code = huc.getResponseCode(); 

(not tested)

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

I am using Debian 10 buster and try download a file with youtube-dl and get this error: sudo youtube-dl -k https://youtu.be/uscis0CnDjk

[youtube] uscis0CnDjk: Downloading webpage ERROR: Unable to download webpage: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)> (caused by URLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)')))

Certificates with python2 and python3.8 are installed correctly, but i persistent receive the same error. finally (which is not the best solution, but works for me was to eliminate the certificate check as it is given as an option in youtube-dl) whith this command sudo youtube-dl -k --no-check-certificate https://youtu.be/uscis0CnDjk

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Differences:

  1. The return type of RenderPartial is void, where as Partial returns MvcHtmlString

  2. Syntax for invoking Partial() and RenderPartial() methods in Razor views

    @Html.Partial("PartialViewName")
    @{ Html.RenderPartial("PartialViewName"); }

  3. Syntax for invoking Partial() and RenderPartial() methods in webform views

[%: Html.Partial("PartialViewName") %]
[% Html.RenderPartial("PartialViewName"); %]

The following are the 2 common interview questions related to Partial() and RenderPartial() When would you use Partial() over RenderPartial() and vice versa?

The main difference is that RenderPartial() returns void and the output will be written directly to the output stream, where as the Partial() method returns MvcHtmlString, which can be assigned to a variable and manipulate it if required. So, when there is a need to assign the output to a variable for manipulating it, then use Partial(), else use RenderPartial().

Which one is better for performance?

From a performance perspective, rendering directly to the output stream is better. RenderPartial() does exactly the same thing and is better for performance over Partial().

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Can I have two JavaScript onclick events in one element?

You can attach a handler which would call as many others as you like:

<a href="#blah" id="myLink"/>

<script type="text/javascript">

function myOtherFunction() {
//do stuff...
}

document.getElementById( 'myLink' ).onclick = function() {
   //do stuff...
   myOtherFunction();
};

</script>

Ignore invalid self-signed ssl certificate in node.js with https.request?

You can also create a request instance with default options:

require('request').defaults({ rejectUnauthorized: false })

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

changing textbox border colour using javascript

If the users enter an incorrect value, apply a 1px red color border to the input field:

document.getElementById('fName').style.border ="1px solid red";

If the user enters a correct value, remove the border from the input field:

document.getElementById('fName').style.border ="";

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

PHP Try and Catch for SQL Insert

You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:

// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;

// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}

function my_mysql_query($query, $conn=false) {
    $res = mysql_query($query, $conn);
    if (!$res) {
        $errno = mysql_errno($conn);
        $error = mysql_error($conn);
        switch ($errno) {
        case MYSQL_DUPLICATE_KEY_ENTRY:
            throw new MySQLDuplicateKeyException($error, $errno);
            break;
        default:
            throw MySQLException($error, $errno);
            break;
        }
    }
    // ...
    // doing something
    // ...
    if ($something_is_wrong) {
        throw new Exception("Logic exception while performing query result processing");
    }

}

try {
    mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
    // duplicate entry exception
    $e->getMessage();
}
catch (MySQLException $e) {
    // other mysql exception (not duplicate key entry)
    $e->getMessage();
}
catch (Exception $e) {
    // not a MySQL exception
    $e->getMessage();
}

How to delete a row from GridView?

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Default3 : System.Web.UI.Page
{
   DataTable dt = new DataTable();
    DataSet Gds = new DataSet();
   // DataColumn colm1 = new DataColumn();
   //DataColumn colm2 = new DataColumn();

    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("ExpId", typeof(int));
        dt.Columns.Add("FirstName", typeof(string));

    }


    protected void BtnLoad_Click(object sender, EventArgs e)
    {
        //   gvLoad is Grid View Id
        if (gvLoad.Rows.Count == 0)
        {
            Gds.Tables.Add(tblLoad());
        }
        else
        {
            dt = tblGridRow();
            dt.Rows.Add(tblRow());
            Gds.Tables.Add(dt);
        }
        gvLoad.DataSource = Gds;
        gvLoad.DataBind();
    }

    protected DataTable tblLoad()
    {
        dt.Rows.Add(tblRow());
        return dt;
    }
    protected DataRow tblRow()
    {
        DataRow dr;
        dr = dt.NewRow();
        dr["Exp Id"] = Convert.ToInt16(txtId.Text);
        dr["First Name"] = Convert.ToString(txtName.Text);
        return dr;
    }

    protected DataTable tblGridRow()
    {
        DataRow dr;
        for (int i = 0; i < gvLoad.Rows.Count; i++)
        {
            if (gvLoad.Rows[i].Cells[0].Text != null)
            {

                dr = dt.NewRow();
                dr["Exp Id"] = gvLoad.Rows[i].Cells[1].Text.ToString();
                dr["First Name"] = gvLoad.Rows[i].Cells[2].Text.ToString();
                dt.Rows.Add(dr);

            }

        }
        return dt;
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        dt = tblGridRow();
        dt.Rows.Add(tblRow());
        Session["tab"] = dt;
        // Response.Redirect("Default.aspx");
    }

    protected void gvLoad_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        dt = tblGridRow();
        dt.Rows.RemoveAt(e.RowIndex);
        gvLoad.DataSource = dt;
        gvLoad.DataBind();
    }
}

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

When does Java's Thread.sleep throw InterruptedException?

The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException. It's well worth reading and digesting.

Java code for getting current time

Try this way, more efficient and compatible:

SimpleDateFormat time_formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
String current_time_str = time_formatter.format(System.currentTimeMillis());
//Log.i("test", "current_time_str:" + current_time_str);

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

Parsing json and searching through it

Seems there's a typo (missing colon) in the JSON dict provided by jro.

The correct syntax would be:

jdata = json.load('{"uri": "http:", "foo": "bar"}')

This cleared it up for me when playing with the code.

Scala how can I count the number of occurrences in a list

Here is a pretty easy way to do it.

val data = List("it", "was", "the", "best", "of", "times", "it", "was", 
                 "the", "worst", "of", "times")
data.foldLeft(Map[String,Int]().withDefaultValue(0)){
  case (acc, letter) =>
    acc + (letter -> (1 + acc(letter)))
}
// => Map(worst -> 1, best -> 1, it -> 2, was -> 2, times -> 2, of -> 2, the -> 2)

How to get elements with multiple classes

It's actually very similar to jQuery:

document.getElementsByClassName('class1 class2')

MDN Doc getElementsByClassName

One liner for If string is not null or empty else

You can achieve this with pattern matching with the switch expression in C#8/9

FooTextBox.Text = strFoo switch
{
    { Length: >0 } s => s, // If the length of the string is greater than 0 
    _ => "0" // Anything else
};

Get Path from another app (WhatsApp)

you can try to this , then you get a bitmap of selected image and then you can easily find it's native path from Device Default Gallery.

Bitmap roughBitmap= null;
    try {
    // Works with content://, file://, or android.resource:// URIs
    InputStream inputStream =
    getContentResolver().openInputStream(uri);
    roughBitmap= BitmapFactory.decodeStream(inputStream);

    // calc exact destination size
    Matrix m = new Matrix();
    RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
    RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
    m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
    float[] values = new float[9];
    m.GetValues(values);


    // resize bitmap if needed
    Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);

    string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
    var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
    Java.IO.File file = new Java.IO.File(sdCardPath);
    if (!file.Exists())
    {
        file.Mkdir();
    }
    var filePath = System.IO.Path.Combine(sdCardPath, name);
    } catch (FileNotFoundException e) {
    // Inform the user that things have gone horribly wrong
    }

Adding a right click menu to an item

This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.

  1. Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.

  2. You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
    switch (e.Button)
        {
            case MouseButtons.Right:
            {
                rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
            }
            break;
        }
    }
    
  3. Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):

    this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
    
  4. All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.

This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.

How can I check if a date is the same day as datetime.today()?

You can set the hours, minutes, seconds and microseconds to whatever you like

datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()s of the times

Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace() once vs hundreds of calls to date()

How do I control how Emacs makes backup files?

Another way of configuring backup options is via the Customize interface. Enter:

M-x customize-group

And then at the Customize group: prompt enter backup.

If you scroll to the bottom of the buffer you'll see Backup Directory Alist. Click Show Value and set the first entry of the list as follows:

Regexp matching filename: .*
Backup directory name: /path/to/your/backup/dir

Alternatively, you can turn backups off my setting Make Backup Files to off.

If you don't want Emacs to automatically edit your .emacs file you'll want to set up a customisations file.

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

Finding current executable's path without /proc/self/exe

Making this work reliably across platforms requires using #ifdef statements.

The below code finds the executable's path in Windows, Linux, MacOS, Solaris or FreeBSD (although FreeBSD is untested). It uses Boost 1.55.0 (or later) to simplify the code, but it's easy enough to remove if you want. Just use defines like _MSC_VER and __linux as the OS and compiler require.

#include <string>
#include <boost/predef/os.h>

#if (BOOST_OS_WINDOWS)
#  include <stdlib.h>
#elif (BOOST_OS_SOLARIS)
#  include <stdlib.h>
#  include <limits.h>
#elif (BOOST_OS_LINUX)
#  include <unistd.h>
#  include <limits.h>
#elif (BOOST_OS_MACOS)
#  include <mach-o/dyld.h>
#elif (BOOST_OS_BSD_FREE)
#  include <sys/types.h>
#  include <sys/sysctl.h>
#endif

/*
 * Returns the full path to the currently running executable,
 * or an empty string in case of failure.
 */
std::string getExecutablePath() {
    #if (BOOST_OS_WINDOWS)
        char *exePath;
        if (_get_pgmptr(&exePath) != 0)
            exePath = "";
    #elif (BOOST_OS_SOLARIS)
        char exePath[PATH_MAX];
        if (realpath(getexecname(), exePath) == NULL)
            exePath[0] = '\0';
    #elif (BOOST_OS_LINUX)
        char exePath[PATH_MAX];
        ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath));
        if (len == -1 || len == sizeof(exePath))
            len = 0;
        exePath[len] = '\0';
    #elif (BOOST_OS_MACOS)
        char exePath[PATH_MAX];
        uint32_t len = sizeof(exePath);
        if (_NSGetExecutablePath(exePath, &len) != 0) {
            exePath[0] = '\0'; // buffer too small (!)
        } else {
            // resolve symlinks, ., .. if possible
            char *canonicalPath = realpath(exePath, NULL);
            if (canonicalPath != NULL) {
                strncpy(exePath,canonicalPath,len);
                free(canonicalPath);
            }
        }
    #elif (BOOST_OS_BSD_FREE)
        char exePath[2048];
        int mib[4];  mib[0] = CTL_KERN;  mib[1] = KERN_PROC;  mib[2] = KERN_PROC_PATHNAME;  mib[3] = -1;
        size_t len = sizeof(exePath);
        if (sysctl(mib, 4, exePath, &len, NULL, 0) != 0)
            exePath[0] = '\0';
    #endif
        return std::string(exePath);
}

The above version returns full paths including the executable name. If instead you want the path without the executable name, #include boost/filesystem.hpp> and change the return statement to:

return strlen(exePath)>0 ? boost::filesystem::path(exePath).remove_filename().make_preferred().string() : std::string();

Twig for loop for arrays with keys

I found the answer :

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% endfor %}

How to get the path of the batch script in Windows?

You can use %~dp0, d means the drive only, p means the path only, 0 is the argument for the full filename of the batch file.

For example if the file path was C:\Users\Oliver\Desktop\example.bat then the argument would equal C:\Users\Oliver\Desktop\, also you can use the command set cpath=%~dp0 && set cpath=%cpath:~0,-1% and use the %cpath% variable to remove the trailing slash.

How to check if a char is equal to an empty space?

Character.isSpaceChar(c) || Character.isWhitespace(c) worked for me.

jQuery return ajax result into outside variable

This is all you need to do:

var myVariable;

$.ajax({
    'async': false,
    'type': "POST",
    'global': false,
    'dataType': 'html',
    'url': "ajax.php?first",
    'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
    'success': function (data) {
        myVariable = data;
    }
});

NOTE: Use of "async" has been depreciated. See https://xhr.spec.whatwg.org/.

Git merge with force overwrite

Not really related to this answer, but I'd ditch git pull, which just runs git fetch followed by git merge. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:

git fetch origin   # update all our origin/* remote-tracking branches

git checkout demo         # if needed -- your example assumes you're on it
git merge origin/demo     # if needed -- see below

git checkout master
git merge origin/master

git merge -X theirs demo   # but see below

git push origin master     # again, see below

Controlling the trickiest merge

The most interesting part here is git merge -X theirs. As root545 noted, the -X options are passed on to the merge strategy, and both the default recursive strategy and the alternative resolve strategy take -X ours or -X theirs (one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.

A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours) version and the other (also called remote or --theirs) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.

These changes are what you see in git diff output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).

If the changes happen on different lines—for instance, we change color to colour on line 17 and they change fred to barney on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.

The -X ours and -X theirs options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo (theirs) into master (ours) and want the changes from demo, you would want -X theirs.

Blindly applying -X, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:

int i;

In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X option is no help here since the changes are on different lines.

If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit to the git merge command. We'll leave the details for all of this to other postings.


1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X arguments.


Doing fewer merges and/or smarter merges and/or using rebase

There are three merges in both of our command sequences. The first is to bring origin/demo into the local demo (yours uses git pull which, if your Git is very old, will fail to update origin/demo but will produce the same end result). The second is to bring origin/master into master.

It's not clear to me who is updating demo and/or master. If you write your own code on your own demo branch, and others are writing code and pushing it to the demo branch on origin, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase instead. On the other hand, if you never do any of your own commits on demo, you don't even need a demo branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo: this will fast-forward your demo to match the updated origin/demo if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).

This same logic applies to master, although you are doing the merge on master, so you definitely do need a master. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master.

Let's say that you never do your own commits on demo. In this case we can ditch the name demo entirely:

git fetch origin   # update origin/*

git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"

git merge -X theirs origin/demo || die "complex merge conflict"

git push origin master

If you are doing your own demo branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).

Test if registry value exists

The -not test should fire if a property doesn't exist:

$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
   New-ItemProperty -Path $regkey -Name $name -Value "X"
}

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Hey, we just did a global find-replace, changing Required=" to jRequired=". Then you just change it in the jquery code as well (jquery_helper.js -> Function ValidateControls). Now our validation continues as before and Chrome leaves us alone! :)

Send JSON data from Javascript to PHP?

You can easily convert object into urlencoded string:

function objToUrlEncode(obj, keys) {
    let str = "";
    keys = keys || [];
    for (let key in obj) {
        keys.push(key);
        if (typeof (obj[key]) === 'object') {
            str += objToUrlEncode(obj[key], keys);
        } else {
            for (let i in keys) {
                if (i == 0) str += keys[0];
                else str += `[${keys[i]}]`
            }
            str += `=${obj[key]}&`;
            keys.pop();
        }
    }
    return str;
}

console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));

// key=value&obj[obj_key]=obj_value&

C# Public Enums in Classes

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

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

public class Card
{
}

To Specify:

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

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

Place a button right aligned

Another possibility is to use an absolute positioning oriented to the right. You can do it this way:

style="position: absolute; right: 0;"

AngularJS $location not changing the path

setTimeout(function() { $location.path("/abc"); },0);

it should solve your problem.

PHP - Fatal error: Unsupported operand types

$total_ratings is an array, which you can't use for a division.

From above:

$total_ratings = mysqli_fetch_array($result);

How does the "final" keyword in Java work? (I can still modify an object.)

Above all are correct. Further if you do not want others to create sub classes from your class, then declare your class as final. Then it becomes the leaf level of your class tree hierarchy that no one can extend it further. It is a good practice to avoid huge hierarchy of classes.

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

Switch on ranges of integers in JavaScript

Here is another way I figured it out:

const x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

How is a JavaScript hash map implemented?

I was running into the problem where i had the json with some common keys. I wanted to group all the values having the same key. After some surfing I found hashmap package. Which is really helpful.

To group the element with the same key, I used multi(key:*, value:*, key2:*, value2:*, ...).

This package is somewhat similar to Java Hashmap collection, but not as powerful as Java Hashmap.

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

How to increment an iterator by 2?

We can use both std::advance as well as std::next, but there's a difference between the two.

advance modifies its argument and returns nothing. So it can be used as:

vector<int> v;
v.push_back(1);
v.push_back(2);
auto itr = v.begin();
advance(itr, 1);          //modifies the itr
cout << *itr<<endl        //prints 2

next returns a modified copy of the iterator:

vector<int> v;
v.push_back(1);
v.push_back(2);
cout << *next(v.begin(), 1) << endl;    //prints 2

Difference between javacore, thread dump and heap dump in Websphere

Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.

Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.

Is there a way to return a list of all the image file names from a folder using only Javascript?

IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just .hide() them all with JQuery or display: none; in CSS.

Also you can perform prefetching, like this:

<link rel="prefetch" href="imagefolder/clouds.jpg" />

That way you don't have to hide it and still can extract the path to the image.

Should a function have only one return statement?

This is probably an unusual perspective, but I think that anyone who believes that multiple return statements are to be favoured has never had to use a debugger on a microprocessor that supports only 4 hardware breakpoints. ;-)

While the issues of "arrow code" are completely correct, one issue that seems to go away when using multiple return statements is in the situation where you are using a debugger. You have no convenient catch-all position to put a breakpoint to guarantee that you're going to see the exit and hence the return condition.

RegEx match open tags except XHTML self-contained tags

Here's the solution:

<?php
// here's the pattern:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*(\/>|>)/';

// a string to parse:
$string = 'Hello, try clicking <a href="#paragraph">here</a>
    <br/>and check out.<hr />
    <h2>title</h2>
    <a name ="paragraph" rel= "I\'m an anchor"></a>
    Fine, <span title=\'highlight the "punch"\'>thanks<span>.
    <div class = "clear"></div>
    <br>';

// let's get the occurrences:
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);

// print the result:
print_r($matches[0]);
?>

To test it deeply, I entered in the string auto-closing tags like:

  1. <hr />
  2. <br/>
  3. <br>

I also entered tags with:

  1. one attribute
  2. more than one attribute
  3. attributes which value is bound either into single quotes or into double quotes
  4. attributes containing single quotes when the delimiter is a double quote and vice versa
  5. "unpretty" attributes with a space before the "=" symbol, after it and both before and after it.

Should you find something which does not work in the proof of concept above, I am available in analyzing the code to improve my skills.

<EDIT> I forgot that the question from the user was to avoid the parsing of self-closing tags. In this case the pattern is simpler, turning into this:

$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>/';

The user @ridgerunner noticed that the pattern does not allow unquoted attributes or attributes with no value. In this case a fine tuning brings us the following pattern:

$pattern = '/<(\w+)(\s+(\w+)(\s*\=\s*(\'|"|)(.*?)\\5\s*)?)*\s*>/';

</EDIT>

Understanding the pattern

If someone is interested in learning more about the pattern, I provide some line:

  1. the first sub-expression (\w+) matches the tag name
  2. the second sub-expression contains the pattern of an attribute. It is composed by:
    1. one or more whitespaces \s+
    2. the name of the attribute (\w+)
    3. zero or more whitespaces \s* (it is possible or not, leaving blanks here)
    4. the "=" symbol
    5. again, zero or more whitespaces
    6. the delimiter of the attribute value, a single or double quote ('|"). In the pattern, the single quote is escaped because it coincides with the PHP string delimiter. This sub-expression is captured with the parentheses so it can be referenced again to parse the closure of the attribute, that's why it is very important.
    7. the value of the attribute, matched by almost anything: (.*?); in this specific syntax, using the greedy match (the question mark after the asterisk) the RegExp engine enables a "look-ahead"-like operator, which matches anything but what follows this sub-expression
    8. here comes the fun: the \4 part is a backreference operator, which refers to a sub-expression defined before in the pattern, in this case, I am referring to the fourth sub-expression, which is the first attribute delimiter found
    9. zero or more whitespaces \s*
    10. the attribute sub-expression ends here, with the specification of zero or more possible occurrences, given by the asterisk.
  3. Then, since a tag may end with a whitespace before the ">" symbol, zero or more whitespaces are matched with the \s* subpattern.
  4. The tag to match may end with a simple ">" symbol, or a possible XHTML closure, which makes use of the slash before it: (/>|>). The slash is, of course, escaped since it coincides with the regular expression delimiter.

Small tip: to better analyze this code it is necessary looking at the source code generated since I did not provide any HTML special characters escaping.

Batch Renaming of Files in a Directory

If you don't mind using regular expressions, then this function would give you much power in renaming files:

import re, glob, os

def renamer(files, pattern, replacement):
    for pathname in glob.glob(files):
        basename= os.path.basename(pathname)
        new_filename= re.sub(pattern, replacement, basename)
        if new_filename != basename:
            os.rename(
              pathname,
              os.path.join(os.path.dirname(pathname), new_filename))

So in your example, you could do (assuming it's the current directory where the files are):

renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")

but you could also roll back to the initial filenames:

renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")

and more.

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);

PHP - Session destroy after closing browser

There's one more "hack" by using HTTP Referer (we asume that browser window was closed current referer's domain name and curent page's domain name do not match):

session_start();
$_SESSION['somevariable'] = 'somevalue';

if(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST) != $_SERVER["SERVER_NAME"]){
    session_destroy();
}

This also has some drawbacks, but it helped me few times.

img src SVG changing the styles with CSS

The answer from @Praveen is solid.

I couldn't get it to respond in my work, so I made a jquery hover function for it.

CSS

.svg path {
   transition:0.3s all !important;
}

JS / JQuery

// code from above wrapped into a function
replaceSVG();

// hover function
// hover over an element, and find the SVG that you want to change
$('.element').hover(function() {
    var el = $(this);
    var svg = el.find('svg path');
    svg.attr('fill', '#CCC');
}, function() {
    var el = $(this);
    var svg = el.find('svg path');
    svg.attr('fill', '#3A3A3A');
});

What is a "thread" (really)?

A thread is a set of (CPU)instructions which can be executed.

But in order to better understand the thread we have to have some knowledge about how the CPU and RAM works.

A computer follows instructions and manipulates data. RAM is the place where those instructions and data on which the CPU will operate on, are saved. Within the CPU some memory cells called registers exist. Those registers contain numbers on which the CPU performs simple mathematical operations. An example can be the following: “Add the number in register #3 to the number in register #1.”.

The collection of all operations a CPU can do is called instruction set. Each operation in the instruction set is assigned a number, so computer code is essentially a sequence of numbers representing CPU operations. These operations are stored as numbers in the RAM.

The CPU works in a never-ending loop, always fetching and executing an instruction from memory. At the core of this cycle is the PC register, or Program Counter. It's a special register that stores the memory address of the next instruction to be executed.

The CPU will:  

  1. Fetch the instruction at the memory address given by the PC,
  2. Increment the PC by 1,
  3. Execute the instruction,
  4. Go back to step 1.

The CPU can be instructed to write a new value to the PC, causing the execution to branch, or "jump" to somewhere else in the memory. And this branching can be conditional. For instance, a CPU instruction could say: "set PC to address #200 if register #1 equals zero". This allows computers to execute stuff like this:

if  x = 0
    compute_this()
else
    compute_that()

Resources taken from Computer Science Distilled were used.

How to create a Java cron job

First I would recommend you always refer docs before you start a new thing.

We have SchedulerFactory which schedules Job based on the Cron Expression given to it.

    //Create instance of factory
    SchedulerFactory schedulerFactory=new StdSchedulerFactory();

    //Get schedular
    Scheduler scheduler= schedulerFactory.getScheduler();

    //Create JobDetail object specifying which Job you want to execute
    JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);

    //Associate Trigger to the Job
    CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");

    //Pass JobDetail and trigger dependencies to schedular
    scheduler.scheduleJob(jobDetail,trigger);

    //Start schedular
    scheduler.start();

MyJob.class

public class MyJob implements Job{

      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                 System.out.println("My Logic");
        }

    }

Batch script: how to check for admin rights

Alternative: Use an external utility that is designed for this purpose, e.g., IsAdmin.exe (unrestricted freeware).

Exit codes:

0 - Current user not member of Administrators group

1 - Current user member of Administrators and running elevated

2 - Current user member of Administrators, but not running elevated

how to get current month and year

If you have following two labels:

<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />

Than you can use following code just need to set the Text Property for these labels like:

MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();

Looping over a list in Python

Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.

list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
  change = list1[i] - list1[i-1]
  list2.append(change)

Note that while len(list1) is 11 (elements), len(list2) will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1

How can I find the latitude and longitude from address?

An answer to Kandha problem above :

It throws the "java.io.IOException service not available" i already gave those permission and include the library...i can get map view...it throws that IOException at geocoder...

I just added a catch IOException after the try and it solved the problem

    catch(IOException ioEx){
        return null;
    }

Setting Windows PATH for Postgres tools

configuring postreSQL PATH variable on Windows 7

I encountered this issue too. I'm using Git Bash, hence the Unix-style $ prompt on Windows.

$ rails db
Couldn't find database client: psql, psql.exe.  Check your $PATH and try again.

Here's what I did:

In Windows 7, navigate to:

Control Panel
  All Control Panel Items
    System
      Advanced System Settings
        Environment Variables
          from the System Variables box select "PATH"
              Edit...

Then append this string to the existing PATH Variable Value:

;C:\Program Files\PostgreSQL\9.2\bin

and click "OK" three times to exit the menus.

Now, close the console and restart it.

Navigate back to the directory of your Rails app. In my case, this is accomplished with:

$ cd rails_projects/sample_app

Then, try again:

$ rails db

sources:

How do I put PostgreSQL /bin directory on my path in Windows?

http://railscasts.com/episodes/342-migrating-to-postgresql?view=asciicast

What is difference between functional and imperative programming languages?

There seem to be many opinions about what functional programs and what imperative programs are.

I think functional programs can most easily be described as "lazy evaluation" oriented. Instead of having a program counter iterate through instructions, the language by design takes a recursive approach.

In a functional language, the evaluation of a function would start at the return statement and backtrack, until it eventually reaches a value. This has far reaching consequences with regards to the language syntax.

Imperative: Shipping the computer around

Below, I've tried to illustrate it by using a post office analogy. The imperative language would be mailing the computer around to different algorithms, and then have the computer returned with a result.

Functional: Shipping recipes around

The functional language would be sending recipes around, and when you need a result - the computer would start processing the recipes.

This way, you ensure that you don't waste too many CPU cycles doing work that is never used to calculate the result.

When you call a function in a functional language, the return value is a recipe that is built up of recipes which in turn is built of recipes. These recipes are actually what's known as closures.

// helper function, to illustrate the point
function unwrap(val) {
  while (typeof val === "function") val = val();
  return val;
}

function inc(val) {
  return function() { unwrap(val) + 1 };
}

function dec(val) {
  return function() { unwrap(val) - 1 };
}

function add(val1, val2) {
  return function() { unwrap(val1) + unwrap(val2) }
}

// lets "calculate" something

let thirteen = inc(inc(inc(10)))
let twentyFive = dec(add(thirteen, thirteen))

// MAGIC! The computer still has not calculated anything.
// 'thirteen' is simply a recipe that will provide us with the value 13

// lets compose a new function

let doubler = function(val) {
  return add(val, val);
}

// more modern syntax, but it's the same:
let alternativeDoubler = (val) => add(val, val)

// another function
let doublerMinusOne = (val) => dec(add(val, val));

// Will this be calculating anything?

let twentyFive = doubler(thirteen)

// no, nothing has been calculated. If we need the value, we have to unwrap it:
console.log(unwrap(thirteen)); // 26

The unwrap function will evaluate all the functions to the point of having a scalar value.

Language Design Consequences

Some nice features in imperative languages, are impossible in functional languages. For example the value++ expression, which in functional languages would be difficult to evaluate. Functional languages make constraints on how the syntax must be, because of the way they are evaluated.

On the other hand, with imperative languages can borrow great ideas from functional languages and become hybrids.

Functional languages have great difficulty with unary operators like for example ++ to increment a value. The reason for this difficulty is not obvious, unless you understand that functional languages are evaluated "in reverse".

Implementing a unary operator would have to be implemented something like this:

let value = 10;

function increment_operator(value) {
  return function() {
    unwrap(value) + 1;
  }
}

value++ // would "under the hood" become value = increment_operator(value)

Note that the unwrap function I used above, is because javascript is not a functional language, so when needed we have to manually unwrap the value.

It is now apparent that applying increment a thousand times would cause us to wrap the value with 10000 closures, which is worthless.

The more obvious approach, is to actually directly change the value in place - but voila: you have introduced modifiable values a.k.a mutable values which makes the language imperative - or actually a hybrid.

Under the hood, it boils down to two different approaches to come up with an output when provided with an input.

Below, I'll try to make an illustration of a city with the following items:

  1. The Computer
  2. Your Home
  3. The Fibonaccis

Imperative Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Put The Computer into a box and mark it with a sticky note:

    Field Value
    Mail Address The Fibonaccis
    Return Address Your Home
    Parameters 3
    Return Value undefined

    and send off the computer.

  2. The Fibonaccis will upon receiving the box do as they always do:

    • Is the parameter < 2?

      • Yes: Change the sticky note, and return the computer to the post office:

        Field Value
        Mail Address The Fibonaccis
        Return Address Your Home
        Parameters 3
        Return Value 0 or 1 (returning the parameter)

        and return to sender.

      • Otherwise:

        1. Put a new sticky note on top of the old one:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, step 2, c/oThe Fibonaccis
          Parameters 2 (passing parameter-1)
          Return Value undefined

          and send it.

        2. Take off the returned sticky note. Put a new sticky note on top of the initial one and send The Computer again:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, done, c/o The Fibonaccis
          Parameters 2 (passing parameter-2)
          Return Value undefined
        3. By now, we should have the initial sticky note from the requester, and two used sticky notes, each having their Return Value field filled. We summarize the return values and put it in the Return Value field of the final sticky note.

          Field Value
          Mail Address The Fibonaccis
          Return Address Your Home
          Parameters 3
          Return Value 2 (returnValue1 + returnValue2)

          and return to sender.

As you can imagine, quite a lot of work starts immediately after you send your computer off to the functions you call.

The entire programming logic is recursive, but in truth the algorithm happens sequentially as the computer moves from algorithm to algorithm with the help of a stack of sticky notes.

Functional Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Write the following down on a sticky note:

    Field Value
    Instructions The Fibonaccis
    Parameters 3

That's essentially it. That sticky note now represents the computation result of fib(3).

We have attached the parameter 3 to the recipe named The Fibonaccis. The computer does not have to perform any calculations, unless somebody needs the scalar value.

Functional Javascript Example

I've been working on designing a programming language named Charm, and this is how fibonacci would look in that language.

fib: (n) => if (                         
  n < 2               // test
  n                   // when true
  fib(n-1) + fib(n-2) // when false
)
print(fib(4));

This code can be compiled both into imperative and functional "bytecode".

The imperative javascript version would be:

let fib = (n) => 
  n < 2 ?
  n : 
  fib(n-1) + fib(n-2);

The HALF functional javascript version would be:

let fib = (n) => () =>
  n < 2 ?
  n :
  fib(n-1) + fib(n-2);

The PURE functional javascript version would be much more involved, because javascript doesn't have functional equivalents.

let unwrap = ($) =>
  typeof $ !== "function" ? $ : unwrap($());

let $if = ($test, $whenTrue, $whenFalse) => () =>
  unwrap($test) ? $whenTrue : $whenFalse;

let $lessThen = (a, b) => () =>
  unwrap(a) < unwrap(b);

let $add = ($value, $amount) => () =>
  unwrap($value) + unwrap($amount);

let $sub = ($value, $amount) => () =>
  unwrap($value) - unwrap($amount);

let $fib = ($n) => () =>
  $if(
    $lessThen($n, 2),
    $n,
    $add( $fib( $sub($n, 1) ), $fib( $sub($n, 2) ) )
  );

I'll manually "compile" it into javascript code:

"use strict";

// Library of functions:
  /**
   * Function that resolves the output of a function.
   */
  let $$ = (val) => {
    while (typeof val === "function") {
      val = val();
    }
    return val;
  }

  /**
   * Functional if
   *
   * The $ suffix is a convention I use to show that it is "functional"
   * style, and I need to use $$() to "unwrap" the value when I need it.
   */
  let if$ = (test, whenTrue, otherwise) => () =>
    $$(test) ? whenTrue : otherwise;

  /**
   * Functional lt (less then)
   */
  let lt$ = (leftSide, rightSide)   => () => 
    $$(leftSide) < $$(rightSide)


  /**
   * Functional add (+)
   */
  let add$ = (leftSide, rightSide) => () => 
    $$(leftSide) + $$(rightSide)

// My hand compiled Charm script:

  /**
   * Functional fib compiled
   */
  let fib$ = (n) => if$(                 // fib: (n) => if(
    lt$(n, 2),                           //   n < 2
    () => n,                             //   n
    () => add$(fib$(n-2), fib$(n-1))     //   fib(n-1) + fib(n-2)
  )                                      // )

// This takes a microsecond or so, because nothing is calculated
console.log(fib$(30));

// When you need the value, just unwrap it with $$( fib$(30) )
console.log( $$( fib$(5) ))

// The only problem that makes this not truly functional, is that
console.log(fib$(5) === fib$(5)) // is false, while it should be true
// but that should be solveable

https://jsfiddle.net/819Lgwtz/42/

Vue equivalent of setTimeout?

You can use Vue.nextTick

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                Vue.nextTick(() =>{
                    this.basketAddSuccess = false;
                });
            }

push() a two-dimensional array

In your case you can do that without using push at all:

var myArray = [
    [1,1,1,1,1],
    [1,1,1,1,1],
    [1,1,1,1,1]
]

var newRows = 8;
var newCols = 7;

var item;

for (var i = 0; i < newRows; i++) {
    item = myArray[i] || (myArray[i] = []);

    for (var k = item.length; k < newCols; k++)
        item[k] = 0;    
}

Enable & Disable a Div and its elements in Javascript

The following selects all descendant elements and disables them:

$("#dcacl").find("*").prop("disabled", true);

But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:

$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);

To re-enable you just set "disabled" to false.

I want to Disable them at loading the page and then by a click i can enable them

OK, so put the above code in a document ready handler, and setup an appropriate click handler:

$(document).ready(function() {
    var $dcac1kids = $("#dcac1").find(":input");
    $dcac1kids.prop("disabled",true);

    // not sure what you want to click on to re-enable
    $("selector for whatever you want to click").one("click",function() {
       $dcac1kids.prop("disabled",false);
    }
}

I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one() since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one() to .click() if appropriate.

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

Windows task scheduler error 101 launch failure code 2147943785

Had the same issue today. I added the user to:

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job

But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job

So just be aware that you may need to check both policies for the user.

List only stopped Docker containers

The typical command is:

docker container ls -f 'status=exited'

However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:

  • created
  • restarting
  • running
  • removing
  • paused
  • exited
  • dead

You can filter on multiple statuses by passing multiple filters on the status:

docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'

If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q, and you can also limit to just the containers that exited successfully with an exit code filter:

docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')

For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering

Python import csv to list

Extending your requirements a bit and assuming you do not care about the order of lines and want to get them grouped under categories, the following solution may work for you:

>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
...     for line in f:
...         text, cat = line.rstrip("\n").split(",", 1)
...         dct[cat].append(text)
...
>>> dct
defaultdict(<type 'list'>, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})

This way you get all relevant lines available in the dictionary under key being the category.

How to deal with missing src/test/java source folder in Android/Maven project?

In the case of Maven project

Try right click on the project then select Maven -> Update Project... then Ok

Android studio, gradle and NDK

  1. If your project exported from eclipse,add the codes below in gradle file:

    android {
       sourceSets{
            main{
               jniLibs.srcDir['libs']  
          }  
        }
    }
    

2.If you create a project in Android studio:

create a folder named jniLibs in src/main/ ,and put your *.so files in the jniLibs folder.

And copy code as below in your gradle file :

android {
    sourceSets{  
       main{  
         jniLibs.srcDir['jniLibs']  
      }  
    }
}

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

Exception thrown in catch and finally clause

I think this solve the problem :

boolean allOk = false;
try{
  q();
  allOk = true;
} finally {
  try {
     is.close();
  } catch (Exception e) {
     if(allOk) {
       throw new SomeException(e);
     }
  }
}

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

For all those people stuck with this problem, but still couldn't solve it: I stumbled upon the same error and found the _id field being empty.

I described it here in more detail. Still have not found a solution except changing the fields in _id to not-ID fields which is a dirty hack to me. I'm probably going to file a bug report for mongoose. Any help would be appreciated!

Edit: I updated my thread. I filed a ticket and they confirmed the missing _id problem. It is going to be fixed in the 4.x.x version which has a release candidate available right now. The rc is not recommended for productive use!

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

Count the number of occurrences of a character in a string in Javascript

s = 'dir/dir/dir/dir/'
for(i=l=0;i<s.length;i++)
if(s[i] == '/')
l++

How to send an email with Python?

Here is an example on Python 3.x, much simpler than 2.x:

import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
              from_email='[email protected]'):
    # import smtplib
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(to_email)
    msg.set_content(message)
    print(msg)
    server = smtplib.SMTP(server)
    server.set_debuglevel(1)
    server.login(from_email, 'password')  # user & password
    server.send_message(msg)
    server.quit()
    print('successfully sent the mail.')

call this function:

send_mail(to_email=['[email protected]', '[email protected]'],
          subject='hello', message='Your analysis has done!')

below may only for Chinese user:

If you use 126/163, ????, you need to set"???????", like below:

enter image description here

ref: https://stackoverflow.com/a/41470149/2803344 https://docs.python.org/3/library/email.examples.html#email-examples

Eclipse Indigo - Cannot install Android ADT Plugin

The best answer (by Sathya) is also applicable in Eclipse Juno.

How to set order of repositories in Maven settings.xml

None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:

            <repository>
                <id>1_maven.apache.org</id>
                <releases>  <enabled>true</enabled>  </releases>
                <snapshots> <enabled>true</enabled> </snapshots>
                <url>https://repo.maven.apache.org/maven2</url>
                <layout>default</layout>
            </repository>

            <repository>
                <id>2_maven.oracle.com</id>
                <releases>  <enabled>true</enabled>  </releases>
                <snapshots> <enabled>false</enabled> </snapshots>
                <url>https://maven.oracle.com</url>
                <layout>default</layout>
            </repository>

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I'm using jQuery 3.3.1 and I received the same error, in my case, the URL was an Object vs a string.

What happened was, that I took URL = window.location - which returned an object. Once I've changed it into window.location.href - it worked w/o the e.indexOf error.

How do I add to the Windows PATH variable using setx? Having weird problems

This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:

If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
    CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
    WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True

Advantages of this approach:

1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.

$(this).serialize() -- How to add a value?

Instead of

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

you probably want

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

You should be careful to URL-encode the value of NonFormValue if it might contain any special characters.

Can an abstract class have a constructor?

Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check JLS:

It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression.

A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.

WampServer orange icon

PLEASE NOTE! If you have gone through all of the above, like "I" did, and still get the Orange icon, and, when you test Port 80 you get "Apache", look at the file: c:/wamp/bin/apache/apache2.4.9/conf/httpd.conf (your apache version number may differ).

In the file, about line # 62, you'll find a note saying to fill in this:

Listen 0.0.0.0:80 Listen [::0]:80

Why?

Change this to Listen on specific IP addresses as shown below to prevent Apache from glomming onto all bound IP addresses.

I changed that to match my localhost IP address and when I restarted Wamp, it quickly went from Red to Green. Success!...3 hours later....

Specify a Root Path of your HTML directory for script links?

As Alexander Jank mentioned <base href="http://www.example.com/default/"> is great. When using sub-domains e.g. default.example.com base works great, because the JS and CSS loads from the said sub-domain and is accessible to both default.example.com and example.com/default

When using the root path, and your JS and CSS files are located in example.com/css, or example.com/js, then the subdomain has no access and the root of the subdomain is not accessible, except using the base.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

How to install Python packages from the tar.gz file without using pip install

Is it possible for you to use sudo apt-get install python-seaborn instead? Basically tar.gz is just a zip file containing a setup, so what you want to do is to unzip it, cd to the place where it is downloaded and use gunzip -c seaborn-0.7.0.tar.gz | tar xf - for linux. Change dictionary into the new seaborn unzipped file and execute python setup.py install

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

How to get ER model of database from server with Workbench

On mac, press Command + R or got to Database -> Reverse Engineer and keep selecting your requirements and continue

enter image description here

How do I use 3DES encryption/decryption in Java?

I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.

Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)



    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Security;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;


    /**
     *
     * @author Jose Luis Montes de Oca
     */
    public class TripleDesCipher {
       private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
       private static String ALGORITHM = "DESede";
       private static String BOUNCY_CASTLE_PROVIDER = "BC";
       private Cipher encrypter;
       private Cipher decrypter;

       public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
             InvalidKeyException {
          Security.addProvider(new BouncyCastleProvider());
          SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
          encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
          encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
          decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
          decrypter.init(Cipher.DECRYPT_MODE, keySpec);
       }

       public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
          return encrypter.doFinal(input);
       }

       public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
          return decrypter.doFinal(input);
       }
    }

How to get current date time in milliseconds in android

I think leverage this functionality using Java

long time= System.currentTimeMillis();

this will return current time in milliseconds mode . this will surely work

long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);

Here is my logcat using the above function

05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157

If you got any doubt with millisecond value .Check Here

EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds that mentioned in log to match with time in log you might get a different value based your system timezone

EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

updating web.config with the following assembly binding resolved the issue 
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">     
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed"
                culture="neutral" />
        <bindingRedirect oldVersion="4.5.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

can you host a private repository for your organization to use with npm?

There is an easy to use npm package to do this. https://www.npmjs.org/package/sinopia

In a nutshell, Sinopia is a private/caching npm repository server that you can setup with zero configuration.

Sinopia can be used to :

  • publish own private packages without exposing it to the public
  • cache only public packages that are used (there is no need to have to replicate the whole public registery)
  • override public packages with a modified version that have been produced internally.

Why does "return list.sort()" return None, not the list?

Python has two kinds of sorts: a sort method (or "member function") and a sort function. The sort method operates on the contents of the object named -- think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.

Given a list of integers named l the list itself will be reordered if we call l.sort():

>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]

This method has no return value. But what if we try to assign the result of l.sort()?

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None

r now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don't forget again).

The function sorted(), on the other hand, will not do anything to the contents of l, but will return a new, sorted list with the same contents as l:

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]

Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:

>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]

HTTP authentication logout via PHP

Trac - by default - uses HTTP Authentication as well. Logout does not work and can not be fixed:

  • This is an issue with the HTTP authentication scheme itself, and there's nothing we can do in Trac to fix it properly.
  • There is currently no workaround (JavaScript or other) that works with all major browsers.

From: http://trac.edgewall.org/ticket/791#comment:103

Looks like that there is no working answer to the question, that issue has been reported seven years ago and it makes perfect sense: HTTP is stateless. Either a request is done with authentication credentials or not. But that's a matter of the client sending the request, not the server receiving it. The server can only say if a request URI needs authorization or not.

How to validate IP address in Python?

I hope it's simple and pythonic enough:

def is_valid_ip(ip):
    m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
    return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

Just remember, if the field you want to make nullable is part of a primary key, you can't. Primary Keys cannot have null fields.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to replace NaNs by preceding values in pandas DataFrame?

You can use fillna to remove or replace NaN values.

NaN Remove

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])

df.fillna(method='ffill')
     0    1    2
0  1.0  2.0  3.0
1  4.0  2.0  3.0
2  4.0  2.0  9.0

NaN Replace

df.fillna(0) # 0 means What Value you want to replace 
     0    1    2
0  1.0  2.0  3.0
1  4.0  0.0  0.0
2  0.0  0.0  9.0

Reference pandas.DataFrame.fillna

finding first day of the month in python

Can be done on the same line using date.replace:

from datetime import datetime

datetime.today().replace(day=1)

Swift apply .uppercaseString to only the first letter of a string

Here's the way I did it in small steps, its similar to @Kirsteins.

func capitalizedPhrase(phrase:String) -> String {
    let firstCharIndex = advance(phrase.startIndex, 1)
    let firstChar = phrase.substringToIndex(firstCharIndex).uppercaseString
    let firstCharRange = phrase.startIndex..<firstCharIndex
    return phrase.stringByReplacingCharactersInRange(firstCharRange, withString: firstChar)
}

Python datetime strptime() and strftime(): how to preserve the timezone information

Here is my answer in Python 2.7

Print current time with timezone

from datetime import datetime
import tzlocal  # pip install tzlocal

print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")

Print current time with specific timezone

from datetime import datetime
import pytz # pip install pytz

print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")

It will print something like

2017-08-10 20:46:24 +0800

Changing file permission in Python

os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

stat

The following flags can also be used in the mode argument of os.chmod():

stat.S_ISUID Set UID bit.

stat.S_ISGID Set-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT).

stat.S_ISVTX Sticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process.

stat.S_IRWXU Mask for file owner permissions.

stat.S_IRUSR Owner has read permission.

stat.S_IWUSR Owner has write permission.

stat.S_IXUSR Owner has execute permission.

stat.S_IRWXG Mask for group permissions.

stat.S_IRGRP Group has read permission.

stat.S_IWGRP Group has write permission.

stat.S_IXGRP Group has execute permission.

stat.S_IRWXO Mask for permissions for others (not in group).

stat.S_IROTH Others have read permission.

stat.S_IWOTH Others have write permission.

stat.S_IXOTH Others have execute permission.

stat.S_ENFMT System V file locking enforcement. This flag is shared with S_ISGID: file/record locking is enforced on files that do not have the group execution bit (S_IXGRP) set.

stat.S_IREAD Unix V7 synonym for S_IRUSR.

stat.S_IWRITE Unix V7 synonym for S_IWUSR.

stat.S_IEXEC Unix V7 synonym for S_IXUSR.

How to get history on react-router v4?

This works! https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Regular expressions inside SQL Server

You can write queries like this in SQL Server:

--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'

Resetting MySQL Root Password with XAMPP on Localhost

1.-In XAMPP press button Shell

2.-place command:

mysqladmin -u root password

New password: aqui colocar password ejemplo ´09876´

3.-go on the local disk c: xampp \ phpMyAdmin open config.inic.php with notepad ++

5.- add the password and in AllowNoPassword change to false

/* Authentication type and info */

$cfg['Servers'][$i]['auth_type'] = 'cookie';

$cfg['Servers'][$i]['user'] = 'root';

$cfg['Servers'][$i]['password'] = '09876';

$cfg['Servers'][$i]['extension'] = 'mysqli';

$cfg['Servers'][$i]['AllowNoPassword'] = false;

$cfg['Lang'] = '';

6.- save changes, clear browser cache and restart xampp

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

date --date="2:00:01 PM" +%T
14:00:01

date --date="2:00 PM" +%T | cut -d':' -f1-2
14:00

var="2:00:02 PM"
date --date="$var" +%T
14:00:02

rails bundle clean

If you are using Bundler 1.1 or later you can use bundle clean, just as you imagined you could. This is redundant if you're using bundle install --path (Bundler manages the location you specified with --path, so takes responsibility for removing outdated gems), but if you've used Bundler to install the gems as system gems then bundle clean --force will delete any system gems not required by your Gemfile. Blindingly obvious caveat: don't do this if you have other apps that rely on system gems that aren't in your Gemfile!

Pat Shaughnessy has a good description of bundle clean and other new additions in bundler 1.1.

Disable EditText blinking cursor

In kotlin your_edittext.isCursorVisible = false

Maximum and Minimum values for ints

I rely heavily on commands like this.

python -c 'import sys; print(sys.maxsize)'

Max int returned: 9223372036854775807

For more references for 'sys' you should access

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

How can I write an anonymous function in Java?

if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

How to load image files with webpack file-loader

webpack.config.js

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name].[ext]',
    },
}

anyfile.html

<img src={image_name.jpg} />

How to read xml file contents in jQuery and display in html elements?

responseText is what you are looking for. Example:

    $.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});

Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.

What is the difference between "px", "dip", "dp" and "sp"?

You can see the difference between px and dp from the below picture, and you can also find that the px and dp could not guarantee the same physical sizes on the different screens.

enter image description here

Return 0 if field is null in MySQL

Use IFNULL:

IFNULL(expr1, 0)

From the documentation:

If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.

How to view the committed files you have not pushed yet?

Assuming you're on local branch master, which is tracking origin/master:

git diff --stat origin/master..

Tree implementation in Java (root, parents and children)

Here is my implementation in java for your requirement. In the treeNode class i used generic array to store the tree data. we can also use arraylist or dynamic array to store the tree value.

public class TreeNode<T> {
   private T value = null;
   private TreeNode[] childrens = new TreeNode[100];
   private int childCount = 0;

    TreeNode(T value) {
        this.value = value;
    }

    public TreeNode addChild(T value) {
        TreeNode newChild = new TreeNode(value, this);
        childrens[childCount++] = newChild;
        return newChild;
    }

    static void traverse(TreeNode obj) {
        if (obj != null) {
            for (int i = 0; i < obj.childCount; i++) {
                System.out.println(obj.childrens[i].value);
                traverse(obj.childrens[i]);
            }
        }
        return;
    }

    void printTree(TreeNode obj) {
        System.out.println(obj.value);
        traverse(obj);
    }
}

And the client class for the above implementation.

public class Client {
    public static void main(String[] args) {
        TreeNode menu = new TreeNode("Menu");
        TreeNode item = menu.addChild("Starter");
            item = item.addChild("Veg");
                item.addChild("Paneer Tikka");
                item.addChild("Malai Paneer Tikka");
            item = item.addChild("Non-veg");
                item.addChild("Chicken Tikka");
                item.addChild("Malai Chicken Tikka");
        item = menu.addChild("Main Course");
            item = item.addChild("Veg");
                item.addChild("Mili Juli Sabzi");
                item.addChild("Aloo Shimla Mirch");
            item = item.addChild("Non-veg");
                item.addChild("Chicken Do Pyaaza");
                item.addChild("Chicken Chettinad");
        item = menu.addChild("Desserts");
                item = item.addChild("Cakes");
                        item.addChild("Black Forest");
                        item.addChild("Black Current");
                item = item.addChild("Ice Creams");
                        item.addChild("chocolate");
                        item.addChild("Vanilla");
        menu.printTree(menu);
    }
}

OUTPUT

Menu                                                                     
Starter                                                                 
Veg                                                                
Paneer Tikka                                                        
Malai Paneer Tikka                                                    
Non-veg                                                              
Chicken Tikka                                                      
Malai Chicken Tikka                                                 
Main Course                                                      
Veg                                                             
Mili Juli Sabzi                                                   
Aloo Shimla Mirch                                                  
Non-veg                                                               
Chicken Do Pyaaza                                                   
Chicken Chettinad                                                    
Desserts                                                         
Cakes                                                            
Black Forest                                                     
Black Current                                                   
Ice Creams                                                      
chocolate                                                       
Vanilla           

twitter bootstrap navbar fixed top overlapping site

for Bootstrap 3.+ , I'd use following CSS to fix navbar-fixed-top and the anchor jump overlapped issue based on https://github.com/twbs/bootstrap/issues/1768

/* fix fixed-bar */
body { padding-top: 40px; }
@media screen and (max-width: 768px) {
  body { padding-top: 40px; }
}

/* fix fixed-bar jumping to in-page anchor issue */
*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; 
  height: 75px; 
  visibility: hidden; 
}

Binding multiple events to a listener (without JQuery)?

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

How to remove specific substrings from a set of strings in Python?

You could do this:

import re
import string
set1={'Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad'}

for x in set1:
    x.replace('.good',' ')
    x.replace('.bad',' ')
    x = re.sub('\.good$', '', x)
    x = re.sub('\.bad$', '', x)
    print(x)

How to manipulate arrays. Find the average. Beginner Java

Well, to calculate the average of an array, you can consider using for loop instead of while loop.

So as per your question let me assume an array as arrNumbers ( here i'm considering the same array elements as in your question )

int arrNumbers[] = new int[]{1, 3, 2, 5, 8};
int sum = 0;

for(int a = 0; a < arrNumbers.length; a++)
{
   sum = sum + arrNumbers[a];
}

double average = sum / arrNumbers.length;

System.out.println("Average is: " + average);

You can use scanner class as well. It's left to you.

How should I escape strings in JSON?

org.json.JSONObject quote(String data) method does the job

import org.json.JSONObject;
String jsonEncodedString = JSONObject.quote(data);

Extract from the documentation:

Encodes data as a JSON string. This applies quotes and any necessary character escaping. [...] Null will be interpreted as an empty string

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

<div> cannot appear as a descendant of <p>

I had a similar issue and wrapped the component in "div" instead of "p" and the error went away.

How to change dataframe column names in pyspark?

You can put into for loop, and use zip to pairs each column name in two array.

new_name = ["id", "sepal_length_cm", "sepal_width_cm", "petal_length_cm", "petal_width_cm", "species"]

new_df = df
for old, new in zip(df.columns, new_name):
    new_df = new_df.withColumnRenamed(old, new)

How is TeamViewer so fast?

My random guess is: TV uses x264 codec which has a commercial license (otherwise TeamViewer would have to release their source code). At some point (more than 5 years ago), I recall main developer of x264 wrote an article about improvements he made for low delay encoding (if you delay by a few frames encoders can compress better), plus he mentioned some other improvements that were relevant for TeamViewer-like use. In that post he mentioned playing quake over video stream with no noticeable issues. Back then I was kind of sure who was the sponsor of these improvements, as TeamViewer was pretty much the only option at that time. x264 is an open source implementation of H264 video codec, and it's insanely good implementation, it's the best one. At the same time it's extremely well optimized. Most likely due to extremely good implementation of x264 you get much better results with TV at lower CPU load. AnyDesk and Chrome Remote Desk use libvpx, which isn't as good as x264 (optimization and video quality wise).

However, I don't think TeamView can beat microsoft's RDP. To me it's the best, however it works between windows PCs or from Mac to Windows only. TV works even from mobiles.

Update: article was written in January 2010, so that work was done roughly 10 years ago. Also, I made a mistake: he played call of duty, not quake. When you posted your question, if my guess is correct, TeamViewer had been using that work for 3 years. Read that blog post from web archive: x264: the best low-latency video streaming platform in the world. When I read the article back in 2010, I was sure that the "startup–which has requested not to be named" that the author mentions was TeamViewer.

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

Child with max-height: 100% overflows parent

A good solution is to not use height on the parent and use it just on the child with View Port :

Fiddle Example: https://jsfiddle.net/voan3v13/1/

body, html {
  width: 100%;
  height: 100%;
}
.parent {
  width: 400px;
  background: green;
}

.child {
  max-height: 40vh;
  background: blue;
  overflow-y: scroll;
}

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

How to call a shell script from python code?

Use the subprocess module as mentioned above.

I use it like this:

subprocess.call(["notepad"])

Pyinstaller setting icons don't change

The below command can set the icon on an executable file.

Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".

pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py

For example:

If the app.py file is present in the current directory and app.ico is present inside the Images folder within the current directory.

Then the command should be as below. The final executable file will be generated inside the dist folder

pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py

I cannot start SQL Server browser

My approach was similar to @SoftwareFactor, but different, perhaps because I'm running a different OS, Windows Server 2012. These steps worked for me.

Control Panel > System and Security > Administrative Tools > Services, right-click SQL Server Browser > Properties > General tab, change Startup type to Automatic, click Apply button, then click Start button in Service Status area.

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Set width to match constraints in ConstraintLayout

For making your view as match_parent is not possible directly, but we can do it in a little different way, but don't forget to use Left and Right attribute with Start and End, coz if you use RTL support, it will be needed.

    <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

How to move the cursor word by word in the OS X Terminal

As of Mac OS X Lion 10.7, Terminal maps Option-Left/Right Arrow to Esc-b/f by default, so this is now built-in for bash and other programs that use these emacs-compatible keybindings.

Remove background drawable programmatically in Android

setBackgroundResource(0) is the best option. From the documentation:

Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.

It works everywhere, because it's since API 1.

setBackground was added much later, in API 16, so it will not work if your minSdkVersion is lower than 16.

Why do we not have a virtual constructor in C++?

The virtual mechanism only works when you have a based class pointer to a derived class object. Construction has it's own rules for the calling of base class constructors, basically base class to derived. How could a virtual constructor be useful or called? I don't know what other languages do, but I can't see how a virtual constructor could be useful or even implemented. Construction needs to have taken place for the virtual mechanism to make any sense and construction also needs to have taken place for the vtable structures to have been created which provides the mechanics of the polymorphic behaviour.

How to replicate background-attachment fixed on iOS

It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.

Check this comment by @PaulIrish:

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.

you can see workarounds to this in this posts:

Fixed background image with ios7

Fixed body background scrolls with the page on iOS7

jquery simple image slideshow tutorial

This is by far the easiest example I have found on the net. http://jonraasch.com/blog/a-simple-jquery-slideshow

Summaring the example, this is what you need to do a slideshow:

HTML:

<div id="slideshow">
    <img src="img1.jpg" style="position:absolute;" class="active" />
    <img src="img2.jpg" style="position:absolute;" />
    <img src="img3.jpg" style="position:absolute;" />
</div>

Position absolute is used to put an each image over the other.

CSS

<style type="text/css">
    .active{
        z-index:99;
    }
</style>

The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.

<script>
    function slideSwitch() {
        var $active = $('div#slideshow IMG.active');
        var $next = $active.next();    

        $next.addClass('active');

        $active.removeClass('active');
    }

    $(function() {
        setInterval( "slideSwitch()", 5000 );
    });
</script>

If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.

Git command to checkout any branch and overwrite local changes

git reset and git clean can be overkill in some situations (and be a huge waste of time).

If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch> is the best option.

If you're like me, your other option was to clean and perform a --hard reset then recompile your project.

Only variable references should be returned by reference - Codeigniter

It's not a better idea to override the core.common file of codeigniter. Because that's the more tested and system files....

I make a solution for this problem. In your ckeditor_helper.php file line- 65

if($k !== end (array_keys($data['config']))) {
       $return .= ",";
}

Change this to-->

 $segment = array_keys($data['config']);
    if($k !== end($segment)) {
           $return .= ",";
    }

I think this is the best solution and then your problem notice will dissappear.

How to compare two java objects

You need to Override equals and hashCode.
equals will compare the objects for equality according to the properties you need and hashCode is mandatory in order for your objects to be used correctly in Collections and Maps

Android, How to create option Menu

The previous answers have covered the traditional menu used in android. Their is another option you can use if you are looking for an alternative

https://github.com/AnshulBansal/Android-Pulley-Menu

Pulley menu is an alternate to the traditional Menu which allows user to select any option for an activity intuitively. The menu is revealed by dragging the screen downwards and in that gesture user can also select any of the options.

Source file not compiled Dev C++

I guess you're using windows 7 with the Orwell Dev CPP

This version of Dev CPP is good for windows 8 only. However on Windows 7 you need the older version of it which is devcpp-4.9.9.2_setup.exe Download it from the link and use it. (Don't forget to uninstall any other version already installed on your pc) Also note that the older version does not work with windows 8.

python save image from url

Python code snippet to download a file from an url and save with its name

import requests

url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

Add ... if string is too long PHP

$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";

if(strlen($string) >= 50)
{
    echo substr($string, 50); //prints everything after 50th character
    echo substr($string, 0, 50); //prints everything before 50th character
}

RegEx for valid international mobile phone number

Even though it is about international numbers I would want the code to be like :

/^(\+|\d)[0-9]{7,16}$/;

As you can have international numbers starting with '00' as well.

Why I prefer 15 digits : http://en.wikipedia.org/wiki/E.164

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

How can I "disable" zoom on a mobile web page?

You can accomplish the task by simply adding the following 'meta' element into your 'head':

<meta name="viewport" content="user-scalable=no">

Adding all the attributes like 'width','initial-scale', 'maximum-width', 'maximum-scale' might not work. Therefore, just add the above element.

How do I limit the number of decimals printed for a double?

Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.

 private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;

 public static void main(String[] args)
  {
   computeShippingCost();
  }

  public static void computeShippingCost()
  {
   System.out.print("Enter a number of jars: ");
   Scanner kboard = new Scanner (System.in);
   nJars = kboard.nextInt();
   int nCartons = (nJars + 11) / 12;
   int totalOunces = (nJars * 21) + (nCartons * 25);
   int lbs = totalOunces / 16;


   double shippingCost =  ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;

     Formatter fmt = new Formatter();
     fmt.format("%.2f", shippingCost);

   System.out.print("$" + fmt);

   fmt.close();

}

How do I make this file.sh executable via double click?

By default, *.sh files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command. By default, these are sent to Terminal, which will execute the file as a shell script.

You will also need to ensure the file is executable, e.g.:

chmod +x file.command

Without this, Terminal will refuse to execute it.

Note that the script does not have to begin with a #! prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #! line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)

Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd command if you actually need it to run with a particular working directory.

Sorting options elements alphabetically using jQuery

html:

<select id="list">
    <option value="op3">option 3</option>
    <option value="op1">option 1</option>
    <option value="op2">option 2</option>
</select>

jQuery:

var options = $("#list option");                    // Collect options         
options.detach().sort(function(a,b) {               // Detach from select, then Sort
    var at = $(a).text();
    var bt = $(b).text();         
    return (at > bt)?1:((at < bt)?-1:0);            // Tell the sort function how to order
});
options.appendTo("#list");                          // Re-attach to select

I used tracevipin's solution, which worked fantastically. I provide a slightly modified version here for anyone like me who likes to find easily readable code, and compress it after it's understood. I've also used .detach instead of .remove to preserve any bindings on the option DOM elements.

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

How to dismiss notification after action has been clicked

In new APIs don't forget about TAG:

notify(String tag, int id, Notification notification)

and correspondingly

cancel(String tag, int id) 

instead of:

cancel(int id)

https://developer.android.com/reference/android/app/NotificationManager

Fatal error: Class 'PHPMailer' not found

Doesn't sound like all the files needed to use that class are present. I would start over:

  1. Download the package from https://github.com/PHPMailer/PHPMailer by clicking on the "Download ZIP" button on the far lower right of the page.
  2. extract the zip file
  3. upload the language folder, class.phpmailer.php, class.pop3.php, class.smtp.php, and PHPMailerAutoload.php all into the same directory on your server, I like to create a directory on the server called phpmailer to place all of these into.
  4. Include the class in your PHP project: require_once('phpmailer/PHPMailerAutoload.php');

jQuery - Trigger event when an element is removed from the DOM

We can also use DOMNodeRemoved:

$("#youridwhichremoved").on("DOMNodeRemoved", function () {
// do stuff
})

BeanFactory vs ApplicationContext

For the most part, ApplicationContext is preferred unless you need to save resources, like on a mobile application.

I'm not sure about depending on XML format, but I'm pretty sure the most common implementations of ApplicationContext are the XML ones such as ClassPathXmlApplicationContext, XmlWebApplicationContext, and FileSystemXmlApplicationContext. Those are the only three I've ever used.

If your developing a web app, it's safe to say you'll need to use XmlWebApplicationContext.

If you want your beans to be aware of Spring, you can have them implement BeanFactoryAware and/or ApplicationContextAware for that, so you can use either BeanFactory or ApplicationContext and choose which interface to implement.

comparing two strings in ruby

var1 is a regular string, whereas var2 is an array, this is how you should compare (in this case):

puts var1 == var2[0]

Value Change Listener to JTextField

If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.

usernameTextField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
    }
});

Python code to remove HTML tags from a string

There's a simple way to this in any C-like language. The style is not Pythonic but works with pure Python:

def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

The idea based in a simple finite-state machine and is detailed explained here: http://youtu.be/2tu9LTDujbw

You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s

PS - If you're interested in the class(about smart debugging with python) I give you a link: https://www.udacity.com/course/software-debugging--cs259. It's free!

Viewing full output of PS command

Just throw it on cat, which line-wraps automatically

ps aux | cat

Checking if my Windows application is running

you need a way to say that "i am running" from the app,

1) open a WCF ping service 2) write to registry/file on startup and delete on shutdown 3) create a Mutex

... i prefer the WCF part because you may not clean up file/registry correctly and Mutex seems to have its own issues

cast or convert a float to nvarchar?

For anyone willing to try a different method, they can use this:

select FORMAT([Column_Name], '') from YourTable

This will easily change any float value to nvarchar.

How can I call a function using a function pointer?

//Declare the pointer and asign it to the function
bool (*pFunc)() = A;
//Call the function A
pFunc();
//Call function B
pFunc = B;
pFunc();
//Call function C
pFunc = C;
pFunc();

javascript: pause setTimeout();

A slightly modified version of Tim Downs answer. However, since Tim rolled back my edit, I've to answer this myself. My solution makes it possible to use extra arguments as third (3, 4, 5...) parameter and to clear the timer:

function Timer(callback, delay) {
    var args = arguments,
        self = this,
        timer, start;

    this.clear = function () {
        clearTimeout(timer);
    };

    this.pause = function () {
        this.clear();
        delay -= new Date() - start;
    };

    this.resume = function () {
        start = new Date();
        timer = setTimeout(function () {
            callback.apply(self, Array.prototype.slice.call(args, 2, args.length));
        }, delay);
    };

    this.resume();
}

As Tim mentioned, extra parameters are not available in IE lt 9, however I worked a bit around so that it will work in oldIE's too.

Usage: new Timer(Function, Number, arg1, arg2, arg3...)

function callback(foo, bar) {
    console.log(foo); // "foo"
    console.log(bar); // "bar"
}

var timer = new Timer(callback, 1000, "foo", "bar");

timer.pause();
document.onclick = timer.resume;