Programs & Examples On #Wordpress geo mashup

Eloquent - where not equal to

Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition

The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)

Code::where(function ($query) {
            $query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');                  
        })->get();

How to increase buffer size in Oracle SQL Developer to view all records?

after you retrieve the first 50 rows in the query windows, simply click a column to get focus on the query window, then once selected do ctrl + pagedown

This will load the full result set (all rows)

jQuery - disable selected options

This will disable/enable the options when you select/remove them, respectively.

$("#theSelect").change(function(){          
    var value = $(this).val();
    if (value === '') return;
    var theDiv = $(".is" + value);

    var option = $("option[value='" + value + "']", this);
    option.attr("disabled","disabled");

    theDiv.slideDown().removeClass("hidden");
    theDiv.find('a').data("option",option);
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    $(this).data("option").removeAttr('disabled');
});

Demo: http://jsfiddle.net/AaXkd/

How do I install the babel-polyfill library?

This changed a bit in babel v6.

From the docs:

The polyfill will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node.

Installation:
$ npm install babel-polyfill

Usage in Node / Browserify / Webpack:
To include the polyfill you need to require it at the top of the entry point to your application.
require("babel-polyfill");

Usage in Browser:
Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script> before it.

NOTE: Do not require this via browserify etc, use babel-polyfill.

Making a div vertically scrollable using CSS

You can use this code instead.

<div id="" style="overflow-y:scroll; overflow-x:hidden; height:400px;">


overflow-x: The overflow-x property specifies what to do with the left/right edges of the content - if it overflows the element's content area.
overflow-y: The overflow-y property specifies what to do with the top/bottom edges of the content - if it overflows the element's content area.

Values
visible: Default value. The content is not clipped, and it may be rendered outside the content box.
hidden: The content is clipped - and no scrolling mechanism is provided.
scroll: The content is clipped and a scrolling mechanism is provided.
auto: Should cause a scrolling mechanism to be provided for overflowing boxes.
initial: Sets this property to its default value.
inherit Inherits this property from its parent element.

Git push error: Unable to unlink old (Permission denied)

This is an old question, but this may help Mac users.

If you are copying files from Time Machine manually, instead of restoring them through Time Machine, it'll add ACLs to everything, which can mess up your permissions.

For example, the section in this article that says "How to Fix Mac OS X File Permissions" shows that "everyone" has custom permissions, which messes it all up:

Bad permissions, from http://dreamlight.com/how-to-fix-mac-os-x-file-permissions

You need to remove the ACLs from those directories/files. This Super User answer goes into it, but here's the command:

sudo chmod -RN .

Then you can make sure your directories and files have the proper permissions. I use 750 for directories and 644 for files.

Find a string by searching all tables in SQL Server Management Studio 2008

This was very helpful. I wanted to import this function to a Postgre SQL database. Thought i would share it with anyone who is interested. Will have them a few hours. Note: this function creates a list of SQL statements that can be copied and executed on the Postgre database. Maybe someone smarter then me can get Postgre to create and execute the statements all in one function.

CREATE OR REPLACE FUNCTION SearchAllTables(_search text) RETURNS TABLE( txt text ) as $funct$
    DECLARE __COUNT int;
    __SQL text;
BEGIN
    EXECUTE 'SELECT COUNT(0) FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE    DATA_TYPE = ''text'' 
                    AND          table_schema = ''public'' ' INTO __COUNT;

    RETURN QUERY 
        SELECT CASE WHEN ROW_NUMBER() OVER (ORDER BY table_name) < __COUNT THEN 
            'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "'  || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search  || '%'' UNION ALL' 
            ELSE 
            'SELECT ''' || table_name ||'.'|| column_name || ''' AS tbl, "'  || column_name || '" AS col FROM "public"."' || "table_name" || '" WHERE "'|| "column_name" || '" ILIKE ''%' || _search  || '%'''
        END AS txt

                    FROM     INFORMATION_SCHEMA.COLUMNS
                    WHERE    DATA_TYPE = 'text' 
                    AND          table_schema = 'public';
END
$funct$ LANGUAGE plpgsql;

How does Java import work?

Import in Java does not work at all, as it is evaluated at compile time only. (Treat it as shortcuts so you do not have to write fully qualified class names). At runtime there is no import at all, just FQCNs.

At runtime it is necessary that all classes you have referenced can be found by classloaders. (classloader infrastructure is sometimes dark magic and highly dependent on environment.) In case of an applet you will have to rig up your HTML tag properly and also provide necessary JAR archives on your server.

PS: Matching at runtime is done via qualified class names - class found under this name is not necessarily the same or compatible with class you have compiled against.

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

Count characters in textarea

Improved version based on Caterham's function:

$('#field').keyup(function () {
  var max = 500;
  var len = $(this).val().length;
  if (len >= max) {
    $('#charNum').text(' you have reached the limit');
  } else {
    var char = max - len;
    $('#charNum').text(char + ' characters left');
  }
});

jQuery checkbox check/uncheck

Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

Live Demo

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.prop('checked', false);
        $(this).removeClass('admin_checked');
    }else{
        ele.prop('checked', true);
        $(this).addClass('admin_checked');
    }
});

Use prop instead of attr for properties like checked

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method

Creating a JSON Array in node js

You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

Use JSON.stringify(object) to turn it into (a string of) JSON text.

The transaction log for the database is full

Try this:

USE YourDB;  
GO  
-- Truncate the log by changing the database recovery model to SIMPLE.  
ALTER DATABASE YourDB
SET RECOVERY SIMPLE;  
GO  
-- Shrink the truncated log file to 50 MB.  
DBCC SHRINKFILE (YourDB_log, 50);  
GO  
-- Reset the database recovery model.  
ALTER DATABASE YourDB
SET RECOVERY FULL;  
GO 

I hope it helps.

Disable all Database related auto configuration in Spring Boot

I was getting this error even if I did all the solutions mentioned above.

 by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfig ...

At some point when i look up the POM there was this dependency in it

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

And the Pojo class had the following imports

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;

Which clearly shows the application was expecting a datasource.

What I did was I removed the JPA dependency from pom and replaced the imports for the pojo with the following once

import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document;

Finally I got SUCCESSFUL build. Check it out you might have run into the same problem

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

Add default value of datetime field in SQL Server to a timestamp

This can also be done through the SSMS GUI.

  1. Put your table in design view (Right click on table in object explorer->Design)
  2. Add a column to the table (or click on the column you want to update if it already exists)
  3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

Image of table in design view

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

Python: Total sum of a list of numbers with the for loop

I think what you mean is how to encapsulate that for general use, e.g. in a function:

def sum_list(l):
    sum = 0
    for x in l:
        sum += x
    return sum

Now you can apply this to any list. Examples:

l = [1, 2, 3, 4, 5]
sum_list(l)

l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)

But note that sum is already built in!

How to use pip with Python 3.x alongside Python 2.x

The approach you should take is to install pip for Python 3.2.

You do this in the following way:

$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py

Then, you can install things for Python 3.2 with pip-3.2, and install things for Python 2-7 with pip-2.7. The pip command will end up pointing to one of these, but I'm not sure which, so you will have to check.

Cannot install Aptana Studio 3.6 on Windows

Installing Aptana Studio in passive mode bypasses the installation of Git for Windows and Node.js.

Aptana_Studio_3_Setup_3.6.1 /passive /norestart

(I am unsure whether Aptana Studio will work properly without those "prerequisites", but it appears to.)

If you want a global installation in a specific directory, the command line is

Aptana_Studio_3_Setup_3.6.1.exe /passive /norestart ALLUSERS=1 APPDIR=c:\apps\AptanaStudio

Center form submit buttons HTML / CSS

I see a few answers here, most of them complicated or with some cons (additional divs, text-align doesn't work because of display: inline-block). I think this is the simplest and problem-free solution:

HTML:

<table>
    <!-- Rows -->
    <tr>
        <td>E-MAIL</td>
        <td><input name="email" type="email" /></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" value="Register!" /></td>
    </tr>
</table>

CSS:

table input[type="submit"] {
    display: block;
    margin: 0 auto;
}

How can I make window.showmodaldialog work in chrome 37?

I put the following javascript in the page header and it seems to work. It detects when the browser does not support showModalDialog and attaches a custom method that uses window.open, parses the dialog specs (height, width, scroll, etc.), centers on opener and sets focus back to the window (if focus is lost). Also, it uses the URL as the window name so that a new window is not opened each time. If you are passing window args to the modal you will need to write some additional code to fix that. The popup is not modal but at least you don't have to change a lot of code. Might need some work for your circumstances.

<script type="text/javascript">
  // fix for deprecated method in Chrome 37
  if (!window.showModalDialog) {
     window.showModalDialog = function (arg1, arg2, arg3) {

        var w;
        var h;
        var resizable = "no";
        var scroll = "no";
        var status = "no";

        // get the modal specs
        var mdattrs = arg3.split(";");
        for (i = 0; i < mdattrs.length; i++) {
           var mdattr = mdattrs[i].split(":");

           var n = mdattr[0];
           var v = mdattr[1];
           if (n) { n = n.trim().toLowerCase(); }
           if (v) { v = v.trim().toLowerCase(); }

           if (n == "dialogheight") {
              h = v.replace("px", "");
           } else if (n == "dialogwidth") {
              w = v.replace("px", "");
           } else if (n == "resizable") {
              resizable = v;
           } else if (n == "scroll") {
              scroll = v;
           } else if (n == "status") {
              status = v;
           }
        }

        var left = window.screenX + (window.outerWidth / 2) - (w / 2);
        var top = window.screenY + (window.outerHeight / 2) - (h / 2);
        var targetWin = window.open(arg1, arg1, 'toolbar=no, location=no, directories=no, status=' + status + ', menubar=no, scrollbars=' + scroll + ', resizable=' + resizable + ', copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        targetWin.focus();
     };
  }
</script>

How to unpackage and repackage a WAR file

This worked for me:

mv xyz.war ./tmp
cd tmp
jar -xvf xyz.war
rm -rf WEB-INF/lib/zookeeper-3.4.10.jar
rm -rf xyz.war
jar -cvf xyz.war *
mv xyz.war ../
cd ..

How to check for palindrome using Python logic

The real easy way to do that it is

word = str(raw_input(""))
is_palindrome = word.find(word[::-1])
if is_palindrome == 0:
    print True
else:
    print False

And if/else here just for fancy looks. The question about palindrome was on Amazon's interview for QA

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]

Using a PagedList with a ViewModel ASP.Net MVC

As Chris suggested the reason you're using ViewModel doesn't stop you from using PagedList. You need to form a collection of your ViewModel objects that needs to be send to the view for paging over.

Here is a step by step guide on how you can use PagedList for your viewmodel data.

Your viewmodel (I have taken a simple example for brevity and you can easily modify it to fit your needs.)

public class QuestionViewModel
{
        public int QuestionId { get; set; }
        public string QuestionName { get; set; }
}

and the Index method of your controller will be something like

public ActionResult Index(int? page)
{
     var questions = new[] {
           new QuestionViewModel { QuestionId = 1, QuestionName = "Question 1" },
           new QuestionViewModel { QuestionId = 1, QuestionName = "Question 2" },
           new QuestionViewModel { QuestionId = 1, QuestionName = "Question 3" },
           new QuestionViewModel { QuestionId = 1, QuestionName = "Question 4" }
     };

     int pageSize = 3;
     int pageNumber = (page ?? 1);
     return View(questions.ToPagedList(pageNumber, pageSize));
}

And your Index view

@model PagedList.IPagedList<ViewModel.QuestionViewModel>
@using PagedList.Mvc; 
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />


<table>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.QuestionId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.QuestionName)
        </td>
    </tr>
}

</table>

<br />

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager( Model, page => Url.Action("Index", new { page }) )

Here is the SO link with my answer that has the step by step guide on how you can use PageList

nodeJS - How to create and read session with express

I need to point out here that you're incorrectly adding middleware to the application. The app.use calls should not be done within the app.get request handler, but outside of it. Simply call them directly after createServer, or take a look at the other examples in the docs.

The secret you pass to express.session should be a string constant, or perhaps something taken from a configuration file. Don't feed it something the client might know, that's actually dangerous. It's a secret only the server should know about.

If you want to store the email address in the session, simply do something along the lines of:

req.session.email = req.param('email');

With that out of the way...


If I understand correctly, what you're trying to do is handle one or more HTTP requests and keep track of a session, then later on open a Socket.IO connection from which you need the session data as well.

What's tricky about this problem is that Socket.IO's means of making the magic work on any http.Server is by hijacking the request event. Thus, Express' (or rather Connect's) session middleware is never called on the Socket.IO connection.

I believe you can make this work, though, with some trickery.

You can get to Connect's session data; you simply need to get a reference to the session store. The easiest way to do that is to create the store yourself before calling express.session:

// A MemoryStore is the default, but you probably want something
// more robust for production use.
var store = new express.session.MemoryStore;
app.use(express.session({ secret: 'whatever', store: store }));

Every session store has a get(sid, callback) method. The sid parameter, or session ID, is stored in a cookie on the client. The default name of that cookie is connect.sid. (But you can give it any name by specifying a key option in your express.session call.)

Then, you need to access that cookie on the Socket.IO connection. Unfortunately, Socket.IO doesn't seem to give you access to the http.ServerRequest. A simple work around would be to fetch the cookie in the browser, and send it over the Socket.IO connection.

Code on the server would then look something like the following:

var io      = require('socket.io'),
    express = require('express');

var app    = express.createServer(),
    socket = io.listen(app),
    store  = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: 'something', store: store }));

app.get('/', function(req, res) {
  var old = req.session.email;
  req.session.email = req.param('email');

  res.header('Content-Type', 'text/plain');
  res.send("Email was '" + old + "', now is '" + req.session.email + "'.");
});

socket.on('connection', function(client) {
  // We declare that the first message contains the SID.
  // This is where we handle the first message.
  client.once('message', function(sid) {
    store.get(sid, function(err, session) {
      if (err || !session) {
        // Do some error handling, bail.
        return;
      }

      // Any messages following are your chat messages.
      client.on('message', function(message) {
        if (message.email === session.email) {
          socket.broadcast(message.text);
        }
      });
    });
  });
});

app.listen(4000);

This assumes you only want to read an existing session. You cannot actually create or delete sessions, because Socket.IO connections may not have a HTTP response to send the Set-Cookie header in (think WebSockets).

If you want to edit sessions, that may work with some session stores. A CookieStore wouldn't work for example, because it also needs to send a Set-Cookie header, which it can't. But for other stores, you could try calling the set(sid, data, callback) method and see what happens.

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

How do I finish the merge after resolving my merge conflicts?

How do I finish the merge after resolving my merge conflicts?

With Git 2.12 (Q1 2017), you will have the more natural command:

git merge --continue

See commit c7d227d (15 Dec 2016) by Jeff King (peff).
See commit 042e290, commit c261a87, commit 367ff69 (14 Dec 2016) by Chris Packham (cpackham).
(Merged by Junio C Hamano -- gitster -- in commit 05f6e1b, 27 Dec 2016)

See 2.12 release notes.

merge: add '--continue' option as a synonym for 'git commit'

Teach 'git merge' the --continue option which allows 'continuing' a merge by completing it.
The traditional way of completing a merge after resolving conflicts is to use 'git commit'.
Now with commands like 'git rebase' and 'git cherry-pick' having a '--continue' option adding such an option to 'git merge' presents a consistent UI.

python pandas dataframe columns convert to dict key and value

You can also do this if you want to play around with pandas. However, I like punchagan's way.

# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 
                 'area': [10, 20, 30, 40], 
                 'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)

# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)

output: {10: 7, 20: 5, 30: 2, 40: 3}

How can I do an OrderBy with a dynamic string parameter?

I did so:

using System.Linq.Expressions;

namespace System.Linq
{
    public static class LinqExtensions
    {

        public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string field, string dir = "asc")
        {
            // parametro => expressão
            var parametro = Expression.Parameter(typeof(TSource), "r");
            var expressao = Expression.Property(parametro, field);
            var lambda = Expression.Lambda(expressao, parametro); // r => r.AlgumaCoisa
            var tipo = typeof(TSource).GetProperty(field).PropertyType;

            var nome = "OrderBy";
            if (string.Equals(dir, "desc", StringComparison.InvariantCultureIgnoreCase))
            {
                nome = "OrderByDescending";
            }
            var metodo = typeof(Queryable).GetMethods().First(m => m.Name == nome && m.GetParameters().Length == 2);
            var metodoGenerico = metodo.MakeGenericMethod(new[] { typeof(TSource), tipo });
            return metodoGenerico.Invoke(source, new object[] { source, lambda }) as IOrderedQueryable<TSource>;

        }

        public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, string field, string dir = "asc")
        {
            var parametro = Expression.Parameter(typeof(TSource), "r");
            var expressao = Expression.Property(parametro, field);
            var lambda = Expression.Lambda<Func<TSource, string>>(expressao, parametro); // r => r.AlgumaCoisa
            var tipo = typeof(TSource).GetProperty(field).PropertyType;

            var nome = "ThenBy";
            if (string.Equals(dir, "desc", StringComparison.InvariantCultureIgnoreCase))
            {
                nome = "ThenByDescending";
            }

            var metodo = typeof(Queryable).GetMethods().First(m => m.Name == nome && m.GetParameters().Length == 2);
            var metodoGenerico = metodo.MakeGenericMethod(new[] { typeof(TSource), tipo });
            return metodoGenerico.Invoke(source, new object[] { source, lambda }) as IOrderedQueryable<TSource>;
        }

    }
}

Use :

example.OrderBy("Nome", "desc").ThenBy("other")

Work like:

example.OrderByDescending(r => r.Nome).ThenBy(r => r.other)

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

List<String> to ArrayList<String> conversion issue

Cast works where the actual instance of the list is an ArrayList. If it is, say, a Vector (which is another extension of List) it will throw a ClassCastException.

The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList. The exception tells you that it did not found the method it was looking for.

Create a new ArrayList with the contents of the old one.

new ArrayList<String>(myList);

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

Simple PowerShell LastWriteTime compare

Try the following.

$d = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime

This is part of the item property weirdness. When you run Get-ItemProperty it does not return the value but instead the property. You have to use one more level of indirection to get to the value.

MySQL LIKE IN()?

Just note to anyone trying the REGEXP to use "LIKE IN" functionality.

IN allows you to do:

field IN (
'val1',
'val2',
'val3'
)

In REGEXP this won't work

REGEXP '
val1$|
val2$|
val3$
'

It has to be in one line like this:

REGEXP 'val1$|val2$|val3$'

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

Python [Errno 98] Address already in use

$ ps -fA | grep python
501 81211 12368   0  10:11PM ttys000    0:03.12  
python -m SimpleHTTPServer

$ kill 81211

Javascript Append Child AFTER Element

This suffices :

 parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);

since if the refnode (second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore

Actually I doubt that the || null is required, try it and see.

How can I make an EXE file from a Python program?

Use cx_Freeze to make exe your python program

Using JQuery to open a popup window and print

You should put the print function in your view-details.php file and call it once the file is loaded, by either using

<body onload="window.print()"> 

or

$(document).ready(function () { 
  window.print(); 
});

Refused to apply inline style because it violates the following Content Security Policy directive

Well, I think it is too late and many others have the solution so far.

But I hope this can Help:

I'm using react for an identity server so 'unsafe-inline' is not an option at all. If you look at your console and actually read the CSP docs, you might find that there are three options for solving the issue:

  1. 'unsafe-inline' as it says is unsafe if your project is using CSPs is for one reason and it is like throwing out the complete policy, will be the same to no have CSP policy at all

    1. 'sha-XXXCODE' this is good, safe but not optimal because there is a lot of manual work and every compilation the SHA might change so it will become easily a nightmare, use only when the script or style is unlikely to change and there are few references

    2. Nonce. This is the winner!

Nonce works in the similar way as scripts

CSP HEADER ///csp stuff nonce-12331

<script nonce="12331">
   //script content
</script>

Because the nonce in the csp is the same that the tag, the script will be executed

In the case of inline styles, the nonce also came in the form of attribute so the same rules apply.

so generate the nonce and put it on your inline scritps

If you are using webpack maybe you are using the style-loader

the following code will do the trick


module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              attributes: {
                nonce: '12345678',
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.

How to prevent favicon.ico requests?

In our experience, with Apache falling over on request of favicon.ico, we commented out extra headers in the .htaccess file.

For example we had Header set X-XSS-Protection "1; mode=block"

... but we had forgotten to sudo a2enmod headers beforehand. Commenting out extra headers being sent resolved our favicon.ico issue.

We also had several virtual hosts set up for development, and only failed out with 500 Internal Server Error when using http://localhost and fetching /favicon.ico. If you run "curl -v http://localhost/favicon.ico" and get a warning about the host name not being in the resolver cache or something to that effect, you might experience problems.

It could be as simple as not fetching (we tried that and it didn't work, because our root cause was different) or look around for directives in apache2.conf or .htaccess which might be causing strange 500 Internal Server Error messages.

We found it failed so quickly there was nothing useful in Apache's error logs whatsoever and spent an entire morning changing small things here and there until we resolved the problem of setting extra headers when we had forgotten to have mod_headers loaded!

Maven error: Not authorized, ReasonPhrase:Unauthorized

I have recently encountered this problem. Here are the steps to resolve

  1. Check the servers section in the settings.xml file.Is username and password correct?

_x000D_
_x000D_
<servers>_x000D_
  <server>_x000D_
    <id>serverId</id>_x000D_
    <username>username</username>_x000D_
    <password>password</password>_x000D_
  </server>_x000D_
</servers>
_x000D_
_x000D_
_x000D_

  1. Check the repository section in the pom.xml file.The id of the server tag should be the same as the id of the repository tag.

_x000D_
_x000D_
<repositories>_x000D_
 <repository>_x000D_
   <id>serverId</id>  _x000D_
   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
 </repository>_x000D_
</repositories>
_x000D_
_x000D_
_x000D_

  1. If the repository tag is not configured in the pom.xml file, look in the settings.xml file.

_x000D_
_x000D_
<profiles>_x000D_
 <profile>_x000D_
   <repositories>_x000D_
     <repository>_x000D_
      <id>serverId</id>_x000D_
      <name>aliyun</name>_x000D_
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
     </repository>_x000D_
   </repositories>_x000D_
 </profile>_x000D_
</profiles>
_x000D_
_x000D_
_x000D_

Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.

Difference between app.use and app.get in express.js

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

  • GET /
  • PUT /foo
  • POST /foo/bar
  • etc.

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET /

And, the equivalent routing for your example of app.use() would actually be:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

(Update: Attempting to better demonstrate the differences.)

The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').

Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.

Examples:

  • For simple, static routes:

    app.get('/', function (req, res) {
      // ...
    });
    

    vs.

    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      // ...
    });
    
  • With multiple handlers for the same route:

    app.get('/', authorize('ADMIN'), function (req, res) {
      // ...
    });
    

    vs.

    const authorizeAdmin = authorize('ADMIN');
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET' || req.url !== '/')
        return next();
    
      authorizeAdmin(req, res, function (err) {
        if (err) return next(err);
    
        // ...
      });
    });
    
  • With parameters:

    app.get('/item/:id', function (req, res) {
      let id = req.params.id;
      // ...
    });
    

    vs.

    const pathToRegExp = require('path-to-regexp');
    
    function prepareParams(matches, pathKeys, previousParams) {
      var params = previousParams || {};
    
      // TODO: support repeating keys...
      matches.slice(1).forEach(function (segment, index) {
        let { name } = pathKeys[index];
        params[name] = segment;
      });
    
      return params;
    }
    
    const itemIdKeys = [];
    const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
    
    app.use('/', function (req, res, next) {
      if (req.method !== 'GET') return next();
    
      var urlMatch = itemIdPattern.exec(req.url);
      if (!urlMatch) return next();
    
      if (itemIdKeys && itemIdKeys.length)
        req.params = prepareParams(urlMatch, itemIdKeys, req.params);
    
      let id = req.params.id;
      // ...
    });
    

Note: Express' implementation of these features are contained in its Router, Layer, and Route.

Object not found! The requested URL was not found on this server. localhost

You are not specified your project as right way.

  • So run your XAMPP control panel then start the apache and MySQL
  • Then note the ports.
  • For Example PORT 80: then you type your browser url as localhost:80\ press enter now your php basic Config page is visible.
  • Then create any folder on xampp\htdocs\YourFloderName Then create php file then save it and go to browser then type it localhost\YourFolderName now it listed the files click the file and it runs.

finding first day of the month in python

You can use dateutil.rrule:

In [1]: from dateutil.rrule import *

In [2]: rrule(DAILY, bymonthday=1)[0].date()
Out[2]: datetime.date(2018, 10, 1)

In [3]: rrule(DAILY, bymonthday=1)[1].date()
Out[3]: datetime.date(2018, 11, 1)

Using JavaMail with TLS

Good post, the line

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.

Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.

Submit button not working in Bootstrap form

Replace this

 <button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">

with

<button  value=" Send" class="btn btn-success" type="submit" id="submit">

How do I make a transparent canvas in html5?

I believe you are trying to do exactly what I just tried to do: I want two stacked canvases... the bottom one has a static image and the top one contains animated sprites. Because of the animation, you need to clear the background of the top layer to transparent at the start of rendering every new frame. I finally found the answer: it's not using globalAlpha, and it's not using a rgba() color. The simple, effective answer is:

context.clearRect(0,0,width,height);

Protractor : How to wait for page complete after click a button?

you can do something like this

_x000D_
_x000D_
emailEl.sendKeys('jack');_x000D_
passwordEl.sendKeys('123pwd');_x000D_
_x000D_
btnLoginEl.click().then(function(){_x000D_
browser.wait(5000);_x000D_
});
_x000D_
_x000D_
_x000D_

How can I write these variables into one line of code in C#?

 DateTime dateTime = dateTime.Today.ToString("MM.dd.yyyy");

 Console.Write(dateTime);

How to format an inline code in Confluence?

I use a combination of Zelphir and Peter Gluck's answers. i.e.

  1. (Mac-speak) Click COMMAND + SHIFT + D
  2. Select Markdown in the dropdown of the model pop-up
  3. Surround your text with the code tag - i.e. <code>bovvered</code>
  4. Click INSERT

How do you display a Toast from a background thread on Android?

Kotlin Code with runOnUiThread

runOnUiThread(
        object : Runnable {
            override fun run() {
                Toast.makeText(applicationContext, "Calling from runOnUiThread()", Toast.LENGTH_SHORT)  
            }
        }
)

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Making the main scrollbar always visible

An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.

html { width: 100vw; }

How do I check if a Sql server string is null or empty

SELECT
   CASE WHEN LEN(listing.OfferText) > 0 THEN listing.OfferText 
        ELSE COALESCE(Company.OfferText, '') END 
   AS Offer_Text,

... 

In this example, if listing.OfferText is NULL, the LEN() function should also return NULL, but that's still not > 0.

Update

I've learned some things in the 5 1/2 years since posting this, and do it much differently now:

COALESCE(NULLIF(listing.OfferText,''), Company.OfferText, '')

This is similar to the accepted answer, but it also has a fallback in case Company.OfferText is also null. None of the other current answers using NULLIF() also do this.

Resize an Array while keeping current elements in Java?

You could just use ArrayList which does the job for you.

What exactly is the function of Application.CutCopyMode property in Excel

There is a good explanation at https://stackoverflow.com/a/33833319/903783

The values expected seem to be xlCopy and xlCut according to xlCutCopyMode enumeration (https://msdn.microsoft.com/en-us/VBA/Excel-VBA/articles/xlcutcopymode-enumeration-excel), but the 0 value (this is what False equals to in VBA) seems to be useful to clear Excel data put on the Clipboard.

How to parse JSON data with jQuery / JavaScript?

Use that code.

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

How to simplify a null-safe compareTo() implementation?

See the bottom of this answer for updated (2013) solution using Guava.


This is what I ultimately went with. It turned out we already had a utility method for null-safe String comparison, so the simplest solution was to make use of that. (It's a big codebase; easy to miss this kind of thing :)

public int compareTo(Metadata other) {
    int result = StringUtils.compare(this.getName(), other.getName(), true);
    if (result != 0) {
        return result;
    }
    return StringUtils.compare(this.getValue(), other.getValue(), true);
}

This is how the helper is defined (it's overloaded so that you can also define whether nulls come first or last, if you want):

public static int compare(String s1, String s2, boolean ignoreCase) { ... }

So this is essentially the same as Eddie's answer (although I wouldn't call a static helper method a comparator) and that of uzhin too.

Anyway, in general, I would have strongly favoured Patrick's solution, as I think it's a good practice to use established libraries whenever possible. (Know and use the libraries as Josh Bloch says.) But in this case that would not have yielded the cleanest, simplest code.

Edit (2009): Apache Commons Collections version

Actually, here's a way to make the solution based on Apache Commons NullComparator simpler. Combine it with the case-insensitive Comparator provided in String class:

public static final Comparator<String> NULL_SAFE_COMPARATOR 
    = new NullComparator(String.CASE_INSENSITIVE_ORDER);

@Override
public int compareTo(Metadata other) {
    int result = NULL_SAFE_COMPARATOR.compare(this.name, other.name);
    if (result != 0) {
        return result;
    }
    return NULL_SAFE_COMPARATOR.compare(this.value, other.value);
}

Now this is pretty elegant, I think. (Just one small issue remains: the Commons NullComparator doesn't support generics, so there's an unchecked assignment.)

Update (2013): Guava version

Nearly 5 years later, here's how I'd tackle my original question. If coding in Java, I would (of course) be using Guava. (And quite certainly not Apache Commons.)

Put this constant somewhere, e.g. in "StringUtils" class:

public static final Ordering<String> CASE_INSENSITIVE_NULL_SAFE_ORDER =
    Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast(); // or nullsFirst()

Then, in public class Metadata implements Comparable<Metadata>:

@Override
public int compareTo(Metadata other) {
    int result = CASE_INSENSITIVE_NULL_SAFE_ORDER.compare(this.name, other.name);
    if (result != 0) {
        return result;
    }
    return CASE_INSENSITIVE_NULL_SAFE_ORDER.compare(this.value, other.value);
}    

Of course, this is nearly identical to the Apache Commons version (both use JDK's CASE_INSENSITIVE_ORDER), the use of nullsLast() being the only Guava-specific thing. This version is preferable simply because Guava is preferable, as a dependency, to Commons Collections. (As everyone agrees.)

If you were wondering about Ordering, note that it implements Comparator. It's pretty handy especially for more complex sorting needs, allowing you for example to chain several Orderings using compound(). Read Ordering Explained for more!

Cannot add a project to a Tomcat server in Eclipse

I fixed this issue as adding Dynamic Web Module to Project Facets

  1. right click on project name in the Package Explorer view.
  2. select Properties
  3. Select Project Facets
  4. Activate Dynamic Web Module
  5. Click on OK

How to get the string size in bytes?

You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.

If you want to get size of memory buffer, that contains your string, and you have pointer to it:

  • If it is dynamic array(created with malloc), it is impossible to get it size, since compiler doesn't know what pointer is pointing at. (check this)
  • If it is static array, you can use sizeof to get its size.

If you are confused about difference between dynamic and static arrays, check this.

ImportError: DLL load failed: %1 is not a valid Win32 application

Or you have to rebuild the cv2 module for win 64bit.

HTML <sup /> tag affecting line height, how to make it consistent?

I had the same problem and non of the given answers worked. But I found a git commit with a fix that did work for me:

sup {
  font-size: 0.8em;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
  top: -0.5em;
}

How do I add an element to array in reducer of React native redux?

Two different options to add item to an array without mutation

case ADD_ITEM :
    return { 
        ...state,
        arr: [...state.arr, action.newItem]
    }

OR

case ADD_ITEM :
    return { 
        ...state,
        arr: state.arr.concat(action.newItem)
    }

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Passing an array using an HTML form hidden element

You can use serialize and base64_encode from the client side. After that, then use unserialize and base64_decode on the server side.

Like:

On the client side, use:

    $postvalue = array("a", "b", "c");
    $postvalue = base64_encode(serialize($array));

   // Your form hidden input
   <input type="hidden" name="result" value="<?php echo $postvalue; ?>">

On the server side, use:

    $postvalue = unserialize(base64_decode($_POST['result']));
    print_r($postvalue) // Your desired array data will be printed here

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

SQLiteDatabase.query method

tableColumns

  • null for all columns as in SELECT * FROM ...
  • new String[] { "column1", "column2", ... } for specific columns as in SELECT column1, column2 FROM ... - you can also put complex expressions here:
    new String[] { "(SELECT max(column1) FROM table1) AS max" } would give you a column named max holding the max value of column1

whereClause

  • the part you put after WHERE without that keyword, e.g. "column1 > 5"
  • should include ? for things that are dynamic, e.g. "column1=?" -> see whereArgs

whereArgs

  • specify the content that fills each ? in whereClause in the order they appear

the others

  • just like whereClause the statement after the keyword or null if you don't use it.

Example

String[] tableColumns = new String[] {
    "column1",
    "(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
    "value1",
    "value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
        null, null, orderBy);

// since we have a named column we can do
int idx = c.getColumnIndex("max");

is equivalent to the following raw query

String queryString =
    "SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
    "WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);

By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '.

Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";

because if value contains a ' your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--" might even drop your table since the statement would become two statements and a comment:

SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'

using the args version XYZ'; DROP TABLE table1;-- would be escaped to 'XYZ''; DROP TABLE table1;--' and would only be treated as a value. Even if the ' is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int and other primitives directly into whereClause though)

C# naming convention for constants?

Leave Hungarian to the Hungarians.

In the example I'd even leave out the definitive article and just go with

private const int Answer = 42;

Is that answer or is that the answer?

*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to life, the universe and everything.

c# dictionary one key many values

Here's my approach to achieve this behavior.

For a more comprehensive solution involving ILookup<TKey, TElement>, check out my other answer.

public abstract class Lookup<TKey, TElement> : KeyedCollection<TKey, ICollection<TElement>>
{
  protected override TKey GetKeyForItem(ICollection<TElement> item) =>
    item
    .Select(b => GetKeyForItem(b))
    .Distinct()
    .SingleOrDefault();

  protected abstract TKey GetKeyForItem(TElement item);

  public void Add(TElement item)
  {
    var key = GetKeyForItem(item);
    if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
      collection.Add(item);
    else
      Add(new List<TElement> { item });
  }

  public void Remove(TElement item)
  {
    var key = GetKeyForItem(item);
    if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
    {
      collection.Remove(item);
      if (collection.Count == 0)
        Remove(key);
    }
  }
}

Usage:

public class Item
{
  public string Key { get; }
  public string Value { get; set; }
  public Item(string key, string value = null) { Key = key; Value = value; }
}

public class Lookup : Lookup<string, Item>
{
  protected override string GetKeyForItem(Item item) => item.Key;
}

static void Main(string[] args)
{
  var toRem = new Item("1", "different");
  var single = new Item("2", "single");
  var lookup = new Lookup()
  {
    new Item("1", "hello"),
    new Item("1", "hello2"),
    new Item(""),
    new Item("", "helloo"),
    toRem,
    single
  };

  lookup.Remove(toRem);
  lookup.Remove(single);
}

Note: the key must be immutable (or remove and re-add upon key-change).

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

Don't use Cascade.All until you really have to. Role and Permission have bidirectional manyToMany relation. Then the following code would work fine

    Permission p = new Permission();
    p.setName("help");
    Permission p2 = new Permission();
    p2.setName("self_info");
    p = (Permission)crudRepository.save(p); // returned p has id filled in.
    p2 = (Permission)crudRepository.save(p2); // so does p2.
    Role role = new Role();
    role.setAvailable(true);
    role.setDescription("a test role");
    role.setRole("admin");
    List<Permission> pList = new ArrayList<Permission>();
    pList.add(p);
    pList.add(p2);
    role.setPermissions(pList);
    crudRepository.save(role);

while if the object is just a "new" one, then it would throw the same error.

Python json.loads shows ValueError: Extra data

As you can see in the following example, json.loads (and json.load) does not decode multiple json object.

>>> json.loads('{}')
{}
>>> json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 368, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4)

If you want to dump multiple dictionaries, wrap them in a list, dump the list (instead of dumping dictionaries multiple times)

>>> dict1 = {}
>>> dict2 = {}
>>> json.dumps([dict1, dict2])
'[{}, {}]'
>>> json.loads(json.dumps([dict1, dict2]))
[{}, {}]

How to remove the hash from window.location (URL) with JavaScript without page refresh?

You can do it as below:

history.replaceState({}, document.title, window.location.href.split('#')[0]);

Recursive Fibonacci

int fib(int x) 
{
    if (x < 2)
      return x;
    else 
      return (fib(x - 1) + fib(x - 2));
}

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

PYODBC--Data source name not found and no default driver specified

if any one are trying to access the database which is hosted in azure then try to give the driver as ODBC Driver 17 for SQL Server

Remove empty strings from array while keeping record Without Loop?

var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]

filter documentation


// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]

Arrow functions documentation

How can I open a Shell inside a Vim Window?

Well it depends on your OS - actually I did not test it on MS Windows - but Conque is one of the best plugins out there.

Actually, it can be better, but works.

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

Is there "\n" equivalent in VBscript?

As David and Remou pointed out, vbCrLf if you want a carriage-return-linefeed combination. Otherwise, Chr(13) and Chr(10) (although some VB-derivatives have vbCr and vbLf; VBScript may well have those, worth checking before using Chr).

Angular 2: Get Values of Multiple Checked Checkboxes

I hope this would help someone who has the same problem.

templet.html

<form [formGroup] = "myForm" (ngSubmit) = "confirmFlights(myForm.value)">
  <ng-template ngFor [ngForOf]="flightList" let-flight let-i="index" >
     <input type="checkbox" [value]="flight.id" formControlName="flightid"
         (change)="flightids[i]=[$event.target.checked,$event.target.getAttribute('value')]" >
  </ng-template>
</form>

component.ts

flightids array will have another arrays like this [ [ true, 'id_1'], [ false, 'id_2'], [ true, 'id_3']...] here true means user checked it, false means user checked then unchecked it. The items that user have never checked will not be inserted to the array.

flightids = []; 
confirmFlights(value){  
    //console.log(this.flightids);

    let confirmList = [];
    this.flightids.forEach(id => {
      if(id[0]) // here, true means that user checked the item 
        confirmList.push(this.flightList.find(x => x.id === id[1]));
    });
    //console.log(confirmList);

}

Searching if value exists in a list of objects using Linq

LINQ defines an extension method that is perfect for solving this exact problem:

using System.Linq;
...
    bool has = list.Any(cus => cus.FirstName == "John");

make sure you reference System.Core.dll, that's where LINQ lives.

Change placeholder text

For JavaScript use:

document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";

For jQuery use:

$('.select-holder')[0].placeholder = "This is my new text";

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

I came across the same issue. I tried adding the server in "Server Runtime" but unfortunately that didn't work for me.

What worked for me is, I added javax.servlet-api-3.0.1.jar file in build path. On the other hand If It's a Maven project add dependency for this jar file. This would definitely work.

prevent iphone default keyboard when focusing an <input>

I asked a similar question here and got a fantastic answer - use the iPhone native datepicker - it's great.

How to turn off iPhone keypad for a specified input field on web page

Synopsis / pseudo-code:

if small screen mobile device 

  set field type to "date" - e.g. document.getElementById('my_field').type = "date";
  // input fields of type "date" invoke the iPhone datepicker.

else

  init datepicker - e.g. $("#my_field").datepicker();

The reason for dynamically setting the field type to "date" is that Opera will pop up its own native datepicker otherwise, and I'm assuming you want to show the datepicker consistently on desktop browsers.

How to find the kth largest element in an unsorted array of length n in O(n)?

You do like quicksort. Pick an element at random and shove everything either higher or lower. At this point you'll know which element you actually picked, and if it is the kth element you're done, otherwise you repeat with the bin (higher or lower), that the kth element would fall in. Statistically speaking, the time it takes to find the kth element grows with n, O(n).

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

You can still force the use of the soft x86 emulator by running it from the command line and using the -no-accel option, i.e. from the SDK/tools directory:

emulator -avd AVD_NAME -memory 768 -no-accel -gpu on

BUT this still won't work with the current (V24) SDK, because the current x86 system images crash the soft x86 emulator :-(

The only way I got this working again was to downgrade the SDK tools to V22.3 from here: http://dl-ssl.google.com/android/repository/tools_r22.3-windows.zip and to buld an AVD using a downgraded system image, for instance https://dl-ssl.google.com/android/repository/sys-img/android/sysimg_x86-17_r02.zip. (So this is no help if you need to test on more recent versions of Android).

Google have moved on to an updated version of their emulator based on a more recent version of qemu, and provide binaries for arm and mips emulators, but have omitted to ship the x86 equivalent (there is no emulator-ranchu-x86.exe and emulator64-ranchu-x86.exe). If they did so, or if someone else went to the trouble of setting up and compiling their emulator source with the "x86" flag on, then _x86 soft emulation could conceivably be made to work again.

The requested resource does not support HTTP method 'GET'

just use this attribute

[System.Web.Http.HttpGet]

not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

How do I put a border around an Android textview?

You can create custom background for your text view. Steps 1. Go to your project. 2. Go to resources and right click to drawable. 3. Click on New -> Drawable Resource File 4. Give name to you file 5. Paste following code in the file

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="@color/colorBlack" />
<padding android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp" />
<corners android:radius="6dp" />
<solid android:color="#ffffffff" />

  1. For your text view where you want to use it as backgroud,

    android:background="@drawable/your_fileName"

JPA Hibernate One-to-One relationship

You just need to add @JoinColumn(name="column_name") to Host Entity relation . column_name is the database column name in person table.

@Entity
public class Person {
    @Id
    public int id;

    @OneToOne
    @JoinColumn(name="other_info")
    public OtherInfo otherInfo;

    rest of attributes ...
}

Person has a one-to-one relationship with OtherInfo: mappedBy="var_name" var_name is variable name for otherInfo in Person class.

@Entity
public class OtherInfo {
    @Id
    @OneToOne(mappedBy="otherInfo")
    public Person person;

    rest of attributes ...
}

mysql query result in php variable

$query="SELECT * FROM contacts";
$result=mysql_query($query);

Twitter Bootstrap Multilevel Dropdown Menu

I just added class="span2" to the <li> for the dropdown items and that worked.

Round double value to 2 decimal places

To remove the decimals from your double, take a look at this output

Obj C

double hellodouble = 10.025;
NSLog(@"Your value with 2 decimals: %.2f", hellodouble);
NSLog(@"Your value with no decimals: %.0f", hellodouble);

The output will be:

10.02 
10

Swift 2.1 and Xcode 7.2.1

let hellodouble:Double = 3.14159265358979
print(String(format:"Your value with 2 decimals: %.2f", hellodouble))
print(String(format:"Your value with no decimals: %.0f", hellodouble))

The output will be:

3.14 
3

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

PHP - auto refreshing page

Maybe use this code,

<meta http-equiv="refresh" content = "30" />

take it be easy

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

Explanation of <script type = "text/template"> ... </script>

By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).

<script type="text/template">I am a Micro template. 
  I am going to make your web page faster.</script>

For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/

R: Plotting a 3D surface from x, y, z

You can use the function outer() to generate it.

Have a look at the demo for the function persp(), which is a base graphics function to draw perspective plots for surfaces.

Here is their first example:

x <- seq(-10, 10, length.out = 50)  
y <- x  
rotsinc <- function(x,y) {
    sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }  
    10 * sinc( sqrt(x^2+y^2) )  
}

z <- outer(x, y, rotsinc)  
persp(x, y, z)

The same applies to surface3d():

require(rgl)  
surface3d(x, y, z)

C++ JSON Serialization

There is no reflection in C++. True. But if the compiler can't provide you the metadata you need, you can provide it yourself.

Let's start by making a property struct:

template<typename Class, typename T>
struct PropertyImpl {
    constexpr PropertyImpl(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}

    using Type = T;

    T Class::*member;
    const char* name;
};

template<typename Class, typename T>
constexpr auto property(T Class::*member, const char* name) {
    return PropertyImpl<Class, T>{member, name};
}

Of course, you also can have a property that takes a setter and getter instead of a pointer to member, and maybe read only properties for calculated value you'd like to serialize. If you use C++17, you can extend it further to make a property that works with lambdas.

Ok, now we have the building block of our compile-time introspection system.

Now in your class Dog, add your metadata:

struct Dog {
    std::string barkType;
    std::string color;
    int weight = 0;

    bool operator==(const Dog& rhs) const {
        return std::tie(barkType, color, weight) == std::tie(rhs.barkType, rhs.color, rhs.weight);
    }

    constexpr static auto properties = std::make_tuple(
        property(&Dog::barkType, "barkType"),
        property(&Dog::color, "color"),
        property(&Dog::weight, "weight")
    );
};

We will need to iterate on that list. To iterate on a tuple, there are many ways, but my preferred one is this:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    using unpack_t = int[];
    (void)unpack_t{(static_cast<void>(f(std::integral_constant<T, S>{})), 0)..., 0};
}

If C++17 fold expressions are available in your compiler, then for_sequence can be simplified to:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    (static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}

This will call a function for each constant in the integer sequence.

If this method don't work or gives trouble to your compiler, you can always use the array expansion trick.

Now that you have the desired metadata and tools, you can iterate through the properties to unserialize:

// unserialize function
template<typename T>
T fromJson(const Json::Value& data) {
    T object;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;

    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // get the type of the property
        using Type = typename decltype(property)::Type;

        // set the value to the member
        // you can also replace `asAny` by `fromJson` to recursively serialize
        object.*(property.member) = Json::asAny<Type>(data[property.name]);
    });

    return object;
}

And for serialize:

template<typename T>
Json::Value toJson(const T& object) {
    Json::Value data;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;

    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // set the value to the member
        data[property.name] = object.*(property.member);
    });

    return data;
}

If you want recursive serialization and unserialization, you can replace asAny by fromJson.

Now you can use your functions like this:

Dog dog;

dog.color = "green";
dog.barkType = "whaf";
dog.weight = 30;

Json::Value jsonDog = toJson(dog); // produces {"color":"green", "barkType":"whaf", "weight": 30}
auto dog2 = fromJson<Dog>(jsonDog);

std::cout << std::boolalpha << (dog == dog2) << std::endl; // pass the test, both dog are equal!

Done! No need for run-time reflection, just some C++14 goodness!

This code could benefit from some improvement, and could of course work with C++11 with some ajustements.

Note that one would need to write the asAny function. It's just a function that takes a Json::Value and call the right as... function, or another fromJson.

Here's a complete, working example made from the various code snippet of this answer. Feel free to use it.

As mentionned in the comments, this code won't work with msvc. Please refer to this question if you want a compatible code: Pointer to member: works in GCC but not in VS2015

How to check for file existence

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.

What is the difference between atomic / volatile / synchronized?

volatile:

volatile is a keyword. volatile forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.

AtomicXXX:

AtomicXXX classes support lock-free thread-safe programming on single variables. These AtomicXXX classes (like AtomicInteger) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.

When to use: Multiple threads can read and modify data.

synchronized:

synchronized is keyword used to guard a method or code block. By making method as synchronized has two effects:

  1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

  2. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations

AtomicXXX is equivalent of volatile + synchronized even though the implementation is different. AmtomicXXX extends volatile variables + compareAndSet methods but does not use synchronization.

Related SE questions:

Difference between volatile and synchronized in Java

Volatile boolean vs AtomicBoolean

Good articles to read: ( Above content is taken from these documentation pages)

https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

How to post object and List using postman

In case of simple example if your api is below

@POST
    @Path("update_accounts")
    @Consumes(MediaType.APPLICATION_JSON)
    @PermissionRequired(Permissions.UPDATE_ACCOUNTS)
    void createLimit(List<AccountUpdateRequest> requestList) throws RuntimeException;

where AccountUpdateRequest :

public class AccountUpdateRequest {
    private Long accountId;
    private AccountType accountType;
    private BigDecimal amount;
...
}

then your postman request would be: http://localhost:port/update_accounts

[
         {
            "accountType": "LEDGER",
            "accountId": 11111,
            "amount": 100
         },
         {
            "accountType": "LEDGER",
            "accountId": 2222,
            "amount": 300
          },
         {
            "accountType": "LEDGER",
            "accountId": 3333,
            "amount": 1000
          }
]

Set up adb on Mac OS X

Here is a step wise information :

Step-1

Start up Terminal and go to your home folder.

cd ~/

Step-2

Open and edit .bash_profile file

$ open -e .bash_profile

If you don’t have .bash_profile file in your computer path, then create one. Enter below command to create a new file. Once created follow Step-2.

touch .bash_profile

Step-3

Save the below line)

export PATH=${PATH}:/Applications/adt-bundle-mac-x86_64-20140321/sdk/tools
export PATH=${PATH}:/Applications/adt-bundle-mac-x86_64-20140321/sdk/platform-tools

Step-4

Refresh the file using below command

$ source .bash_profile

$ echo $PATH

You should see your android path set in the output now.

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

Change action bar color in android

Maybe this can help you also. It's from the website:

http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…

<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">

Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.

<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Light">
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
    </style>

    <style name="WindowTitleBackground">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

That’s it!

Mapping list in Yaml to list of objects in Spring Boot

I had referenced this article and many others and did not find a clear cut concise response to help. I am offering my discovery, arrived at with some references from this thread, in the following:

Spring-Boot version: 1.3.5.RELEASE

Spring-Core version: 4.2.6.RELEASE

Dependency Management: Brixton.SR1

The following is the pertinent yaml excerpt:

tools:
  toolList:
    - 
      name: jira
      matchUrl: http://someJiraUrl
    - 
      name: bamboo
      matchUrl: http://someBambooUrl

I created a Tools.class:

@Component
@ConfigurationProperties(prefix = "tools")
public class Tools{
    private List<Tool> toolList = new ArrayList<>();
    public Tools(){
      //empty ctor
    }

    public List<Tool> getToolList(){
        return toolList;
    }

    public void setToolList(List<Tool> tools){
       this.toolList = tools;
    }
}

I created a Tool.class:

@Component
public class Tool{
    private String name;
    private String matchUrl;

    public Tool(){
      //empty ctor
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
       this.name= name;
    }
    public String getMatchUrl(){
        return matchUrl;
    }

    public void setMatchUrl(String matchUrl){
       this.matchUrl= matchUrl;
    }

    @Override
    public String toString(){
        StringBuffer sb = new StringBuffer();
        String ls = System.lineSeparator();
        sb.append(ls);
        sb.append("name:  " + name);
        sb.append(ls);
        sb.append("matchUrl:  " + matchUrl);
        sb.append(ls);
    }
}

I used this combination in another class through @Autowired

@Component
public class SomeOtherClass{

   private Logger logger = LoggerFactory.getLogger(SomeOtherClass.class);

   @Autowired
   private Tools tools;

   /* excluded non-related code */

   @PostConstruct
   private void init(){
       List<Tool>  toolList = tools.getToolList();
       if(toolList.size() > 0){
           for(Tool t: toolList){
               logger.info(t.toString());
           }
       }else{
           logger.info("*****-----     tool size is zero     -----*****");
       }  
   }

   /* excluded non-related code */

}

And in my logs the name and matching url's were logged. This was developed on another machine and thus I had to retype all of the above so please forgive me in advance if I inadvertently mistyped.

I hope this consolidation comment is helpful to many and I thank the previous contributors to this thread!

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

How to compare variables to undefined, if I don’t know whether they exist?

if (obj === undefined)
{
    // Create obj
}

If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.

Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.

Is it possible to assign numeric value to an enum in Java?

I realize this is an older question, but it comes up first in a Google search, and among the excellent answers provided, I didn't see anything fully comprehensive, so I did a little more digging and I ended up writing an enum class that not only allowed me to assign multiple custom values to the enum constants, I even added a method that allows me to assign values to them on the fly during code execution.

This enum class is for a "server" program that I run on a Raspberry Pi. The program receives commands from a client then it executes terminal commands that make adjustments to a webcam that is affixed to my 3D printer.

Using the Linux program 'v4l2-ctl' on the Pi, you can extract all of the possible adjustment commands for a given attached webcam, which also provides the setting datatype, the min and max values, the number of value steps in a given value range etc., so I took all of those and put them in an enum and created an enum interface that makes it easy to both set and get values for each command as well as a simple method to get the actual terminal command that is executed (using the Process and Runtime classes) in order to adjust the setting.

It is a rather large class and I apologize for that, but for me, it's always easier to learn something when I can see it working in full context, so I decided not to scale it down. However, even though it's large, it is definitely simple and it should be obvious what's happening in the class with minimal effort.

package constants;

import java.util.HashMap;
import java.util.Map;

public enum PICam {
    BRIGHTNESS                  ("brightness",                  0,      "int",      0,      100,    1,  50),
    CONTRAST                    ("contrast",                    1,      "int",      100,    100,    1,  0),
    SATURATION                  ("saturation",                  2,      "int",      100,    100,    1,  0),
    RED_BALANCE                 ("red_balance",                 3,      "intmenu",  1,      7999,   1,  1000),
    BLUE_BALANCE                ("blue_balance",                4,      "int",      1,      7999,   1,  1000),
    HORIZONTAL_FLIP             ("horizontal_flip",             5,      "bool",     0,      1,      1,  0),
    VERTICAL_FLIP               ("vertical_flip",               6,      "bool",     0,      1,      1,  0),
    POWER_LINE_FREQUENCY        ("power_line_frequency",        7,      "menu",     0,      3,      1,  1),
    SHARPNESS                   ("sharpness",                   8,      "int",      100,    100,    1,  0),
    COLOR_EFFECTS               ("color_effects",               9,      "menu",     0,      15,     1,  0),
    ROTATE                      ("rotate",                      10,     "int",      0,      360,    90, 0),
    COLOR_EFFECTS_CBCR          ("color_effects_cbcr",          11,     "int",      0,      65535,  1,  32896),
    VIDEO_BITRATE_MODE          ("video_bitrate_mode",          12,     "menu",     0,      1,      1,  0),
    VIDEO_BITRATE               ("video_bitrate",               13,     "int",      25000,  25000000,   25000,  10000000),
    REPEAT_SEQUENCE_HEADER      ("repeat_sequence_header",      14,     "bool",     0,      1,      1,  0),
    H264_I_FRAME_PERIOD         ("h_264_i_frame_period",        15,     "int",      0,      2147483647,1,   60),
    H264_LEVEL                  ("h_264_level",                 16,     "menu",     0,      11,     1,  11),
    H264_PROFILE                ("h_264_profile",               17,     "menu",     0,      4,      1,  4),
    AUTO_EXPOSURE               ("auto_exposure",               18,     "menu",     0,      3,      1,  0),
    EXPOSURE_TIME_ABSOLUTE      ("exposure_time_absolute",      19,     "int",      1,      10000,  1,  1000),
    EXPOSURE_DYNAMIC_FRAMERATE  ("exposure_dynamic_framerate",  20,     "bool",     0,      1,      1,  0),
    AUTO_EXPOSURE_BIAS          ("auto_exposure_bias",          21,     "intmenu",  0,      24,     1,  12),
    WHITE_BALANCE_AUTO_PRESET   ("white_balance_auto_preset",   22,     "menu",     0,      9,      1,  1),
    IMAGE_STABILIZATION         ("image_stabilization",         23,     "bool",     0,      1,      1,  0),
    ISO_SENSITIVITY             ("iso_sensitivity",             24,     "intmenu",  0,      4,      1,  0),
    ISO_SENSITIVITY_AUTO        ("iso_sensitivity_auto",        25,     "menu",     0,      1,      1,  1),
    EXPOSURE_METERING_MODE      ("exposure_metering_mode",      26,     "menu",     0,      2,      1,  0),
    SCENE_MODE                  ("scene_mode",                  27,     "menu",     0,      13,     1,  0),
    COMPRESSION_QUALITY         ("compression_quality",         28,     "int",      1,      100,    1,  30);


    private static final Map<String, PICam>    LABEL_MAP       = new HashMap<>();
    private static final Map<Integer, PICam>   INDEX_MAP       = new HashMap<>();
    private static final Map<String, PICam>    TYPE_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   MIN_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   MAX_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   STEP_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   DEFAULT_MAP     = new HashMap<>();
    private static final Map<Integer, Integer> THIS_VALUE_MAP  = new HashMap<>();

    private static final String                baseCommandLine = "/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=";

    static {
        for (PICam e: values()) {
            LABEL_MAP.put(e.label, e);
            INDEX_MAP.put(e.index, e);
            TYPE_MAP.put(e.type, e);
            MIN_MAP.put(e.min, e);
            MAX_MAP.put(e.max, e);
            STEP_MAP.put(e.step, e);
            DEFAULT_MAP.put(e.defaultValue, e);
        }
    }

    public final String label;
    public final int index;
    public final String type;
    public final int min;
    public final int max;
    public final int step;
    public final int defaultValue;

    private PICam(String label, int index, String type, int min, int max, int step, int defaultValue) {
        this.label = label;
        this.index = index;
        this.type = type;
        this.min = min;
        this.max = max;
        this.step = step;
        this.defaultValue = defaultValue;
    }

    public static void setValue(Integer index, Integer value) {
        if (THIS_VALUE_MAP.containsKey(index)) THIS_VALUE_MAP.replace(index, value);
        else THIS_VALUE_MAP.put(index, value);
    }

    public Integer getValue (Integer index) {
        return THIS_VALUE_MAP.getOrDefault(index, null);
    }

    public static PICam getLabel(String label) {
        return LABEL_MAP.get(label);
    }

    public static PICam getType(String type) {
        return TYPE_MAP.get(type);
    }

    public static PICam getMin(int min) {
        return MIN_MAP.get(min);
    }

    public static PICam getMax(int max) {
        return MAX_MAP.get(max);
    }

    public static PICam getStep(int step) {
        return STEP_MAP.get(step);
    }

    public static PICam getDefault(int defaultValue) {
        return DEFAULT_MAP.get(defaultValue);
    }

    public static String getCommandFor(int index, int newValue) {
        PICam picam = INDEX_MAP.get(index);
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam picam, Integer newValue) {
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(picam.index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam piCam) {
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }

    public static String getCommandFor(Integer index) {
        PICam piCam = INDEX_MAP.get(index);
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }
}

Here are some ways that the class can be interacted with:

This code:

public static void test() {
    PICam.setValue(0,127); //Set brightness to 125
    PICam.setValue(PICam.SHARPNESS,143); //Set sharpness to 125
    String command1 = PICam.getSetCommandStringFor(PICam.BRIGHTNESS); //Get command line string to include the brightness value that we previously set referencing it by enum constant.
    String command2 = PICam.getSetCommandStringFor(0); //Get command line string to include the brightness value that we previously set referencing it by index number.
    String command3 = PICam.getDefaultCamString(PICam.BRIGHTNESS); //Get command line string with the default value
    String command4 = PICam.getSetCommandStringFor(PICam.SHARPNESS); //Get command line string with the sharpness value that we previously set.
    String command5 = PICam.getDefaultCamString(PICam.SHARPNESS); //Get command line string with the default sharpness value.
    System.out.println(command1);
    System.out.println(command2);
    System.out.println(command3);
    System.out.println(command4);
    System.out.println(command5);
}

Produces these results:

/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=50
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=143
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=0

How to get past the login page with Wget?

I had the same problem. My solution was to do the login via Chrome and save the cookies data to a text file. This is easily done with this Chrome extension: Chrome cookie.txt export extension.

When you get the cookies data, there is also an example on how to use them with wget. A simple copy-paste command line is provided to you.

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

I Get the same message, when using Intel XHAM emulator (instead of ARM) and have "Use Host GPU" option enabled. I belive when you disable it, it goes away.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

>>> import ctypes
>>> s = 'abcdef'
>>> mutable = ctypes.create_string_buffer(s)
>>> for i in range(0,len(s),2):
>>>     mutable[i], mutable[i+1] = mutable[i+1], mutable[i]
>>> s = mutable.value
>>> print s
badcfe

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

using where and inner join in mysql

Try this :

SELECT
    (
      SELECT
          `NAME`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
    ) as `NAME`
FROM
     school_locations
WHERE
     (
      SELECT
          `TYPE`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
     ) = 'coun';

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

How to make (link)button function as hyperlink?

There is a middle way. If you want a HTML control but you need to access it server side you can simply add the runat="server" attribute:

<a runat="server" Id="lnkBack">Back</a>

You can then alter the href server side using Attributes

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       lnkBack.Attributes.Add("href", url);
    }
}

resulting in:

<a id="ctl00_ctl00_mainContentPlaceHolder_contentPlaceHolder_lnkBack" 
      href="url.aspx">Back</a>

How to set the maximum memory usage for JVM?

The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.

That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.

Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.

Setting a max height on a table

Use divs with max height and min height around the content that needs to scroll.

<tr>
    <td>
        <div>content</div>
    </td>
</tr>

td div{
    max-height:20px;
}

https://jsfiddle.net/ethanabrace/4w0ksczr/

How to open maximized window with Javascript?

The best solution I could find at present time to open a window maximized is (Internet Explorer 11, Chrome 49, Firefox 45):

  var popup = window.open("your_url", "popup", "fullscreen");
  if (popup.outerWidth < screen.availWidth || popup.outerHeight < screen.availHeight)
  {
    popup.moveTo(0,0);
    popup.resizeTo(screen.availWidth, screen.availHeight);
  }

see https://jsfiddle.net/8xwocrp6/7/

Note 1: It does not work on Edge (13.1058686). Not sure whether it's a bug or if it's as designed (I've filled a bug report, we'll see what they have to say about it). Here is a workaround:

if (navigator.userAgent.match(/Edge\/\d+/g))
{
    return window.open("your_url", "popup", "width=" + screen.width + ",height=" + screen.height);
}

Note 2: moveTo or resizeTo will not work (Access denied) if the window you are opening is on another domain.

Volatile boolean vs AtomicBoolean

If you have only one thread modifying your boolean, you can use a volatile boolean (usually you do this to define a stop variable checked in the thread's main loop).

However, if you have multiple threads modifying the boolean, you should use an AtomicBoolean. Else, the following code is not safe:

boolean r = !myVolatileBoolean;

This operation is done in two steps:

  1. The boolean value is read.
  2. The boolean value is written.

If an other thread modify the value between #1 and 2#, you might got a wrong result. AtomicBoolean methods avoid this problem by doing steps #1 and #2 atomically.

Regular expression for letters, numbers and - _

[A-Za-z0-9_.-]*

This will also match for empty strings, if you do not want that exchange the last * for an +

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

Add up a column of numbers at the Unix shell

if you don't have bc installed, try

echo $(( $(... | paste -sd+ -) ))

instead of

... | paste -sd+ - | bc

$( ) <-- return the value of executing the command

$(( 1+2 )) <-- return the evaluated results

echo <-- echo it to the screen

How to set default font family for entire Android app

With the release of Android Oreo you can use the support library to reach this goal.

  1. Check in your app build.gradle if you have the support library >= 26.0.0
  2. Add "font" folder to your resources folder and add your fonts there
  3. Reference your default font family in your app main style:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <item name="android:fontFamily">@font/your_font</item>
       <item name="fontFamily">@font/your_font</item> <!-- target android sdk versions < 26 and > 14 if theme other than AppCompat -->
    </style>
    

Check https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html for more detailed information.

CSS - Expand float child DIV height to parent's height

I learned of this neat trick in an internship interview. The original question is how do you ensure the height of each top component in three columns have the same height that shows all the content available. Basically create a child component that is invisible that renders the maximum possible height.

<div class="parent">
    <div class="assert-height invisible">
        <!-- content -->
    </div>
    <div class="shown">
        <!-- content -->
    </div>
</div>

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

How to kill a while loop with a keystroke?

From following this thread down the rabbit hole, I came to this, works on Win10 and Ubuntu 20.04. I wanted more than just killing the script, and to use specific keys, and it had to work in both MS and Linux..

import _thread
import time
import sys
import os

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        msvcrt_char = msvcrt.getch()
        return msvcrt_char.decode("utf-8")

def input_thread(key_press_list):
    char = 'x'
    while char != 'q': #dont keep doing this after trying to quit, or 'stty sane' wont work
        time.sleep(0.05)
        getch = _Getch()
        char = getch.impl()
        pprint("getch: "+ str(char))
        key_press_list.append(char)

def quitScript():
    pprint("QUITTING...")
    time.sleep(0.2) #wait for the thread to die
    os.system('stty sane')
    sys.exit()

def pprint(string_to_print): #terminal is in raw mode so we need to append \r\n
    print(string_to_print, end="\r\n")

def main():
    key_press_list = []
    _thread.start_new_thread(input_thread, (key_press_list,))
    while True:
        #do your things here
        pprint("tick")
        time.sleep(0.5)

        if key_press_list == ['q']:
            key_press_list.clear()
            quitScript()

        elif key_press_list == ['j']:
            key_press_list.clear()
            pprint("knock knock..")

        elif key_press_list:
            key_press_list.clear()

main()

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How to check cordova android version of a cordova/phonegap project?

After upgrading the Application. I observed different Cordova versions.

  1. Apache Cordova Cli version which is 6.0.0.
  2. Cordova Android version which is 5.1.0.
  3. Cordova IOS version which is 4.1.1.
  4. Docs version is which is 6.0.0, shown on the Cordova Docs website.

Now i am confused, On which version basis, Google Dev Console is giving warning?

Please migrate your app(s) to Apache Cordova v.4.1.1 or higher as soon as possible and increment the version number of the upgraded APK. Beginning May 9, 2016, Google Play will block publishing of any new apps or updates that use pre-4.1.1 versions of Apache Cordova.

The vulnerabilities were addressed in Apache Cordova 4.1.1. If you’re using a 3rd party library that bundles Apache Cordova, you’ll need to upgrade it to a version that bundles Apache Cordova 4.1.1 or later.

And before upgrading. Our Application versions were these.

  1. Apache Cordova Cli version which is 5.4.1.
  2. Cordova Android version which is 4.1.1.
  3. Cordova IOS version which is 3.9.1.
  4. Docs version is which is 5.4.1, shown on the Cordova Docs website.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:

python -V

I hope it helps

C read file line by line

//open and get the file handle
FILE* fh;
fopen_s(&fh, filename, "r");

//check if file exists
if (fh == NULL){
    printf("file does not exists %s", filename);
    return 0;
}


//read line by line
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, fh) != NULL)  {
    printf(line);
}
free(line);    // dont forget to free heap memory

Microsoft Excel ActiveX Controls Disabled?

Simplified instructions for end-users. Feel free to copy/paste the following.

Here’s how to fix the problem when it comes up:

  1. Close all your Office programs and files.
  2. Open Windows Explorer and type %TEMP% into the address bar, then press Enter. This will take you into the system temporary folder.
  3. Locate and delete the following folders: Excel8.0, VBE, Word8.0
  4. Now try to use your file again, it shouldn't have any problems.

You might need to wait until the problem occurs in order for this fix to work. Applying it prematurely (before the Windows Update gets installed on your system) won't help.

create unique id with javascript

const uid = function(){
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

This Function generates very unique IDs that are sorted by its generated Date. Also useable for IDs in Databases.

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

How should I have explained the difference between an Interface and an Abstract class?

From what I understand and how I approach,

Interface is like a specification/contract, any class that implements an interface class have to implement all the methods defined in the abstract class (except default methods (introduced in Java 8))

Whereas I define a class abstract when I know the implementation required for some methods of the class and some methods I still do not know what will be the implementation (we might know the function signature but not the implementation). I do this so that later in the part of development when I know how these methods are to be implemented, I can just extend this abstract class and implement these methods.

Note: You cannot have function body in interface methods unless the method is static or default.

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind has its problems too.When you try to use angular filters, limit or something else, you maybe can have problem if you use ng-bind. But in other case, ng-bind is better in UX side.when user opens a page, he/she will see (10ms-100ms) that print symbols ( {{ ... }} ), that's why ng-bind is better.

How do I run .sh or .bat files from Terminal?

The .sh is for *nix systems and .bat should be for Windows. Since your example shows a bash error and you mention Terminal, I'm assuming it's OS X you're using.

In this case you should go to the folder and type:

./startup.sh

./ just means that you should call the script located in the current directory. (Alternatively, just type the full path of the startup.sh). If it doesn't work then, check if startup.sh has execute permissions.

How to get address of a pointer in c/c++?

In C++ you can do:

// Declaration and assign variable a
int a = 7;
// Declaration pointer b
int* b;
// Assign address of variable a to pointer b
b = &a;

// Declaration pointer c
int** c;
// Assign address of pointer b to pointer c
c = &b;

std::cout << "a: " << a << "\n";       // Print value of variable a
std::cout << "&a: " << &a << "\n";     // Print address of variable a

std::cout << "" << "" << "\n";

std::cout << "b: " << b << "\n";       // Print address of variable a
std::cout << "*b: " << *b << "\n";     // Print value of variable a
std::cout << "&b: " << &b << "\n";     // Print address of pointer b

std::cout << "" << "" << "\n";

std::cout << "c: " << c << "\n";       // Print address of pointer b
std::cout << "**c: " << **c << "\n";   // Print value of variable a
std::cout << "*c: " << *c << "\n";     // Print address of variable a
std::cout << "&c: " << &c << "\n";     // Print address of pointer c

Convert php array to Javascript

You do not have to call parseJSON since the output of json_encode is a javascript literal. Just assign it to a js variable.

<script type="text/javascript">
    //Assign php generated json to JavaScript variable
    var tempArray = <?php echo json_encode($php_array); ?>;

   //You will be able to access the properties as 
    alert(tempArray[0].Key);
</script>

Left function in c#

It's the Substring method of String, with the first argument set to 0.

 myString.Substring(0,1);

[The following was added by Almo; see Justin J Stark's comment. —Peter O.]

Warning: If the string's length is less than the number of characters you're taking, you'll get an ArgumentOutOfRangeException.

bootstrap jquery show.bs.modal event won't fire

Make sure that you really use the bootstrap jquery modal and not another jquery modal.

Wasted way too much time on this...

How to convert a string of bytes into an int?

In Python 2.x, you could use the format specifiers <B for unsigned bytes, and <b for signed bytes with struct.unpack/struct.pack.

E.g:

Let x = '\xff\x10\x11'

data_ints = struct.unpack('<' + 'B'*len(x), x) # [255, 16, 17]

And:

data_bytes = struct.pack('<' + 'B'*len(data_ints), *data_ints) # '\xff\x10\x11'

That * is required!

See https://docs.python.org/2/library/struct.html#format-characters for a list of the format specifiers.

ClientScript.RegisterClientScriptBlock?

The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.

Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )

Guessing the problem

If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.

Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.

Amazon S3 boto - how to create a folder?

There is no concept of folders or directories in S3. You can create file names like "abc/xys/uvw/123.jpg", which many S3 access tools like S3Fox show like a directory structure, but it's actually just a single file in a bucket.

Edit and Continue: "Changes are not allowed when..."

That happens when the debugger hasn't hit a breakpoint or you haven't hit Break All (pause). It couldn't be that simple could it?

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

I uninstalled the NDK since I didn't need it . Go to SDK manager on Android studio ( Tools -> Android -> SDK Manager ) . If NDK is installed . Just uncheck the box and click OK . The installed components will be deleted .

Alter user defined type in SQL Server

1.Rename the old UDT,
2.Execute query , 3.Drop the old UDT.

Postgresql: Scripting psql execution with password

It can be done simply using PGPASSWORD. I am using psql 9.5.10. In your case the solution would be

PGPASSWORD=password psql -U myuser < myscript.sql

When does System.gc() do something?

Most JVMs will kick off a GC (depending on the -XX:DiableExplicitGC and -XX:+ExplicitGCInvokesConcurrent switch). But the specification is just less well defined in order to allow better implementations later on.

The spec needs clarification: Bug #6668279: (spec) System.gc() should indicate that we don't recommend use and don't guarantee behaviour

Internally the gc method is used by RMI and NIO, and they require synchronous execution, which: this is currently in discussion:

Bug #5025281: Allow System.gc() to trigger concurrent (not stop-the-world) full collections

HTML-Tooltip position relative to mouse pointer

I prefer this technique:

_x000D_
_x000D_
function showTooltip(e) {_x000D_
  var tooltip = e.target.classList.contains("tooltip")_x000D_
      ? e.target_x000D_
      : e.target.querySelector(":scope .tooltip");_x000D_
  tooltip.style.left =_x000D_
      (e.pageX + tooltip.clientWidth + 10 < document.body.clientWidth)_x000D_
          ? (e.pageX + 10 + "px")_x000D_
          : (document.body.clientWidth + 5 - tooltip.clientWidth + "px");_x000D_
  tooltip.style.top =_x000D_
      (e.pageY + tooltip.clientHeight + 10 < document.body.clientHeight)_x000D_
          ? (e.pageY + 10 + "px")_x000D_
          : (document.body.clientHeight + 5 - tooltip.clientHeight + "px");_x000D_
}_x000D_
_x000D_
var tooltips = document.querySelectorAll('.couponcode');_x000D_
for(var i = 0; i < tooltips.length; i++) {_x000D_
  tooltips[i].addEventListener('mousemove', showTooltip);_x000D_
}
_x000D_
.couponcode {_x000D_
    color: red;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
.couponcode:hover .tooltip {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    white-space: nowrap;_x000D_
    display: none;_x000D_
    background: #ffffcc;_x000D_
    border: 1px solid black;_x000D_
    padding: 5px;_x000D_
    z-index: 1000;_x000D_
    color: black;_x000D_
}
_x000D_
Lorem ipsum dolor sit amet, <span class="couponcode">consectetur_x000D_
adipiscing<span class="tooltip">This is a tooltip</span></span>_x000D_
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi_x000D_
ut aliquip ex ea commodo consequat. Duis aute irure dolor in <span_x000D_
class="couponcode">reprehenderit<span class="tooltip">This is_x000D_
another tooltip</span></span> in voluptate velit esse cillum dolore eu_x000D_
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,_x000D_
sunt in culpa qui officia deserunt mollit anim id est <span_x000D_
class="couponcode">laborum<span class="tooltip">This is yet_x000D_
another tooltip</span></span>.
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

How to convert a Title to a URL slug in jQuery?

More powerful slug generation method on pure JavaScript. It's basically support transliteration for all Cyrillic characters and many Umlauts (German, Danish, France, Turkish, Ukrainian and etc.) but can be easily extended.

_x000D_
_x000D_
function makeSlug(str)_x000D_
{_x000D_
  var from="? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? a a ä á à â å c c e e e é è ê æ g g ö ó ø ? ô o ? ? n ? r s ü ß r l d þ h ? i ï í î j k l n n n r š s t u ú û ? ù ü u u ý ÿ ž z z ç ? ?".split(' ');_x000D_
  var to=  "a b v g d e e zh z i y k l m n o p r s t u f h ts ch sh shch # y # e yu ya a a ae a a a a c c e e e e e e e g g oe o o o o o m n n p r s ue ss r l d th h h i i i i j k l n n n r s s t u u u u u u u u y y z z z c ye g".split(' ');_x000D_
 _x000D_
  str = str.toLowerCase();_x000D_
  _x000D_
  // remove simple HTML tags_x000D_
  str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
  str = str.replace(/(<\/[a-z0-9\-]{1,15}[\s]*>)/gi, '');_x000D_
  str = str.replace(/(<[a-z0-9\-]{1,15}[\s]*\/>)/gi, '');_x000D_
  _x000D_
  str = str.replace(/^\s+|\s+$/gm,''); // trim spaces_x000D_
  _x000D_
  for(i=0; i<from.length; ++i)_x000D_
    str = str.split(from[i]).join(to[i]);_x000D_
  _x000D_
  // Replace different kind of spaces with dashes_x000D_
  var spaces = [/(&nbsp;|&#160;|&#32;)/gi, /(&mdash;|&ndash;|&#8209;)/gi,_x000D_
     /[(_|=|\\|\,|\.|!)]+/gi, /\s/gi];_x000D_
_x000D_
  for(i=0; i<from.length; ++i)_x000D_
   str = str.replace(spaces[i], '-');_x000D_
  str = str.replace(/-{2,}/g, "-");_x000D_
_x000D_
  // remove special chars like &amp;_x000D_
  str = str.replace(/&[a-z]{2,7};/gi, '');_x000D_
  str = str.replace(/&#[0-9]{1,6};/gi, '');_x000D_
  str = str.replace(/&#x[0-9a-f]{1,6};/gi, '');_x000D_
  _x000D_
  str = str.replace(/[^a-z0-9\-]+/gmi, ""); // remove all other stuff_x000D_
  str = str.replace(/^\-+|\-+$/gm,''); // trim edges_x000D_
  _x000D_
  return str;_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementsByTagName('pre')[0].innerHTML = makeSlug(" <br/> &#x202A;???&amp;???<strong>??_????</strong>?…???????????\r???\n?&ndash;??????&nbsp;??????\t \n?\t??????&#180;?&nbsp;??\\?????&ndash;????????\t????.Danke schön!ich heiße=?áÞÿá-Skånske,København çagatay rí gé tor zöldülésetekrol - . ");
_x000D_
<div>_x000D_
  <pre>Hello world!</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml contains the necessary slf4j dependencies, e.g.:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.0</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
    </dependency>

How to convert an OrderedDict into a regular dict in python3

If you are looking for a recursive version without using the json module:

def ordereddict_to_dict(value):
    for k, v in value.items():
        if isinstance(v, dict):
            value[k] = ordereddict_to_dict(v)
    return dict(value)

What is the difference between a process and a thread?

Threads within the same process share the Memory, but each thread has its own stack and registers, and threads store thread-specific data in the heap. Threads never execute independently, so the inter-thread communication is much faster when compared to inter-process communication.

Processes never share the same memory. When a child process creates it duplicates the memory location of the parent process. Process communication is done by using pipe, shared memory, and message parsing. Context switching between threads is very slow.

Angular 5, HTML, boolean on checkbox is checked

Here is my answer,

In row.model.ts

export interface Row {
   otherProperty : type;
   checked : bool;
   otherProperty : type;
   ...
}

In .html

<tr class="even" *ngFor="let item of rows">
   <input [checked]="item.checked" type="checkbox">
</tr>

In .ts

rows : Row[] = [];

update the rows in component.ts

detect back button click in browser

Please try this (if the browser does not support "onbeforeunload"):

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }

});

How to check if a process is in hang state (Linux)

Is there any command in Linux through which i can know if the process is in hang state.

There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):

  • run ps to find list of PIDs of the watched processes (along with exec time, etc)
  • loop over the PIDs
  • start gdb attaching to the process using its PID, dumping stack trace from it using thread apply all where, detaching from the process
  • a process was declared hung if:
    • its stack trace didn't change and time didn't change after 3 checks
    • its stack trace didn't change and time was indicating 100% CPU load after 3 checks
  • hung process was killed to give a chance for a monitoring application to restart the hung instance.

But that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.

Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.

The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".

is vs typeof

This should answer that question, and then some.

The second line, if (obj.GetType() == typeof(ClassA)) {}, is faster, for those that don't want to read the article.

(Be aware that they don't do the same thing)

Get Application Directory

There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):

getApplicationInfo().dataDir

http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()

Which is better, return value or out parameter?

There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.

However There are some slight differences , but non of them are really important:

Using out parameter will enforce you to use two lines like:

int n;
GetValue(n);

while using return value will let you do it in one line:

int n = GetValue();

Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return, while using OUT parameter will not necessarily do so.

Simple way to encode a string according to a password?

Here's an implementation of URL Safe encryption and Decryption using AES(PyCrypto) and base64.

import base64
from Crypto import Random
from Crypto.Cipher import AES

AKEY = b'mysixteenbytekey' # AES key must be either 16, 24, or 32 bytes long

iv = Random.new().read(AES.block_size)

def encode(message):
    obj = AES.new(AKEY, AES.MODE_CFB, iv)
    return base64.urlsafe_b64encode(obj.encrypt(message))

def decode(cipher):
    obj2 = AES.new(AKEY, AES.MODE_CFB, iv)
    return obj2.decrypt(base64.urlsafe_b64decode(cipher))

If you face some issue like this https://bugs.python.org/issue4329 (TypeError: character mapping must return integer, None or unicode) use str(cipher) while decoding as follows:

return obj2.decrypt(base64.urlsafe_b64decode(str(cipher)))

Test:

In [13]: encode(b"Hello World")
Out[13]: b'67jjg-8_RyaJ-28='

In [14]: %timeit encode("Hello World")
100000 loops, best of 3: 13.9 µs per loop

In [15]: decode(b'67jjg-8_RyaJ-28=')
Out[15]: b'Hello World'

In [16]: %timeit decode(b'67jjg-8_RyaJ-28=')
100000 loops, best of 3: 15.2 µs per loop

Converting datetime.date to UTC timestamp in Python

Using the arrow package:

>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, 
    tm_hour=0, tm_min=0, tm_sec=0, 
    tm_wday=4, tm_yday=365, tm_isdst=0)

Set space between divs

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Request-scoped beans can be autowired with the request object.

private @Autowired HttpServletRequest request;

Send response to all clients except sender

Updated the list for further documentation.

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.

Hope this helps.

How to fully clean bin and obj folders within Visual Studio?

Update: Visual Studio 2019 (Clean [bin] and [obj] before release). However I am not sure if [obj] needs to be deleted. Be aware there is nuget package configuration placed too. You can remove the second line if you think so.

<Target Name="PreBuild" BeforeTargets="PreBuildEvent" Condition="'$(Configuration)' == 'Release'">
  <!--remove bin-->
  <Exec Command="rd /s /q &quot;$(ProjectDir)$(BaseOutputPath)&quot; &amp;&amp; ^" />
  <!--remove obj-->
  <Exec Command="rd /s /q &quot;$(BaseIntermediateOutputPath)Release&quot;" />
</Target>

Double.TryParse or Convert.ToDouble - which is faster and safer?

Lots of hate for the Convert class here... Just to balance a little bit, there is one advantage for Convert - if you are handed an object,

Convert.ToDouble(o);

can just return the value easily if o is already a Double (or an int or anything readily castable).

Using Double.Parse or Double.TryParse is great if you already have it in a string, but

Double.Parse(o.ToString());

has to go make the string to be parsed first and depending on your input that could be more expensive.

How to resolve symbolic links in a shell script

Note: I believe this to be a solid, portable, ready-made solution, which is invariably lengthy for that very reason.

Below is a fully POSIX-compliant script / function that is therefore cross-platform (works on macOS too, whose readlink still doesn't support -f as of 10.12 (Sierra)) - it uses only POSIX shell language features and only POSIX-compliant utility calls.

It is a portable implementation of GNU's readlink -e (the stricter version of readlink -f).

You can run the script with sh or source the function in bash, ksh, and zsh:

For instance, inside a script you can use it as follows to get the running's script true directory of origin, with symlinks resolved:

trueScriptDir=$(dirname -- "$(rreadlink "$0")")

rreadlink script / function definition:

The code was adapted with gratitude from this answer.
I've also created a bash-based stand-alone utility version here, which you can install with
npm install rreadlink -g, if you have Node.js installed.

#!/bin/sh

# SYNOPSIS
#   rreadlink <fileOrDirPath>
# DESCRIPTION
#   Resolves <fileOrDirPath> to its ultimate target, if it is a symlink, and
#   prints its canonical path. If it is not a symlink, its own canonical path
#   is printed.
#   A broken symlink causes an error that reports the non-existent target.
# LIMITATIONS
#   - Won't work with filenames with embedded newlines or filenames containing 
#     the string ' -> '.
# COMPATIBILITY
#   This is a fully POSIX-compliant implementation of what GNU readlink's
#    -e option does.
# EXAMPLE
#   In a shell script, use the following to get that script's true directory of origin:
#     trueScriptDir=$(dirname -- "$(rreadlink "$0")")
rreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.

  target=$1 fname= targetDir= CDPATH=

  # Try to make the execution environment as predictable as possible:
  # All commands below are invoked via `command`, so we must make sure that
  # `command` itself is not redefined as an alias or shell function.
  # (Note that command is too inconsistent across shells, so we don't use it.)
  # `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not 
  # even have an external utility version of it (e.g, Ubuntu).
  # `command` bypasses aliases and shell functions and also finds builtins 
  # in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for
  # that to happen.
  { \unalias command; \unset -f command; } >/dev/null 2>&1
  [ -n "$ZSH_VERSION" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [ -L "$target" ] || [ -e "$target" ] || { command printf '%s\n' "ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [ "$fname" = '/' ] && fname='' # !! curiously, `basename /` returns '/'
      if [ -L "$fname" ]; then
        # Extract [next] target path, which may be defined
        # *relative* to the symlink's own directory.
        # Note: We parse `ls -l` output to find the symlink target
        #       which is the only POSIX-compliant, albeit somewhat fragile, way.
        target=$(command ls -l "$fname")
        target=${target#* -> }
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.
  if [ "$fname" = '.' ]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [ "$fname" = '..' ]; then
    # Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied
    # AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

rreadlink "$@"

A tangent on security:

jarno, in reference to the function ensuring that builtin command is not shadowed by an alias or shell function of the same name, asks in a comment:

What if unalias or unset and [ are set as aliases or shell functions?

The motivation behind rreadlink ensuring that command has its original meaning is to use it to bypass (benign) convenience aliases and functions often used to shadow standard commands in interactive shells, such as redefining ls to include favorite options.

I think it's safe to say that unless you're dealing with an untrusted, malicious environment, worrying about unalias or unset - or, for that matter, while, do, ... - being redefined is not a concern.

There is something that the function must rely on to have its original meaning and behavior - there is no way around that.
That POSIX-like shells allow redefinition of builtins and even language keywords is inherently a security risk (and writing paranoid code is hard in general).

To address your concerns specifically:

The function relies on unalias and unset having their original meaning. Having them redefined as shell functions in a manner that alters their behavior would be a problem; redefinition as an alias is not necessarily a concern, because quoting (part of) the command name (e.g., \unalias) bypasses aliases.

However, quoting is not an option for shell keywords (while, for, if, do, ...) and while shell keywords do take precedence over shell functions, in bash and zsh aliases have the highest precedence, so to guard against shell-keyword redefinitions you must run unalias with their names (although in non-interactive bash shells (such as scripts) aliases are not expanded by default - only if shopt -s expand_aliases is explicitly called first).

To ensure that unalias - as a builtin - has its original meaning, you must use \unset on it first, which requires that unset have its original meaning:

unset is a shell builtin, so to ensure that it is invoked as such, you'd have to make sure that it itself is not redefined as a function. While you can bypass an alias form with quoting, you cannot bypass a shell-function form - catch 22.

Thus, unless you can rely on unset to have its original meaning, from what I can tell, there is no guaranteed way to defend against all malicious redefinitions.

Remove HTML Tags in Javascript with Regex

Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.

urlencoded Forward slash is breaking URL

In Apache, AllowEncodedSlashes On would prevent the request from being immediately rejected with a 404.

Just another idea on how to fix this.

How to detect idle time in JavaScript elegantly?

Tried @freddoo solution but it didn't work for 1 minute timeouts so I've changed it slightly to record the date+time when the user last clicked on the page and in my timerIncrement function I calculate the difference between the current time and the last clicked time and if the value happens to be bigger or equal to the timeout value then I redirect:

var clickedDate = new Date();
var idleTime = 1;//

function timerIncrement() {

    var nowDate = new Date();
    var diffMs = (nowDate - clickedDate); //Milliseconds between now & the last time a user clicked somewhere on the page
    var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); //Convert ms to minutes

    if (diffMins >= idleTime) {
        //Redirect user to home page etc...
    }
}

$(document).ready(function () {

    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    $(this).click(function (e) {
        clickedDate = new Date();
    });

});

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

I had this problem because of a trigger not working..Worked after I deleted the trigger.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Another option would be using flexbox.

While it's not supported by IE8 and IE9, you could consider:

  • Not minding about those old IE versions
  • Providing a fallback
  • Using a polyfill

Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  width: 100%;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    background-color: #4C4;_x000D_
    min-height: 50px;_x000D_
    width: 100%;_x000D_
}_x000D_
footer {_x000D_
    background-color: #4C4;_x000D_
    min-height: 30px;_x000D_
    width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

How do I set default value of select box in angularjs

As per the docs select, the following piece of code worked for me.

<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
  ng-options="option.name for option in data.availableOptions track by     option.id"
  ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>

Installing NumPy via Anaconda in Windows

Anaconda folder basically resides in C:\Users\\Anaconda. Try setting the PATH to this folder.

Structs data type in php?

Closest you'd get to a struct is an object with all members public.

class MyStruct {
    public $foo;
    public $bar;
}

$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';

I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.

How to loop through a collection that supports IEnumerable?

foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{

}

JavaScript regex for alphanumeric string with length of 3-5 chars

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

Getting return value from stored procedure in C#

This Line of code returns Store StoredProcedure returned value from SQL Server

cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Direction = System.Data.ParameterDirection.ReturnValue;                
cmd.ExecuteNonQuery();

Atfer Execution of query value will returned from SP

id = (int)cmd.Parameters["@id"].Value;

Get current URL from IFRAME

Some additional information for anyone who might be struggling with this:

You'll be getting null values if you're trying to get URL from iframe before it's loaded. I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:

var iframe = document.createElement('iframe');
iframe.onload = function() {

    //some custom settings
    this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";

    var href = iframe.contentWindow.location.href;
    var origin = iframe.contentWindow.location.origin;
    var url = iframe.contentWindow.location.url;
    var path = iframe.contentWindow.location.pathname;

    console.log("href: ", href)
    console.log("origin: ", origin)
    console.log("path: ", path)
    console.log("url: ", url)
};

iframe.src = 'http://localhost/folder/index.html';

document.body.appendChild(iframe);

Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.

Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

Java using enum with switch statement

Short associative function example:

public String getIcon(TipoNotificacao tipo)
{
    switch (tipo){
        case Comentou : return "fa fa-comments";
        case ConviteEnviou : return "icon-envelope";
        case ConviteAceitou : return "fa fa-bolt";
        default: return "";
    }
}

Like @Dhanushka said, omit the qualifier inside "switch" is the key.

Get data from php array - AJAX - jQuery

When you echo $array;, the result is Array, result[0] then represents the first character in Array which is A.

One way to handle this problem would be like this:

ajax.php

<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
    echo $a.",";
?>

jquery code

$(function(){ /* short for $(document).ready(function(){ */

    $('#prev').click(function(){

        $.ajax({type:    'POST',
                 url:     'ajax.php',
                 data:    'id=testdata',
                 cache:   false,
                 success: function(data){
                     var tmp = data.split(",");
                     $('#content1').html(tmp[0]);
                 }
                });
    });

});

Check if instance is of a type

Yes, the "is" keyword:

if (c is TForm)
{
    ...
}

See details on MSDN: http://msdn.microsoft.com/en-us/library/scekt9xw(VS.80).aspx

Checks if an object is compatible with a given type. For example, it can be determined if an object is compatible with the string type like this:

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

Is this what you're asking for?

int[] numbers = { 1, 2, 3 };
numbers.ToList().ForEach(n => Console.WriteLine(n));

How do I perform HTML decoding/encoding using Python/Django?

I found this in the Cheetah source code (here)

htmlCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
    """ Returns the ASCII decoded version of the given HTML string. This does
        NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
    for code in codes:
        s = s.replace(code[1], code[0])
    return s

not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)

i noticed your title asked for encode too, so here is Cheetah's encode function.

def htmlEncode(s, codes=htmlCodes):
    """ Returns the HTML encoded version of the given string. This is useful to
        display a plain ASCII text string on a web page."""
    for code in codes:
        s = s.replace(code[0], code[1])
    return s

.toLowerCase not working, replacement function?

var ans = 334 + '';
var temp = ans.toLowerCase();
alert(temp);

Excel add one hour

=A1+TIME(1,0,0)

Although, maybe this should be posted on Super User.