Programs & Examples On #Pyramid

A Python-based web framework provided by the Pylons Project.

import error: 'No module named' *does* exist

I've had this problem too, I had just forgotten to type workon myproject in the terminal before executing my program.

How to wrap async function calls into a sync function in Node.js or Javascript?

You shouldn't be looking at what happens around the call that creates the fiber but rather at what happens inside the fiber. Once you are inside the fiber you can program in sync style. For example:

function f1() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);   
}

function f2() {
    f1();
    f1();
}

Fiber(function() {
    f2();
}).run();

Inside the fiber you call f1, f2 and sleep as if they were sync.

In a typical web application, you will create the Fiber in your HTTP request dispatcher. Once you've done that you can write all your request handling logic in sync style, even if it calls async functions (fs, databases, etc.).

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

How to get the host name of the current machine as defined in the Ansible hosts file?

You can limit the scope of a playbook by changing the hosts header in its plays without relying on your special host label ‘local’ in your inventory. Localhost does not need a special line in inventories.

- name: run on all except local
  hosts: all:!local

python - checking odd/even numbers and changing outputs on number size

def main():
    n = float(input('odd:'))
    while n % 2 == 0:
        #if n % 2 == 1: No need for these lines as if it were true the while loop would not have been entered.
            #break not required as the while condition will break loop
        n = float(input('odd:'))


    for i in range(int((n+1)/2)):
        print(' '*i+'*'*int((n-2*i))+' '*i)

main()

#1st part ensures that it is an odd number that was entered.2nd part does the printing of triangular

How do I create a new line in Javascript?

Use a <br> tag to create a line break in the document

document.write("<br>");

Here's a sample fiddle

How can I calculate an md5 checksum of a directory?

There are two more solutions:

Create:

du -csxb /path | md5sum > file

ls -alR -I dev -I run -I sys -I tmp -I proc /path | md5sum > /tmp/file

Check:

du -csxb /path | md5sum -c file

ls -alR -I dev -I run -I sys -I tmp -I proc /path | md5sum -c /tmp/file

Rails: How can I set default values in ActiveRecord?

The problem with the after_initialize solutions is that you have to add an after_initialize to every single object you look up out of the DB, regardless of whether you access this attribute or not. I suggest a lazy-loaded approach.

The attribute methods (getters) are of course methods themselves, so you can override them and provide a default. Something like:

Class Foo < ActiveRecord::Base
  # has a DB column/field atttribute called 'status'
  def status
    (val = read_attribute(:status)).nil? ? 'ACTIVE' : val
  end
end

Unless, like someone pointed out, you need to do Foo.find_by_status('ACTIVE'). In that case I think you'd really need to set the default in your database constraints, if the DB supports it.

PHP date add 5 year to current date

try this ,

$presentyear = '2013-08-16 12:00:00';

$nextyear  = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($presentyear )),   date("d",strtotime($presentyear )),   date("Y",strtotime($presentyear ))+5));

echo $nextyear;

C++ Singleton design pattern

I did not find a CRTP implementation among the answers, so here it is:

template<typename HeirT>
class Singleton
{
public:
    Singleton() = delete;

    Singleton(const Singleton &) = delete;

    Singleton &operator=(const Singleton &) = delete;

    static HeirT &instance()
    {
        static HeirT instance;
        return instance;
    }
};

To use just inherit your class from this, like: class Test : public Singleton<Test>

Replace multiple strings with multiple other strings

This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

String.prototype.fmt = function (hash) {
        var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}

You would invoke it as follows:

var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'

Class has no objects member

How about suppressing errors on each line specific to each error?

Something like this: https://pylint.readthedocs.io/en/latest/user_guide/message-control.html

Error: [pylint] Class 'class_name' has no 'member_name' member It can be suppressed on that line by:

  # pylint: disable=no-member

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

Actually, you can achieve this pretty easy. Simply specify the line height as a number:

<p style="line-height:1.5">
    <span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
    <span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>

The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.

For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.

CSS Circle with border

Here is a jsfiddle so you can see an example of this working.

HTML code:

<div class="circle"></div>

CSS code:

_x000D_
_x000D_
.circle {_x000D_
        /*This creates a 1px solid red border around your element(div) */_x000D_
        border:1px solid red;_x000D_
        background-color: #FFFFFF;_x000D_
        height: 100px;_x000D_
        /* border-radius 50% will make it fully rounded. */_x000D_
        border-radius: 50%;_x000D_
        -moz-border-radius:50%;_x000D_
        -webkit-border-radius: 50%;_x000D_
        width: 100px;_x000D_
    }
_x000D_
<div class='circle'></div>
_x000D_
_x000D_
_x000D_

How to set TextView textStyle such as bold, italic

Try this:

TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

I have observed a quote ' in your 1st line and also at the end of your last line.

'using System.Collections.Generic;

Is this present in your original code or some formatting mistake?

Shell script to copy files from one location to another location and rename add the current date to every file

In bash, provided you files names have no spaces:

cd /home/webapps/project1/folder1
for f in *.csv
do 
   cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done

How to get current user who's accessing an ASP.NET application?

The quick answer is User = System.Web.HttpContext.Current.User

Ensure your web.config has the following authentication element.

<configuration>
    <system.web>
        <authentication mode="Windows" />
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</configuration>

Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

How do I get ruby to print a full backtrace instead of a truncated one?

You could also do this if you'd like a simple one-liner:

puts caller

Drawing circles with System.Drawing

You'll need to use DrawEllipse if you want to draw a circle using GDI+.

An example is here: http://www.websupergoo.com/helpig6net/source/3-examples/9-drawgdi.htm

How to get the currently logged in user's user id in Django?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

The current user is in request object, you can get it by:

def sample_view(request):
    current_user = request.user
    print current_user.id

request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

There is no rule. I find CTEs more readable, and use them unless they exhibit some performance problem, in which case I investigate the actual problem rather than guess that the CTE is the problem and try to re-write it using a different approach. There is usually more to the issue than the way I chose to declaratively state my intentions with the query.

There are certainly cases when you can unravel CTEs or remove subqueries and replace them with a #temp table and reduce duration. This can be due to various things, such as stale stats, the inability to even get accurate stats (e.g. joining to a table-valued function), parallelism, or even the inability to generate an optimal plan because of the complexity of the query (in which case breaking it up may give the optimizer a fighting chance). But there are also cases where the I/O involved with creating a #temp table can outweigh the other performance aspects that may make a particular plan shape using a CTE less attractive.

Quite honestly, there are way too many variables to provide a "correct" answer to your question. There is no predictable way to know when a query may tip in favor of one approach or another - just know that, in theory, the same semantics for a CTE or a single subquery should execute the exact same. I think your question would be more valuable if you present some cases where this is not true - it may be that you have discovered a limitation in the optimizer (or discovered a known one), or it may be that your queries are not semantically equivalent or that one contains an element that thwarts optimization.

So I would suggest writing the query in a way that seems most natural to you, and only deviate when you discover an actual performance problem the optimizer is having. Personally I rank them CTE, then subquery, with #temp table being a last resort.

How to Deserialize JSON data?

You can write your own JSON parser and make it more generic based on your requirement. Here is one which served my purpose nicely, hope will help you too.

class JsonParsor
{
    public static DataTable JsonParse(String rawJson)
    {
        DataTable dataTable = new DataTable();
        Dictionary<string, string> outdict = new Dictionary<string, string>();
        StringBuilder keybufferbuilder = new StringBuilder();
        StringBuilder valuebufferbuilder = new StringBuilder();
        StringReader bufferreader = new StringReader(rawJson);
        int s = 0;
        bool reading = false;
        bool inside_string = false;
        bool reading_value = false;
        bool reading_number = false;
        while (s >= 0)
        {
            s = bufferreader.Read();
            //open JSON
            if (!reading)
            {
                if ((char)s == '{' && !inside_string && !reading)
                {
                    reading = true;
                    continue;
                }
                if ((char)s == '}' && !inside_string && !reading)
                    break;
                if ((char)s == ']' && !inside_string && !reading)
                    continue;
                if ((char)s == ',')
                    continue;
            }
            else
            {
                if (reading_value)
                {
                    if (!inside_string && (char)s >= '0' && (char)s <= '9')
                    {
                        reading_number = true;
                        valuebufferbuilder.Append((char)s);
                        continue;
                    }
                }
                //if we find a quote and we are not yet inside a string, advance and get inside
                if (!inside_string)
                {
                    if ((char)s == '\"' && !inside_string)
                        inside_string = true;
                    if ((char)s == '[' && !inside_string)
                    {
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                                reading = false;
                                inside_string = false;
                                reading_value = false;
                    }
                    if ((char)s == ',' && !inside_string && reading_number)
                    {
                        if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                            dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                        if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                        keybufferbuilder.Length = 0;
                        valuebufferbuilder.Length = 0;
                        reading_value = false;
                        reading_number = false;
                    }
                    continue;
                }

                //if we reach end of the string
                if (inside_string)
                {
                    if ((char)s == '\"')
                    {
                        inside_string = false;
                        s = bufferreader.Read();
                        if ((char)s == ':')
                        {
                            reading_value = true;
                            continue;
                        }
                        if (reading_value && (char)s == ',')
                        {
                            //put the key-value pair into dictionary
                            if(!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(),typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                            outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            keybufferbuilder.Length = 0;
                            valuebufferbuilder.Length = 0;
                            reading_value = false;
                        }
                        if (reading_value && (char)s == '}')
                        {
                            if (!dataTable.Columns.Contains(keybufferbuilder.ToString()))
                                dataTable.Columns.Add(keybufferbuilder.ToString(), typeof(string));
                            if (!outdict.ContainsKey(keybufferbuilder.ToString()))
                                outdict.Add(keybufferbuilder.ToString(), valuebufferbuilder.ToString());
                            ICollection key = outdict.Keys;
                            DataRow newrow = dataTable.NewRow();
                            foreach (string k_loopVariable in key)
                            {
                                CommonModule.LogTheMessage(outdict[k_loopVariable],"","","");
                                newrow[k_loopVariable] = outdict[k_loopVariable];
                            }
                            dataTable.Rows.Add(newrow);
                            CommonModule.LogTheMessage(dataTable.Rows.Count.ToString(), "", "row_count", "");
                            outdict.Clear();
                            keybufferbuilder.Length=0;
                            valuebufferbuilder.Length=0;
                            reading_value = false;
                            reading = false;
                            continue;
                        }
                    }
                    else
                    {
                        if (reading_value)
                        {
                            valuebufferbuilder.Append((char)s);
                            continue;
                        }
                        else
                        {
                            keybufferbuilder.Append((char)s);
                            continue;
                        }
                    }
                }
                else
                {
                    switch ((char)s)
                    {
                        case ':':
                            reading_value = true;
                            break;
                        default:
                            if (reading_value)
                            {
                                valuebufferbuilder.Append((char)s);
                            }
                            else
                            {
                                keybufferbuilder.Append((char)s);
                            }
                            break;
                    }
                }
            }
        }

        return dataTable;
    }
}

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

Python 3 turn range to a list

Use Range in Python 3.

Here is a example function that return in between numbers from two numbers

def get_between_numbers(a, b):
    """
    This function will return in between numbers from two numbers.
    :param a:
    :param b:
    :return:
    """
    x = []
    if b < a:
        x.extend(range(b, a))
        x.append(a)
    else:
        x.extend(range(a, b))
        x.append(b)

    return x

Result

print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))

[5, 6, 7, 8, 9]  
[5, 6, 7, 8, 9]

How exactly does __attribute__((constructor)) work?

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
   printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

How to check if a string array contains one string in JavaScript?

Create this function prototype:

Array.prototype.contains = function ( needle ) {
   for (i in this) {
      if (this[i] == needle) return true;
   }
   return false;
}

and then you can use following code to search in array x

if (x.contains('searchedString')) {
    // do a
}
else
{
      // do b
}

Shorten string without cutting words in JavaScript

I took a different approach. While I needed a similar result I wanted to keep my return value less than the specified length.

function wordTrim(value, length, overflowSuffix) {
    value = value.trim();
    if (value.length <= length) return value;
    var strAry = value.split(' ');
    var retString = strAry[0];
    for (var i = 1; i < strAry.length; i++) {
        if (retString.length >= length || retString.length + strAry[i].length + 1 > length) break;
        retString += " " + strAry[i];
    }
    return retString + (overflowSuffix || '');
}

Edit I refactored it a bit here: JSFiddle Example. It rejoins the original array instead of concatenating.

function wordTrim(value, length, overflowSuffix) {
    if (value.length <= length) return value;
    var strAry = value.split(' ');
    var retLen = strAry[0].length;
    for (var i = 1; i < strAry.length; i++) {
        if(retLen == length || retLen + strAry[i].length + 1 > length) break;
        retLen+= strAry[i].length + 1
    }
    return strAry.slice(0,i).join(' ') + (overflowSuffix || '');
}

Installing R with Homebrew

This is what actually worked for me on OSX Yosemite.

brew install cask
brew install Caskroom/cask/xquartz
brew install r

How to concatenate int values in java?

Couldn't you just make the numbers strings, concatenate them, and convert the strings to an integer value?

JSON forEach get Key and Value

Use forEach in combo with Object.entries().

_x000D_
_x000D_
const WALLPAPERS = [{
  WALLPAPER_KEY: 'wallpaper.image',
  WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
  WALLPAPER_KEY: 'lockscreen.image',
  WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];

WALLPAPERS.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(`${key} - ${value}`);
  }
});
_x000D_
_x000D_
_x000D_

Evaluating string "3*(4+2)" yield int 18

This is a simple Expression Evaluator using Stacks

public class MathEvaluator
{
    public static void Run()
    {
        Eval("(1+2)");
        Eval("5*4/2");
        Eval("((3+5)-6)");
    }

    public static void Eval(string input)
    {
        var ans = Evaluate(input);
        Console.WriteLine(input + " = " + ans);
    }

    public static double Evaluate(String input)
    {
        String expr = "(" + input + ")";
        Stack<String> ops = new Stack<String>();
        Stack<Double> vals = new Stack<Double>();

        for (int i = 0; i < expr.Length; i++)
        {
            String s = expr.Substring(i, 1);
            if (s.Equals("(")){}
            else if (s.Equals("+")) ops.Push(s);
            else if (s.Equals("-")) ops.Push(s);
            else if (s.Equals("*")) ops.Push(s);
            else if (s.Equals("/")) ops.Push(s);
            else if (s.Equals("sqrt")) ops.Push(s);
            else if (s.Equals(")"))
            {
                int count = ops.Count;
                while (count > 0)
                {
                    String op = ops.Pop();
                    double v = vals.Pop();
                    if (op.Equals("+")) v = vals.Pop() + v;
                    else if (op.Equals("-")) v = vals.Pop() - v;
                    else if (op.Equals("*")) v = vals.Pop()*v;
                    else if (op.Equals("/")) v = vals.Pop()/v;
                    else if (op.Equals("sqrt")) v = Math.Sqrt(v);
                    vals.Push(v);

                    count--;
                }
            }
            else vals.Push(Double.Parse(s));
        }
        return vals.Pop();
    }
}

Install MySQL on Ubuntu without a password prompt

This should do the trick

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

Of course, it leaves you with a blank root password - so you'll want to run something like

mysqladmin -u root password mysecretpasswordgoeshere

Afterwards to add a password to the account.

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

Allow only numeric value in textbox using Javascript

Here is a solution which blocks all non numeric input from being entered into the text-field.

html

<input type="text" id="numbersOnly" />

javascript

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};?

Convert integers to strings to create output filenames at run time

I already showed this elsewhere on SO (How to use a variable in the format specifier statement? , not an exact duplicate IMHO), but I think it is worthwhile to place it here. It is possible to use the techniques from other answers for this question to make a simple function

function itoa(i) result(res)
  character(:),allocatable :: res
  integer,intent(in) :: i
  character(range(i)+2) :: tmp
  write(tmp,'(i0)') i
  res = trim(tmp)
end function

which you can use after without worrying about trimming and left-adjusting and without writing to a temporary variable:

OPEN(1, FILE = 'Output'//itoa(i)//'.TXT')

It requires Fortran 2003 because of the allocatable string.

downloading all the files in a directory with cURL

OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.

First of all, you need to create a batch (script) file for the ftp program, containing instructions for it. Name it as you want, and put into it:

curl -u login:pass ftp.myftpsite.com/iiumlabs* -O

open ftp.myftpsite.com
login
pass
mget *
quit

The first line opens a connection to the ftp server at ftp.myftpsite.com. The two following lines specify the login, and the password which ftp will ask for (replace login and pass with just the login and password, without any keywords). Then, you use mget * to get all files. Instead of the *, you can use any wildcard. Finally, you use quit to close the ftp program without interactive prompt.

If you needed to enter some directory first, add a cd command before mget. It should be pretty straightforward.

Finally, write that file and run ftp like this:

ftp -i -s:yourscript

where -i disables interactivity (asking before downloading files), and -s specifies path to the script you created.


Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp which is practically the PuTTy counter-part of the openssh scp command.

The syntax is similar to copy command, and it supports wildcards:

pscp -batch [email protected]:iiumlabs* .

If you authenticate using a key file, you should pass it using -i path-to-key-file. If you use password, -pw pass. It can also reuse sessions saved using PuTTy, using the load -load your-session-name argument.

How can I output the value of an enum class in C++11

Unlike an unscoped enumeration, a scoped enumeration is not implicitly convertible to its integer value. You need to explicitly convert it to an integer using a cast:

std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl;

You may want to encapsulate the logic into a function template:

template <typename Enumeration>
auto as_integer(Enumeration const value)
    -> typename std::underlying_type<Enumeration>::type
{
    return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}

used as:

std::cout << as_integer(a) << std::endl;

How to remove all white spaces from a given text file

Easiest way for me ->

        echo "Hello my name is Donald" | sed  s/\ //g

6 digits regular expression

^[0-9]{1,6}$ should do it. I don't know VB.NET good enough to know if it's the same there.

For examples, have a look at the Wikipedia.

Extension gd is missing from your system - laravel composer Update

It may not be enabled for php-cli, you can enable like this;

sudo phpenmod gd

UPDATE

I guess, you are using ppa:ondrej php package (5.6), which is confusing you with default ubuntu 14.04 php package (5.5.9).

To install php 5.6 gd library from ppa:ondrej, you should use:

sudo apt-get install php5.6-gd

Visual Studio C# IntelliSense not automatically displaying

Deleted the .suo file in solution folder to solve the problem.

Get the last element of a std::string

You probably want to check the length of the string first and do something like this:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

Retrieving values from nested JSON Object

You will have to iterate step by step into nested JSON.

for e.g a JSON received from Google geocoding api

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Madhya Pradesh",
               "short_name" : "MP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Bhopal, Madhya Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            },
            "location" : {
               "lat" : 23.2599333,
               "lng" : 77.412615
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            }
         },
         "place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615

//recieve JSON in json object

        JSONObject json = new JSONObject(output.toString());
        JSONArray result = json.getJSONArray("results");
        JSONObject result1 = result.getJSONObject(0);
        JSONObject geometry = result1.getJSONObject("geometry");
        JSONObject locat = geometry.getJSONObject("location");

        //"iterate onto level of location";

        double lat = locat.getDouble("lat");
        double lng = locat.getDouble("lng");

CSS hover vs. JavaScript mouseover

In Internet Explorer, there must be declared a <!DOCTYPE> for the :hover selector to work on other elements than the <a> element.

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.

The one I've just found and I could absolutely recommend is The Uniform Server

It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.

They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!

Versions in Uniform Server as of today:

  • Apache 2.4.2
  • MySQL 5.5.23-community
  • PHP 5.4.1
  • phpMyAdmin 3.5.0

Versions in XAMPP as of today:

  • Apache 2.2.21
  • MySQL 5.5.16
  • PHP 5.3.8
  • phpMyAdmin 3.4.5

Apache and IIS side by side (both listening to port 80) on windows2003

It's impossible for both servers to listen on the same port at the same IP address: since a single socket can only be opened by a single process, only the first server configured for a certain IP/port combination will successfully bind, and the second one will fail.

You will thus need a workaround to achieve what you want. Easiest is probably to run Apache on your primary IP/port combination, and have it route requests for IIS (which should be configured for a different IP and/or port) to it using mod_rewrite.

Keep in mind that the alternative IP and port IIS runs on should be reachable to the clients connecting to your server: if you only have a single IP address available, you should take care to pick an IIS port that isn't generally blocked by firewalls (8080 might be a good option, or 443, even though you're running regular HTTP and not SSL)

P.S. Also, please note that you do need to modify the IIS default configuration using httpcfg before it will allow other servers to run on port 80 on any IP address on the same server: see Micky McQuade's answer for the procedure to do that...

How to remove class from all elements jquery

You could try this:

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

jQuery - selecting elements from inside a element

Why not just use:

$("#foo span")

or

$("#foo > span")

$('span', $('#foo')); works fine on my machine ;)

Best way to convert IList or IEnumerable to Array

Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray() and be done with it.

If you only have a non-generic IEnumerable, do something like this:

IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();

If you don't know the type within that method but the method's callers do know it, make the method generic and try this:

public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}

node.js Error: connect ECONNREFUSED; response from server

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

Parsing boolean values with argparse

I think the most canonical way will be:

parser.add_argument('--ensure', nargs='*', default=None)

ENSURE = config.ensure is None

How to make the script wait/sleep in a simple way in unity

here is more simple way without StartCoroutine:

float t = 0f;
float waittime = 1f;

and inside Update/FixedUpdate:

if (t < 0){
    t += Time.deltaTIme / waittime;
    yield return t;
}

What's a decent SFTP command-line client for windows?

This little application does the job for me. I could not find another CLI based client that would access my IIS based TLS/SSL secured ftp site: http://netwinsite.com/surgeftp/sslftp.htm

Data truncation: Data too long for column 'logo' at row 1

Use data type LONGBLOB instead of BLOB in your database table.

Truncate/round whole number in JavaScript?

I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:

function truncateToInt(x)
{
    if(x > 0)
    {
         return Math.floor(x);
    }
    else
    {
         return Math.ceil(x);
    }
 }

Then:

y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3

Notice: This answer was written when Math.trunc(x) was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x).

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

Translate all characters into their hex-entity equivalents. In this case, Null would be converted into &#4E;&#75;&#6C;&#6C;

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

Try something like this:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}

Callback functions in Java

This is very easy in Java 8 with lambdas.

public interface Callback {
    void callback();
}

public class Main {
    public static void main(String[] args) {
        methodThatExpectsACallback(() -> System.out.println("I am the callback."));
    }
    private static void methodThatExpectsACallback(Callback callback){
        System.out.println("I am the method.");
        callback.callback();
    }
}

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

git with IntelliJ IDEA: Could not read from remote repository

I solved this issue by re-adding remote repository: VCS -> Git -> Remotes.

Slide a layout up from bottom of screen

Here is a solution as an extension of [https://stackoverflow.com/a/46644736/10249774]

Bottom panel is pushing main content upwards

https://imgur.com/a/6nxewE0

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
    android:id="@+id/my_button"
    android:layout_marginTop="10dp"
    android:onClick="onSlideViewButtonClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main "
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main "
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main "
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main"
    android:textSize="70dp"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="main"
    android:textSize="70dp"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/footer_view"
    android:background="#a6e1aa"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="footer content"
        android:textSize="40dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="footer content"
        android:textSize="40dp" />
  </LinearLayout>
</RelativeLayout>

MainActivity:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
private Button myButton;
private View footerView;
private View mainView;
private boolean isUp;
private int anim_duration = 700;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    footerView = findViewById(R.id.footer_view);
    mainView = findViewById(R.id.main_view);
    myButton = findViewById(R.id.my_button);

    // initialize as invisible (could also do in xml)
    footerView.setVisibility(View.INVISIBLE);
    myButton.setText("Slide up");
    isUp = false;
}
public void slideUp(View mainView , View footer_view){
    footer_view.setVisibility(View.VISIBLE);
    TranslateAnimation animate_footer = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            footer_view.getHeight(),  // fromYDelta
            0);                // toYDelta
    animate_footer.setDuration(anim_duration);
    animate_footer.setFillAfter(true);
    footer_view.startAnimation(animate_footer);

    mainView.setVisibility(View.VISIBLE);
    TranslateAnimation animate_main = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            0,  // fromYDelta
            (0-footer_view.getHeight()));                // toYDelta
    animate_main.setDuration(anim_duration);
    animate_main.setFillAfter(true);
    mainView.startAnimation(animate_main);
}
public void slideDown(View mainView , View footer_view){
    TranslateAnimation animate_footer = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            0,                 // fromYDelta
            footer_view.getHeight()); // toYDelta
    animate_footer.setDuration(anim_duration);
    animate_footer.setFillAfter(true);
    footer_view.startAnimation(animate_footer);


    TranslateAnimation animate_main = new TranslateAnimation(
            0,                 // fromXDelta
            0,                 // toXDelta
            (0-footer_view.getHeight()),  // fromYDelta
            0);                // toYDelta
    animate_main.setDuration(anim_duration);
    animate_main.setFillAfter(true);
    mainView.startAnimation(animate_main);
}

public void onSlideViewButtonClick(View view) {
    if (isUp) {
        slideDown(mainView , footerView);
        myButton.setText("Slide up");
    } else {
        slideUp(mainView , footerView);
        myButton.setText("Slide down");
    }
    isUp = !isUp;
}
}

How to select an element by classname using jqLite?

Essentially, and as-noted by @kevin-b:

// find('#id')
angular.element(document.querySelector('#id'))

//find('.classname'), assumes you already have the starting elem to search from
angular.element(elem.querySelector('.classname'))

Note: If you're looking to do this from your controllers you may want to have a look at the "Using Controllers Correctly" section in the developers guide and refactor your presentation logic into appropriate directives (such as <a2b ...>).

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

Is it possible to use the SELECT INTO clause with UNION [ALL]?

You don't need a derived table at all for this.

Just put the INTO after the first SELECT

SELECT top(100)* 
INTO tmpFerdeen
FROM Customers
UNION All
SELECT top(100)* 
FROM CustomerEurope
UNION All
SELECT top(100)* 
FROM CustomerAsia
UNION All
SELECT top(100)* 
FROM CustomerAmericas

Change navbar color in Twitter Bootstrap

In this navbar CSS, set to own color:

_x000D_
_x000D_
/* Navbar */_x000D_
.navbar-default {_x000D_
    background-color: #F8F8F8;_x000D_
    border-color: #E7E7E7;_x000D_
}_x000D_
/* Title */_x000D_
.navbar-default .navbar-brand {_x000D_
    color: #777;_x000D_
}_x000D_
.navbar-default .navbar-brand:hover,_x000D_
.navbar-default .navbar-brand:focus {_x000D_
    color: #5E5E5E;_x000D_
}_x000D_
/* Link */_x000D_
.navbar-default .navbar-nav > li > a {_x000D_
    color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover,_x000D_
.navbar-default .navbar-nav > li > a:focus {_x000D_
    color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .active > a, _x000D_
.navbar-default .navbar-nav > .active > a:hover, _x000D_
.navbar-default .navbar-nav > .active > a:focus {_x000D_
    color: #555;_x000D_
    background-color: #E7E7E7;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a, _x000D_
.navbar-default .navbar-nav > .open > a:hover, _x000D_
.navbar-default .navbar-nav > .open > a:focus {_x000D_
    color: #555;_x000D_
    background-color: #D5D5D5;_x000D_
}_x000D_
/* Caret */_x000D_
.navbar-default .navbar-nav > .dropdown > a .caret {_x000D_
    border-top-color: #777;_x000D_
    border-bottom-color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > .dropdown > a:hover .caret,_x000D_
.navbar-default .navbar-nav > .dropdown > a:focus .caret {_x000D_
    border-top-color: #333;_x000D_
    border-bottom-color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a .caret, _x000D_
.navbar-default .navbar-nav > .open > a:hover .caret, _x000D_
.navbar-default .navbar-nav > .open > a:focus .caret {_x000D_
    border-top-color: #555;_x000D_
    border-bottom-color: #555;_x000D_
}
_x000D_
_x000D_
_x000D_

Where to install Android SDK on Mac OS X?

I just have mine in MyUser/Documents/Development. I'm the only one that used my Mac, so I didn't need to worry about making it accessible system-wide.

How to do if-else in Thymeleaf?

I'd like to share my example related to security in addition to Daniel Fernández.

<div th:switch="${#authentication}? ${#authorization.expression('isAuthenticated()')} : ${false}">
    <span th:case="${false}">User is not logged in</span>
    <span th:case="${true}">Logged in user</span>
    <span th:case="*">Should never happen, but who knows...</span>
</div>

Here is complex expression with mixed 'authentication' and 'authorization' utility objects which produces 'true/false' result for thymeleaf template code.

The 'authentication' and 'authorization' utility objects came from thymeleaf extras springsecurity3 library. When 'authentication' object is not available OR authorization.expression('isAuthenticated()') evaluates to 'false', expression returns ${false}, otherwise ${true}.

How to implement a material design circular progress bar in android

The platform uses a vector drawable, so you can't reuse it as in in older versions.
However, the support lib v4 contains a backport of this drawable : http://androidxref.com/5.1.0_r1/xref/frameworks/support/v4/java/android/support/v4/widget/MaterialProgressDrawable.java It has a @hide annotation (it is here for the SwipeRefreshLayout), but nothing prevents you from copying this class in your codebase.

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
    if(s.equals(value)){
        //do something
    }
}

or

for (int i = 0; i < arrayList.size(); i++) {
    if(arrayList.get(i).equals(value)){
        //do something
    }
}

But be carefull ArrayList can hold null values. So comparation should be

value.equals(arrayList.get(i))

when you are sure that value is not null or you should check if given element is null.

How to load GIF image in Swift?

Load GIF image Swift :

## Reference.

#1 : Copy the swift file from This Link :

#2 : Load GIF image Using Name

    let jeremyGif = UIImage.gifImageWithName("funny")
    let imageView = UIImageView(image: jeremyGif)
    imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView)

#3 : Load GIF image Using Data

    let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
    let advTimeGif = UIImage.gifImageWithData(imageData!)
    let imageView2 = UIImageView(image: advTimeGif)
    imageView2.frame = CGRect(x: 20.0, y: 220.0, width: 
    self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView2)

#4 : Load GIF image Using URL

    let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
    let imageURL = UIImage.gifImageWithURL(gifURL)
    let imageView3 = UIImageView(image: imageURL)
    imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView3)

Download Demo Code

OUTPUT :

iPhone 8 / iOS 11 / xCode 9

enter image description here

Remove all the elements that occur in one list from another

Use the Python set type. That would be the most Pythonic. :)

Also, since it's native, it should be the most optimized method too.

See:

http://docs.python.org/library/stdtypes.html#set

http://docs.python.org/library/sets.htm (for older python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

Center a column using Twitter Bootstrap 3

Another approach of offsetting is to have two empty rows, for example:

<div class="col-md-4"></div>
<div class="col-md-4">Centered Content</div>
<div class="col-md-4"></div>

submit a form in a new tab

Try using jQuery

<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>

Here is a full answer - http://ftutorials.com/open-html-form-in-new-tab/

PermGen elimination in JDK 8

The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace.The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error. The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace. Read More>>

Add Insecure Registry to Docker

Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

How can prepared statements protect from SQL injection attacks?

Root Cause #1 - The Delimiter Problem

Sql injection is possible because we use quotation marks to delimit strings and also to be parts of strings, making it impossible to interpret them sometimes. If we had delimiters that could not be used in string data, sql injection never would have happened. Solving the delimiter problem eliminates the sql injection problem. Structure queries do that.

Root Cause #2 - Human Nature, People are Crafty and Some Crafty People Are Malicious And All People Make Mistakes

The other root cause of sql injection is human nature. People, including programmers, make mistakes. When you make a mistake on a structured query, it does not make your system vulnerable to sql injection. If you are not using structured queries, mistakes can generate sql injection vulnerability.

How Structured Queries Resolve the Root Causes of SQL Injection

Structured Queries Solve The Delimiter Problem, by by putting sql commands in one statement and putting the data in a separate programming statement. Programming statements create the separation needed.

Structured queries help prevent human error from creating critical security holes. With regard to humans making mistakes, sql injection cannot happen when structure queries are used. There are ways of preventing sql injection that don't involve structured queries, but normal human error in that approaches usually leads to at least some exposure to sql injection. Structured Queries are fail safe from sql injection. You can make all the mistakes in the world, almost, with structured queries, same as any other programming, but none that you can make can be turned into a ssstem taken over by sql injection. That is why people like to say this is the right way to prevent sql injection.

So, there you have it, the causes of sql injection and the nature structured queries that makes them impossible when they are used.

Make $JAVA_HOME easily changable in Ubuntu

Take a look at bash(1), you need a login shell to pickup the ~/.profile, i.e. the -l option.

Python glob multiple filetypes

glob returns a list: why not just run it multiple times and concatenate the results?

from glob import glob
project_files = glob('*.txt') + glob('*.mdown') + glob('*.markdown')

How do I run a batch script from within a batch script?

huh, I don't know why, but call didn't do the trick
call script.bat didn't return to the original console.
cmd /k script.bat did return to the original console.

Why does javascript map function return undefined?

You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.

The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.

What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.

var arr = ['a','b',1];
var results = arr.filter(function(item){
    return typeof item ==='string';  
});

How to override !important?

Okay here is a quick lesson about CSS Importance. I hope that the below helps!

First of all the every part of the styles name as a weighting, so the more elements you have that relate to that style the more important it is. For example

#P1 .Page {height:100px;}

is more important than:

.Page {height:100px;}

So when using important, ideally this should only ever be used, when really really needed. So to overide the decleration, make the style more specific, but also with an override. See below:

td {width:100px !important;}
table tr td .override {width:150px !important;}

I hope this helps!!!

iOS Detection of Screenshot?

Heres how to do in Swift with closures:

func detectScreenShot(action: () -> ()) {
    let mainQueue = NSOperationQueue.mainQueue()
    NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationUserDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in
        // executes after screenshot
        action()
    }
}

detectScreenShot { () -> () in
    print("User took a screen shot")
}

Swift 4.2

func detectScreenShot(action: @escaping () -> ()) {
    let mainQueue = OperationQueue.main
    NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in
        // executes after screenshot
        action()
    }
}

This is included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

Disclaimer: Its my repo

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

Implementation difference between Aggregation and Composition in Java

In simple terms :

Both Composition and Aggregation are Associations. Composition -> Strong Has-A relationship Aggregation -> Weak Has-A relationship.

Query to list all users of a certain group

And the more complex query if you need to search in a several groups:

(&(objectCategory=user)(|(memberOf=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))

The same example with recursion:

(&(objectCategory=user)(|(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

Hide particular div onload and then show div after click

At first if you want to hide div element with id = "abc" on load and then toggle between hide and show using a button with id = "btn" then,

$(document).ready(function() {
 $("#abc").hide(); 
  $("#btn").click(function() {
     $("#abc").toggle();
  });
});

nodejs module.js:340 error: cannot find module

I faced the same problem. I just copied the testNode.js file(that contain the test code) and pasted into the root of nodejs directory manually. I tried this command C:\Program Files (x86)\nodejs>node testnode.js Bingo! I received this message.

enter image description here

Then I typed this url in a browser and received the message "Hello World". Hope this help somebody.

How to prevent a dialog from closing when a button is clicked

To prevent Dialog box from closing when clicked and it should only close when the internet is available

I am trying to do the same thing, as I don't want the dialog box to be closed until and unless the internet is connected.

Here is my code:

AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); builder.setTitle("Internet Not Connected");
    if(ifConnected()){

        Toast.makeText(this, "Connected or not", Toast.LENGTH_LONG).show();
    }
    else{
        builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
               if(!ifConnected())
               {
                   builder.show();
               }
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.show();

    }

And here is my Connectivity manager code:

 private boolean ifConnected()
{
    ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
   return networkInfo!=null && networkInfo.isConnected();
}

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Remove all occurrences of char from string

Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood

To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):

  • Use String.replace(charsToDelete, ""); which uses regex under the hood
  • Use Lambda
  • Use simple Java implementation

In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)

Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes regex).

By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.

The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.

The exact results vary with each run but the order of performance never changes:

Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms

The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.

The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.

package com.sample;

import java.util.function.BiFunction;
import java.util.stream.IntStream;

public class Main {

    static public String deleteCharsSimple(String fromString, String charsToDelete)
    {
        StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
        for(int i = 0; i < fromString.length(); i++)
            if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
                buf.append(fromString.charAt(i));   // char not in chars to delete so add it
        return buf.toString();
    }

    static public String deleteCharsLambda(String fromString1, String charsToDelete)
    {
        BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
            StringBuilder buf = new StringBuilder(fromString);
            IntStream.range(0, buf.length()).forEach(i -> {
                while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
                    buf.deleteCharAt(i);
            });
            return (buf.toString());
        };

        return deleteChars.apply(fromString1, charsToDelete);
    }

    static public String deleteCharsReplace(String fromString, String charsToDelete)
    {
        return fromString.replace(charsToDelete, "");
    }


    public static void main(String[] args)
    {
        String str = "XXXTextX XXto modifyX";
        String charsToDelete = "X";  // Should only be one char as per OP's requirement

        long start, end;

        System.out.println("Start simple");
        start = System.currentTimeMillis();

        for (int i = 0; i < 1000000; i++)
            deleteCharsSimple(str, charsToDelete);

        end = System.currentTimeMillis();
        System.out.println("Time: " + (end - start));

        System.out.println("Start lambda");
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++)
            deleteCharsLambda(str, charsToDelete);

        end = System.currentTimeMillis();
        System.out.println("Time: " + (end - start));

        System.out.println("Start replace");
        start = System.currentTimeMillis();

        for (int i = 0; i < 1000000; i++)
            deleteCharsReplace(str, charsToDelete);

        end = System.currentTimeMillis();
        System.out.println("Time: " + (end - start));
    }
}

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

Convert string to JSON array

It's a very simple way to convert:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;


class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Integer getCredits() {
    return credits;
}

public void setCredits(Integer credits) {
    this.credits = credits;
}

public String getTwitter_username() {
    return twitter_username;
}

public void setTwitter_username(String twitter_username) {
    this.twitter_username = twitter_username;
}

@Override
public String toString() {
    return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}

}

/*
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
    Gson gson = new Gson();
    try {
        BufferedReader br = new BufferedReader(new FileReader(
                "C:\\Temp\\jsonFileArr.json"));
        JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonElement str = jsonArray.get(i);
            Usuario obj = gson.fromJson(str, Usuario.class);
            System.out.println(obj);
            System.out.println(str);
            System.out.println("-------");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Is there a concurrent List in Java's JDK?

If you never plan to delete elements from the list (since this requires changing the index of all elements after the deleted element), then you can use ConcurrentSkipListMap<Integer, T> in place of ArrayList<T>, e.g.

NavigableMap<Integer, T> map = new ConcurrentSkipListMap<>();

This will allow you to add items to the end of the "list" as follows, as long as there is only one writer thread (otherwise there is a race condition between map.size() and map.put()):

// Add item to end of the "list":
map.put(map.size(), item);

You can also obviously modify the value of any item in the "list" (i.e. the map) by simply calling map.put(index, item).

The average cost for putting items into the map or retrieving them by index is O(log(n)), and ConcurrentSkipListMap is lock-free, which makes it significantly better than say Vector (the old synchronized version of ArrayList).

You can iterate back and forth through the "list" by using the methods of the NavigableMap interface.

You could wrap all the above into a class that implements the List interface, as long as you understand the race condition caveats (or you could synchronize just the writer methods) -- and you would need to throw an unsupported operation exception for the remove methods. There's quite a bit of boilerplate needed to implement all the required methods, but here's a quick attempt at an implementation.

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConcurrentAddOnlyList<V> implements List<V> {
    private NavigableMap<Integer, V> map = new ConcurrentSkipListMap<>();

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.values().contains(o);
    }

    @Override
    public Iterator<V> iterator() {
        return map.values().iterator();
    }

    @Override
    public Object[] toArray() {
        return map.values().toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return map.values().toArray(a);
    }

    @Override
    public V get(int index) {
        return map.get(index);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return map.values().containsAll(c);
    }

    @Override
    public int indexOf(Object o) {
        for (Entry<Integer, V> ent : map.entrySet()) {
            if (Objects.equals(ent.getValue(), o)) {
                return ent.getKey();
            }
        }
        return -1;
    }

    @Override
    public int lastIndexOf(Object o) {
        for (Entry<Integer, V> ent : map.descendingMap().entrySet()) {
            if (Objects.equals(ent.getValue(), o)) {
                return ent.getKey();
            }
        }
        return -1;
    }

    @Override
    public ListIterator<V> listIterator(int index) {
        return new ListIterator<V>() {
            private int currIdx = 0;

            @Override
            public boolean hasNext() {
                return currIdx < map.size();
            }

            @Override
            public V next() {
                if (currIdx >= map.size()) {
                    throw new IllegalArgumentException(
                            "next() called at end of list");
                }
                return map.get(currIdx++);
            }

            @Override
            public boolean hasPrevious() {
                return currIdx > 0;
            }

            @Override
            public V previous() {
                if (currIdx <= 0) {
                    throw new IllegalArgumentException(
                            "previous() called at beginning of list");
                }
                return map.get(--currIdx);
            }

            @Override
            public int nextIndex() {
                return currIdx + 1;
            }

            @Override
            public int previousIndex() {
                return currIdx - 1;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

            @Override
            public void set(V e) {
                // Might change size of map if currIdx == map.size(),
                // so need to synchronize 
                synchronized (map) {
                    map.put(currIdx, e);
                }
            }

            @Override
            public void add(V e) {
                synchronized (map) {
                    // Insertion is not supported except at end of list
                    if (currIdx < map.size()) {
                        throw new UnsupportedOperationException();
                    }
                    map.put(currIdx++, e);
                }
            }
        };
    }

    @Override
    public ListIterator<V> listIterator() {
        return listIterator(0);
    }

    @Override
    public List<V> subList(int fromIndex, int toIndex) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean add(V e) {
        synchronized (map) {
            map.put(map.size(), e);
            return true;
        }
    }

    @Override
    public boolean addAll(Collection<? extends V> c) {
        synchronized (map) {
            for (V val : c) {
                add(val);
            }
            return true;
        }
    }

    @Override
    public V set(int index, V element) {
        synchronized (map) {
            if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            return map.put(index, element);
        }
    }

    @Override
    public void clear() {
        synchronized (map) {
            map.clear();
        }
    }

    @Override
    public synchronized void add(int index, V element) {
        synchronized (map) {
            if (index < map.size()) {
                // Insertion is not supported except at end of list
                throw new UnsupportedOperationException();
            } else if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            // index == map.size()
            add(element);
        }
    }

    @Override
    public synchronized boolean addAll(
            int index, Collection<? extends V> c) {
        synchronized (map) {
            if (index < map.size()) {
                // Insertion is not supported except at end of list
                throw new UnsupportedOperationException();
            } else if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            // index == map.size()
            for (V val : c) {
                add(val);
            }
            return true;
        }
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V remove(int index) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }
}

Don't forget that even with the writer thread synchronization as shown above, you need to be careful not to run into race conditions that might cause you to drop items, if for example you try to iterate through a list in a reader thread while a writer thread is adding to the end of the list.

You can even use ConcurrentSkipListMap as a double-ended list, as long as you don't need the key of each item to represent the actual position within the list (i.e. adding to the beginning of the list will assign items negative keys). (The same race condition caveat applies here, i.e. there should be only one writer thread.)

// Add item after last item in the "list":
map.put(map.isEmpty() ? 0 : map.lastKey() + 1, item);

// Add item before first item in the "list":
map.put(map.isEmpty() ? 0 : map.firstKey() - 1, item);

pip install from git repo branch

For windows & pycharm setup:

If you are using pycharm and If you want to use pip3 install git+https://github.com/...

  • firstly, you should download git from https://git-scm.com/downloads
  • then restart pycharm
  • and you can use pycharm terminal to install what you want

enter image description here

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

How to change target build on Android project?

Another way on the command line if you are using ant is to use the android.bat script (Windows) or android script (Mac). It's in $SDK_DIR/tools.

If you say,

android.bat update project --path .  --target "android-8"

it will regenerate your build.xml, AndroidManifest.xml, etc.

How to get current instance name from T-SQL

another method to find Instance name- Right clck on Database name and select Properties, in this part you can see view connection properties in left down corner, click that then you can see the Instance name.

join on multiple columns

The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...

select 
      tA.Col1,
      tA.Col2,
      tB.Val
   from
      TableA tA
         join TableB tB
            on  ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
            AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )

How to assign the output of a Bash command to a variable?

You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.

All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.

It looks something like this:

NUM_PROCS=$(ps -e | sed 1d | wc -l)

I hope that helps add some handy information to this discussion.

Body of Http.DELETE request in Angular2

The http.delete(url, options) does accept a body. You just need to put it within the options object.

http.delete('/api/something', new RequestOptions({
   headers: headers,
   body: anyObject
}))

Reference options interface: https://angular.io/api/http/RequestOptions

UPDATE:

The above snippet only works for Angular 2.x, 4.x and 5.x.

For versions 6.x onwards, Angular offers 15 different overloads. Check all overloads here: https://angular.io/api/common/http/HttpClient#delete

Usage sample:

const options = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
  body: {
    id: 1,
    name: 'test',
  },
};

this.httpClient
  .delete('http://localhost:8080/something', options)
  .subscribe((s) => {
    console.log(s);
  });

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Python float to int conversion

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:

>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994

If you use int, which truncates the numbers, you get:

250
401

Have a look at the Decimal type.

psql - save results of command to a file

If you got the following error

ufgtoolspg=> COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';');
ERROR:  must be superuser to COPY to or from a file
HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.

you can run it in this way:

psql somepsqllink_or_credentials -c "COPY (SELECT foo, bar FROM baz) TO STDOUT (format csv, delimiter ';')"  > baz.csv

How to remove an item from an array in Vue.js

<v-btn color="info" @click="eliminarTarea(item.id)">Eliminar</v-btn>

And for your JS:

this.listaTareas = this.listaTareas.filter(i=>i.id != id)

What does href expression <a href="javascript:;"></a> do?

<a href="javascript:alert('Hello');"></a>

is just shorthand for:

<a href="" onclick="alert('Hello'); return false;"></a>

Are email addresses case sensitive?

I know this is an old question but I just want to comment here: To any extent email addresses ARE case sensitive, most users would be "very unwise" to actively use an email address that requires capitals. They would soon stop using the address because they'd be missing a lot of their mail. (Unless they have a specific reason to make things difficult, and they expect mail only from specific senders they know.)

That's because imperfect humans as well as imperfect software exist, (Surprise!) which will assume all email is lowercase, and for this reason these humans and software will send messages using a "lower cased version" of the address regardless of how it was provided to them. If the recipient is unable to receive such messages, it won't be long before they notice they're missing a lot, and switch to a lowercase-only email address, or get their server set up to be case-insensitive.

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

Control cannot fall through from one case label

Since it wasn't mentioned in the other answers, I'd like to add that if you want case SearchAuthors to be executed right after the first case, just like omitting the break in some other programming languages where that is allowed, you can simply use goto.

switch (searchType)
{
    case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    goto case "SearchAuthors";

    case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

Get local IP address in Node.js

Here's my utility method for getting the local IP address, assuming you are looking for an IPv4 address and the machine only has one real network interface. It could easily be refactored to return an array of IP addresses for multi-interface machines.

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }
  return '0.0.0.0';
}

Select folder dialog WPF

Microsoft.Win32.OpenFileDialog is the standard dialog that any application on Windows uses. Your user won't be surprised by its appearance when you use WPF in .NET 4.0

The dialog was altered in Vista. WPF in .NET 3.0 and 3.5 still used the legacy dialog but that was fixed in .NET 4.0. I can only guess that you started this thread because you are seeing that old dialog. Which probably means you're actually running a program that is targeting 3.5. Yes, the Winforms wrapper did get the upgrade and shows the Vista version. System.Windows.Forms.OpenFileDialog class, you'll need to add a reference to System.Windows.Forms.

What is the easiest way to parse an INI File in C++?

this question is a bit old, but I will post my answer. I have tested various INI classes (you can see them on my website) and I also use simpleIni because I want to work with INI files on both windows and winCE. Window's GetPrivateProfileString() works only with the registry on winCE.

It is very easy to read with simpleIni. Here is an example:

#include "SimpleIni\SimpleIni.h"    
CSimpleIniA ini;
ini.SetUnicode();
ini.LoadFile(FileName);
const char * pVal = ini.GetValue(section, entry, DefaultStr);

jQuery using append with effects

When you append to the div, hide it and show it with the argument "slow".

$("#img_container").append(first_div).hide().show('slow');

Toad for Oracle..How to execute multiple statements?

Highlight everything you want to run and run as a script. You can do that by clicking the icon on the menu bar that looks like a text file with a lightning bolt on it. That is the same as hitting F5. So if F5 doesn't work you probably have an error in your script.

Do you have semicolons after each statement?

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

UPDATE:
This answer turned out to be wrong. Please see the comments for the real explanation.


Most of you question has been answered, but as for the final part:

What would be the danger of both copies coming through?

None really. You'd waste bandwidth, might add some milliseconds downloading a second useless copy, but there's not actual harm if they both come through. You should, of course, avoid this using the techniques mentioned above.

Spark java.lang.OutOfMemoryError: Java heap space

I have a few suggestions:

  • If your nodes are configured to have 6g maximum for Spark (and are leaving a little for other processes), then use 6g rather than 4g, spark.executor.memory=6g. Make sure you're using as much memory as possible by checking the UI (it will say how much mem you're using)
  • Try using more partitions, you should have 2 - 4 per CPU. IME increasing the number of partitions is often the easiest way to make a program more stable (and often faster). For huge amounts of data you may need way more than 4 per CPU, I've had to use 8000 partitions in some cases!
  • Decrease the fraction of memory reserved for caching, using spark.storage.memoryFraction. If you don't use cache() or persist in your code, this might as well be 0. It's default is 0.6, which means you only get 0.4 * 4g memory for your heap. IME reducing the mem frac often makes OOMs go away. UPDATE: From spark 1.6 apparently we will no longer need to play with these values, spark will determine them automatically.
  • Similar to above but shuffle memory fraction. If your job doesn't need much shuffle memory then set it to a lower value (this might cause your shuffles to spill to disk which can have catastrophic impact on speed). Sometimes when it's a shuffle operation that's OOMing you need to do the opposite i.e. set it to something large, like 0.8, or make sure you allow your shuffles to spill to disk (it's the default since 1.0.0).
  • Watch out for memory leaks, these are often caused by accidentally closing over objects you don't need in your lambdas. The way to diagnose is to look out for the "task serialized as XXX bytes" in the logs, if XXX is larger than a few k or more than an MB, you may have a memory leak. See https://stackoverflow.com/a/25270600/1586965
  • Related to above; use broadcast variables if you really do need large objects.
  • If you are caching large RDDs and can sacrifice some access time consider serialising the RDD http://spark.apache.org/docs/latest/tuning.html#serialized-rdd-storage. Or even caching them on disk (which sometimes isn't that bad if using SSDs).
  • (Advanced) Related to above, avoid String and heavily nested structures (like Map and nested case classes). If possible try to only use primitive types and index all non-primitives especially if you expect a lot of duplicates. Choose WrappedArray over nested structures whenever possible. Or even roll out your own serialisation - YOU will have the most information regarding how to efficiently back your data into bytes, USE IT!
  • (bit hacky) Again when caching, consider using a Dataset to cache your structure as it will use more efficient serialisation. This should be regarded as a hack when compared to the previous bullet point. Building your domain knowledge into your algo/serialisation can minimise memory/cache-space by 100x or 1000x, whereas all a Dataset will likely give is 2x - 5x in memory and 10x compressed (parquet) on disk.

http://spark.apache.org/docs/1.2.1/configuration.html

EDIT: (So I can google myself easier) The following is also indicative of this problem:

java.lang.OutOfMemoryError : GC overhead limit exceeded

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

batch file to list folders within a folder to one level

Dir

Use the dir command. Type in dir /? for help and options.

dir /a:d /b

Redirect

Then use a redirect to save the list to a file.

> list.txt

Together

dir /a:d /b > list.txt

This will output just the names of the directories. if you want the full path of the directories use this below.


Full Path

for /f "delims=" %%D in ('dir /a:d /b') do echo %%~fD

Alternative

other method just using the for command. See for /? for help and options. This can output just the name %%~nxD or the full path %%~fD

for /d %%D in (*) do echo %%~fD

Notes

To use these commands directly on the command line, change the double percent signs to single percent signs. %% to %

To redirect the for methods, just add the redirect after the echo statements. Use the double arrow >> redirect here to append to the file, else only the last statement will be written to the file due to overwriting all the others.

... echo %%~fD>> list.txt

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

Browse files and subfolders in Python

I had a similar thing to work on, and this is how I did it.

import os

rootdir = os.getcwd()

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".html"):
            print (filepath)

Hope this helps.

Best way to parse RSS/Atom feeds with PHP

Another great free parser - http://bncscripts.com/free-php-rss-parser/ It's very light ( only 3kb ) and simple to use!

Disabling submit button until all fields have values

This works well since all the inputs have to meet the condition of not null.

$(function () {
    $('#submits').attr('disabled', true);
    $('#input_5').change(function () {
        if ($('#input_1').val() != '' && $('#input_2').val() != '' && $('#input_3').val() != '' && $('#input_4').val() != '' && $('#input_5').val() != '') {
            $('#submit').attr('disabled', false);
        } else {
            $('#submit').attr('disabled', true);
        }
     });
 });

How can I display an RTSP video stream in a web page?

Found a simple and working solution from VLC official documentation for web plugin

https://wiki.videolan.org/Documentation:WebPlugin/

Modified the code a little bit and got it working. Here is my code-

<embed type="application/x-vlc-plugin" pluginspage="http://www.videolan.org" autoplay="yes" loop="no" width="300" height="200" target="rtsp://10.20.50.15:554/0/888888:888888/main" />
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" codebase="http://download.videolan.org/pub/videolan/vlc/last/win32/axvlc.cab" style="display:none;"></object>

Note: The above snippet uses the rtsp url format that is supported by my IP camera. So you need to get the same for your camera. You can get this information by consulting your camera vendor support. Also keep in mind that I tested it on Chrome (using an activeX plugin for Chrome) and other browsers (including mobile phone browsers) might not be supported.

Find out which remote branch a local branch is tracking

Another simple way is to use

cat .git/config in a git repo

This will list details for local branches

How to find top three highest salary in emp table in oracle?

SELECT * FROM Employees
WHERE rownum <= 3
ORDER BY Salary ;

How to implement WiX installer upgrade?

I used this site to help me understand the basics about WiX Upgrade:

http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization

Afterwards I created a sample Installer, (installed a test file), then created the Upgrade installer (installed 2 sample test files). This will give you a basic understanding of how the mechanism works.

And as Mike said in the book from Apress, "The Definitive Guide to Windows Installer", it will help you out to understand, but it is not written using WiX.

Another site that was pretty helpful was this one:

http://www.wixwiki.com/index.php?title=Main_Page

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

Android Facebook style slide

For info, as the compatibility library starts with 1.6 and this facebook app is also running on devices with Android 1.5, it could not be done with Fragments.

The way you could do it, is : Create a "base" activity BaseMenuActivity where you put all the logic for the onItemClickListener for your menu list and defines the 2 animation ("open" and "close"). At the end/beginning of the animations, you show/hide the layout of the BaseMenuActivity (lets call it menu_layout). The layout for this activity is simple, its only a list with items + a transparent part at the right of your list. This part will be clickable and its width will be the same width as your "move button". With that, you'll be able to click on this layout to start the animation to let the content_layout slide to the left and take the whole screen. For each option (i.e. item of the menu list), you create a "ContentActivity" which extends the BaseMenuActivity. Then when you click on an item of the list, you start your ItemSelectedContentActivity with the menu visible (which you'll close as soon as your activity starts). The layouts for each ContentActivity are FrameLayout and includes the and . You just need to move the content_layout and make the menu_layout visible when you want.

That's a way to do it, and I hope I've been clear enough.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I'm a MacOS user.

I solved it by uninstalling Android Studio and reinstalling it again.

If you want to try this link helped me a lot.

Uninstall Android Studio MacOS (terminal)

How to remove items from a list while iterating?

The answers suggesting list comprehensions are ALMOST correct -- except that they build a completely new list and then give it the same name the old list as, they do NOT modify the old list in place. That's different from what you'd be doing by selective removal, as in @Lennart's suggestion -- it's faster, but if your list is accessed via multiple references the fact that you're just reseating one of the references and NOT altering the list object itself can lead to subtle, disastrous bugs.

Fortunately, it's extremely easy to get both the speed of list comprehensions AND the required semantics of in-place alteration -- just code:

somelist[:] = [tup for tup in somelist if determine(tup)]

Note the subtle difference with other answers: this one is NOT assigning to a barename - it's assigning to a list slice that just happens to be the entire list, thereby replacing the list contents within the same Python list object, rather than just reseating one reference (from previous list object to new list object) like the other answers.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

Align items in a stack panel?

for windows 10 use relativePanel instead of stack panel, and use

relativepanel.alignrightwithpanel="true"

for the contained elements.

Difference between Method and Function?

Both are same, there is no difference its just a different term for the same thing in C#.

Method:

In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class.

With respect to Object Oriented programming the term "Method" is used, not functions.

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I had the very same issue recently. This was my error:

System.InvalidOperationException : session not created: This version of ChromeDriver only supports Chrome version 76 (SessionNotCreated)

This fix worked for me:

  • make sure there are no running chromedriver.exe processes (if needed kill them all e.g. via task manager)
  • go to bin folder and delete chromedriver.exe file from there (in my case it was: [project_folder]\bin\Debug\netcoreapp2.1)

How do I connect to a specific Wi-Fi network in Android programmatically?

Credit to @raji-ramamoorthi & @kenota

The solution which worked for me is combination of above contributors in this thread.

To get ScanResult here is the process.

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false) {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent intent) {
                 wifi.getScanResults();
            }
        };

Notice to unregister it on onPause & onStop live this unregisterReceiver(broadcastReceiver);

public void connectWiFi(ScanResult scanResult) {
        try {

            Log.v("rht", "Item clicked, SSID " + scanResult.SSID + " Security : " + scanResult.capabilities);

            String networkSSID = scanResult.SSID;
            String networkPass = "12345678";

            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes
            conf.status = WifiConfiguration.Status.ENABLED;
            conf.priority = 40;

            if (scanResult.capabilities.toUpperCase().contains("WEP")) {
                Log.v("rht", "Configuring WEP");    
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

                if (networkPass.matches("^[0-9a-fA-F]+$")) {
                    conf.wepKeys[0] = networkPass;
                } else {
                    conf.wepKeys[0] = "\"".concat(networkPass).concat("\"");
                }

                conf.wepTxKeyIndex = 0;

            } else if (scanResult.capabilities.toUpperCase().contains("WPA")) {
                Log.v("rht", "Configuring WPA");

                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

                conf.preSharedKey = "\"" + networkPass + "\"";

            } else {
                Log.v("rht", "Configuring OPEN network");
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedAuthAlgorithms.clear();
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            }

            WifiManager wifiManager = (WifiManager) WiFiApplicationCore.getAppContext().getSystemService(Context.WIFI_SERVICE);
            int networkId = wifiManager.addNetwork(conf);

            Log.v("rht", "Add result " + networkId);

            List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
            for (WifiConfiguration i : list) {
                if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                    Log.v("rht", "WifiConfiguration SSID " + i.SSID);

                    boolean isDisconnected = wifiManager.disconnect();
                    Log.v("rht", "isDisconnected : " + isDisconnected);

                    boolean isEnabled = wifiManager.enableNetwork(i.networkId, true);
                    Log.v("rht", "isEnabled : " + isEnabled);

                    boolean isReconnected = wifiManager.reconnect();
                    Log.v("rht", "isReconnected : " + isReconnected);

                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

JavaScript - Use variable in string match

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.

Check if a given key already exists in a dictionary

in is the intended way to test for the existence of a key in a dict.

d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("this will execute")

if "nonexistent key" in d:
    print("this will not")

If you wanted a default, you can always use dict.get():

d = dict()

for i in range(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1

and if you wanted to always ensure a default value for any key you can either use dict.setdefault() repeatedly or defaultdict from the collections module, like so:

from collections import defaultdict

d = defaultdict(int)

for i in range(100):
    d[i % 10] += 1

but in general, the in keyword is the best way to do it.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Detect if a Form Control option button is selected in VBA

If you are using a Form Control, you can get the same property as ActiveX by using OLEFormat.Object property of the Shape Object. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.

Dim opt As OptionButton

With Sheets("Sheet1") ' Try to be always explicit
    Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
    Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With

But then again, you really don't need to know the value.
If you use Form Control, you associate a Macro or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.

For example you have 2 Form Control Option Buttons.

Sub CheckOptions()
    Select Case Application.Caller
    Case "Option Button 1"
    ' Action for option button 1
    Case "Option Button 2"
    ' Action for option button 2
    End Select
End Sub

In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller.
This way, no need to check whether the option button value is true or false.

Sorting a list with stream.sorted() in Java

This is a simple example :

List<String> citiesName = Arrays.asList( "Delhi","Mumbai","Chennai","Banglore","Kolkata");
System.out.println("Cities : "+citiesName);
List<String> sortedByName = citiesName.stream()
                .sorted((s1,s2)->s2.compareTo(s1))
                        .collect(Collectors.toList());
System.out.println("Sorted by Name : "+ sortedByName);

It may be possible that your IDE is not getting the jdk 1.8 or upper version to compile the code.

Set the Java version 1.8 for Your_Project > properties > Project Facets > Java version 1.8

How do I set vertical space between list items?

Old question but I think it lacked an answer. I would use an adjacent siblings selector. This way we only write "one" line of CSS and take into consideration the space at the end or beginning, which most of the answers lacks.

li + li {
  margin-top: 10px;
}

How to duplicate sys.stdout to a log file?

As per a request by @user5359531 in the comments under @John T's answer, here's a copy of the referenced post to the revised version of the linked discussion in that answer:

Issue of redirecting the stdout to both file and screen
Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 28 12:45:51 CEST 2007

    Previous message: Issue of redirecting the stdout to both file and screen
    Next message: Formal interfaces with Python
    Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]

En Mon, 28 May 2007 06:17:39 -0300, ???????,???????
<kelvin.you at gmail.com> escribió:

> I wanna print the log to both the screen and file, so I simulatered a
> 'tee'
>
> class Tee(file):
>
>     def __init__(self, name, mode):
>         file.__init__(self, name, mode)
>         self.stdout = sys.stdout
>         sys.stdout = self
>
>     def __del__(self):
>         sys.stdout = self.stdout
>         self.close()
>
>     def write(self, data):
>         file.write(self, data)
>         self.stdout.write(data)
>
> Tee('logfile', 'w')
> print >>sys.stdout, 'abcdefg'
>
> I found that it only output to the file, nothing to screen. Why?
> It seems the 'write' function was not called when I *print* something.

You create a Tee instance and it is immediately garbage collected. I'd
restore sys.stdout on Tee.close, not __del__ (you forgot to call the
inherited __del__ method, btw).
Mmm, doesn't work. I think there is an optimization somewhere: if it looks
like a real file object, it uses the original file write method, not yours.
The trick would be to use an object that does NOT inherit from file:

import sys
class TeeNoFile(object):
     def __init__(self, name, mode):
         self.file = open(name, mode)
         self.stdout = sys.stdout
         sys.stdout = self
     def close(self):
         if self.stdout is not None:
             sys.stdout = self.stdout
             self.stdout = None
         if self.file is not None:
             self.file.close()
             self.file = None
     def write(self, data):
         self.file.write(data)
         self.stdout.write(data)
     def flush(self):
         self.file.flush()
         self.stdout.flush()
     def __del__(self):
         self.close()

tee=TeeNoFile('logfile', 'w')
print 'abcdefg'
print 'another line'
tee.close()
print 'screen only'
del tee # should do nothing

--
Gabriel Genellina

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I had the error when I was trying to make a custom result for a stored procedure and assumed it had to be an entity.

The solution was that I just made a complex type in the Model browser and assigned that as a result to the "Edit function imports".

I will add it here since it looks like this question is where google takes you when you get this error.

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

How can I search (case-insensitive) in a column using LIKE wildcard?

Simply use :

"SELECT * FROM `trees` WHERE LOWER(trees.`title`) LIKE  '%elm%'";

Or Use

"SELECT * FROM `trees` WHERE LCASE(trees.`title`) LIKE  '%elm%'";

Both functions works same

How to move an element into another element?

You may also try:

$("#destination").html($("#source"))

But this will completely overwrite anything you have in #destination.

Java constructor/method with optional parameters?

Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:

public Foo(int param1, int param2)
{
    this.param1 = param1;
    this.param2 = param2;
}

public Foo(int param1)
{
    this(param1, 2);
}

SSL Error: CERT_UNTRUSTED while using npm command

Since i stumbled on the post via google:

Try using npm ci it will be much than an npm install.

From the manual:

In short, the main differences between using npm install and npm ci are:

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.

Where can I get Google developer key

Please use Google API console
Create a new project
For the created project goto API access
There you will find your Client ID and Secret. And the API key in the last is your developer key.

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

Checking letter case (Upper/Lower) within a string in Java

I have streamlined the answer of @Quirliom above into functions that can be used:

private static boolean hasLength(CharSequence data) {
    if (String.valueOf(data).length() >= 8) return true;
    else return false;
}

private static boolean hasSymbol(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
    return hasSpecial;
}

private static boolean hasUpperCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasUppercase = !password.equals(password.toLowerCase());
    return hasUppercase;
}

private static boolean hasLowerCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasLowercase = !password.equals(password.toUpperCase());
    return hasLowercase;
}

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

Facebook Open Graph not clearing cache

I'm sorry folks but the correct answer is:

There is no fool proof way to update the open graph og:image url with immediate result. It is cached until fb updates (reportedly every 24 hours)

Here are things that have been reported to work by others but I have had ZERO success with any of them.

  • Choosing "Fetch new scrape information"
  • Changing the actual image filename and/or deleting the original
  • Adding a query string to the image url by appending a PHP TIMESTAMP or ?anything
  • Adding the "...yoursite.com/?fbrefresh=anything" query string to the debugger fetch url
  • Choosing the graph API link at the bottom of the og dev page
  • Choosing to see exactly what the scraper sees - does not appear to request real time un-cached scrape data, it still shows the cached image url even if the file no longer exists

Inspecting your code is always a spot on way to confirm it is not an issue with browser cache or some caching service. If the meta information is up to date in your code and you've tried all of the above (unless another suggestion comes to fruition), the correct answer is you can do nothing but wait.

Decimal or numeric values in regular expression validation

Actually, none of the given answers are fully cover the request.
As the OP didn't provided a specific use case or types of numbers, I will try to cover all possible cases and permutations.

Regular Numbers

Whole Positive

This number is usually called unsigned integer, but you can also call it a positive non-fractional number, include zero. This includes numbers like 0, 1 and 99999.
The Regular Expression that covers this validation is:

/^(0|[1-9]\d*)$/

Test This Regex

Whole Positive and Negative

This number is usually called signed integer, but you can also call it a non-fractional number. This includes numbers like 0, 1, 99999, -99999, -1 and -0.
The Regular Expression that covers this validation is:

/^-?(0|[1-9]\d*)$/

Test This Regex

As you probably noticed, I have also included -0 as a valid number. But, some may argue with this usage, and tell that this is not a real number (you can read more about Signed Zero here). So, if you want to exclude this number from this regex, here's what you should use instead:

/^-?(0|[1-9]\d*)(?<!-0)$/

Test This Regex

All I have added is (?<!-0), which means not to include -0 before this assertion. This (?<!...) assertion called negative lookbehind, which means that any phrase replaces the ... should not appear before this assertion. Lookbehind has limitations, like the phrase cannot include quantifiers. That's why for some cases I'll be using Lookahead instead, which is the same, but in the opposite way.

Many regex flavors, including those used by Perl and Python, only allow fixed-length strings. You can use literal text, character escapes, Unicode escapes other than \X, and character classes. You cannot use quantifiers or backreferences. You can use alternation, but only if all alternatives have the same length. These flavors evaluate lookbehind by first stepping back through the subject string for as many characters as the lookbehind needs, and then attempting the regex inside the lookbehind from left to right.

You can read more bout Lookaround assertions here.

Fractional Numbers

Positive

This number is usually called unsigned float or unsigned double, but you can also call it a positive fractional number, include zero. This includes numbers like 0, 1, 0.0, 0.1, 1.0, 99999.000001, 5.10.
The Regular Expression that covers this validation is:

/^(0|[1-9]\d*)(\.\d+)?$/

Test This Regex

Some may say, that numbers like .1, .0 and .00651 (same as 0.1, 0.0 and 0.00651 respectively) are also valid fractional numbers, and I cannot disagree with them. So here is a regex that is additionally supports this format:

/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/

Test This Regex

Negative and Positive

This number is usually called signed float or signed double, but you can also call it a fractional number. This includes numbers like 0, 1, 0.0, 0.1, 1.0, 99999.000001, 5.10, -0, -1, -0.0, -0.1, -99999.000001, 5.10.
The Regular Expression that covers this validation is:

/^-?(0|[1-9]\d*)(\.\d+)?$/

Test This Regex

For non -0 believers:

/^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/

Test This Regex

For those who want to support also the invisible zero representations, like .1, -.1, use the following regex:

/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/

Test This Regex

The combination of non -0 believers and invisible zero believers, use this regex:

/^(?!-0?(\.0+)?$)-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/

Test This Regex

Numbers with a Scientific Notation (AKA Exponential Notation)

Some may want to support in their validations, numbers with a scientific character e, which is by the way, an absolutely valid number, it is created for shortly represent a very long numbers. You can read more about Scientific Notation here. These numbers are usually looks like 1e3 (which is 1000), 1e-3 (which is 0.001) and are fully supported by many major programming languages (e.g. JavaScript). You can test it by checking if the expression '1e3'==1000 returns true.
I will divide the support for all the above sections, including numbers with scientific notation.

Regular Numbers

Whole positive number regex validation, supports numbers like 6e4, 16e-10, 0e0 but also regular numbers like 0, 11:

/^(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Whole positive and negative number regex validation, supports numbers like -6e4, -16e-10, -0e0 but also regular numbers like -0, -11 and all the whole positive numbers above:

/^-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Whole positive and negative number regex validation for non -0 believers, same as the above, except now it forbids numbers like -0, -0e0, -0e5 and -0e-6:

/^(?!-0)-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Fractional Numbers

Positive number regex validation, supports also the whole numbers above, plus numbers like 0.1e3, 56.0e-3, 0.0e10 and 1.010e0:

/^(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i

Test This Regex

Positive number with invisible zero support regex validation, supports also the above positive numbers, in addition numbers like .1e3, .0e0, .0e-5 and .1e-7:

/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number regex validation, supports the positive numbers above, but also numbers like -0e3, -0.1e0, -56.0e-3 and -0.0e10:

/^-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number regex validation fro non -0 believers, same as the above, except now it forbids numbers like -0, -0.00000, -0.0e0, -0.00000e5 and -0e-6:

/^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number with invisible zero support regex validation, supports also the above positive and negative numbers, in addition numbers like -.1e3, -.0e0, -.0e-5 and -.1e-7:

/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Negative and positive number with the combination of non -0 believers and invisible zero believers, same as the above, but forbids numbers like -.0e0, -.0000e15 and -.0e-19:

/^(?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i

Test This Regex

Numbers with Hexadecimal Representation

In many programming languages, string representation of hexadecimal number like 0x4F7A may be easily cast to decimal number 20346.
Thus, one may want to support it in his validation script.
The following Regular Expression supports only hexadecimal numbers representations:

/^0x[0-9a-f]+$/i

Test This Regex

All Permutations

These final Regular Expressions, support the invisible zero numbers.

Signed Zero Believers

/^(-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i

Test This Regex

Non Signed Zero Believers

/^((?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i

Test This Regex

Hope I covered all number permutations that are supported in many programming languages.
Good luck!


Oh, forgot to mention, that those who want to validate a number includes a thousand separator, you should clean all the commas (,) first, as there may be any type of separator out there, you can't actually cover them all.
But you can remove them first, before the number validation:

//JavaScript
function clearSeparators(number)
{
    return number.replace(/,/g,'');
}

Similar post on my blog.

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

JavaScript ternary operator example with functions

If you're going to nest ternary operators, I believe you'd want to do something like this:

   var audience = (countrycode == 'eu') ? 'audienceEU' :
                  (countrycode == 'jp') ? 'audienceJP' :
                  (countrycode == 'cn') ? 'audienceCN' :
                  'audienceUS';

It's a lot more efficient to write/read than:

var audience = 'audienceUS';
if countrycode == 'eu' {
   audience = 'audienceEU';
} else if countrycode == 'jp' {
   audience = 'audienceJP';
} else if countrycode == 'cn' {
   audience = 'audienceCN';
}

As with all good programming, whitespace makes everything nice for people who have to read your code after you're done with the project.

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

Use aliases:

SELECT COUNT(*) AS total FROM ..

and then

rs3.getInt("total")

JQuery Calculate Day Difference in 2 date textboxes

1) Html

<input type="text" id="firstDate" name="firstDate"/>
<input type="text" id="secondDate" name="secondDate"/>

2) Jquery

$("#firstDate").datepicker({

}); 
$("#secondDate").datepicker({
    onSelect: function () {
        myfunc();
    }
}); 

function myfunc(){
    var start= $("#firstDate").datepicker("getDate");
    var end= $("#secondDate").datepicker("getDate");
    days = (end- start) / (1000 * 60 * 60 * 24);
    alert(Math.round(days));
}

Jsfiddle working example here

How to use an environment variable inside a quoted string in Bash

If unsure, you might use the 'cols' request on the terminal, and forget COLUMNS:

COLS=$(tput cols)

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

You have to use now the new XLSX-Driver from Access-Redist (32/64-Bit). The current XLS-Driver are corrupted since last cumulative update.

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

display Java.util.Date in a specific format

If you want to simply output a date, just use the following:

System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());

As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:

String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());

You can also customize your output by following the Java API on Date/Time conversions.

Missing Maven dependencies in Eclipse project

So many answers. You see, there could be many reasons, why this is not working, as expected. In my case, I also did not realize the - Tag around my dependencies. facepalm

Example:

...
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

this only DEFINES the dependency for this and all subprojects with desired version! This is, what it e.g. should look like in the master-POM. To really use the lib in THIS current project, you have too add the depency as following:

...
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </dependency>
</dependencies>

NOW it will provide the lib in THIS current project.

How to get a variable value if variable name is stored as string?

You can use ${!a}:

var1="this is the real value"
a="var1"
echo "${!a}" # outputs 'this is the real value'

This is an example of indirect parameter expansion:

The basic form of parameter expansion is ${parameter}. The value of parameter is substituted.

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

I add the ",-std=c++0x" after "-c -fmessage-length=0",under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. Dont't forget to add the comma "," as the seperator.

SQL Server database backup restore on lower version

Go to Task->Generate Scripts...

In Advanced in "Types of data for script" select "Schema and data" and try to run this script in your lower version.

Could not load file or assembly '***.dll' or one of its dependencies

I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.

Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.

How do I put two increment statements in a C++ 'for' loop?

Try this

for(int i = 0; i != 5; ++i, ++j)
    do_something(i,j);

Simplest way to have a configuration file in a Windows Forms C# application

You should create an App.config file (very similar to web.config).

You should right click on your project, add new item, and choose new "Application Configuration File".

Ensure that you add using System.Configuration in your project.

Then you can add values to it:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }

Just a note: According to Microsoft, you should use ConfigurationManager instead of ConfigurationSettings (see the remarks section):

"The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. "

How to start new activity on button click

You can try this code:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

I had the same problem in a Xamarin Forms project. iOS project was unavailable and I couldn't reload the project. I was looking for a solution that doesn't need uninstalling anything.

The answer I got from this blog: https://dev.to/codeprototype/xamarin-form-application-failed-to-load-android-project-root-element-missing--27o0

So without uninstalling anything, you could delete the .csproj.user file (or rename it) so Visual Studio will create the file again. Worked for me twice.

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You can just put this all on one line:

LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/path/to/library" ./sync_test

Should make things a little easier, even if it doesn't change anything fundamental

Python code to remove HTML tags from a string

Using a regex

Using a regex, you can clean everything inside <> :

import re

def cleanhtml(raw_html):
  cleanr = re.compile('<.*?>')
  cleantext = re.sub(cleanr, '', raw_html)
  return cleantext

Some HTML texts can also contain entities that are not enclosed in brackets, such as '&nsbm'. If that is the case, then you might want to write the regex as

cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')

This link contains more details on this.

Using BeautifulSoup

You could also use BeautifulSoup additional package to find out all the raw text.

You will need to explicitly set a parser when calling BeautifulSoup I recommend "lxml" as mentioned in alternative answers (much more robust than the default one (html.parser) (i.e. available without additional install).

from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text

But it doesn't prevent you from using external libraries, so I recommend the first solution.

EDIT: To use lxml you need to pip install lxml.

How to recover closed output window in netbeans?

in Netbeans 7.4 try Window -> Output OR Ctrl + 4

Do I need <class> elements in persistence.xml?

The persistence.xml has a jar-file that you can use. From the Java EE 5 tutorial:

<persistence>
    <persistence-unit name="OrderManagement">
        <description>This unit manages orders and customers.
            It does not rely on any vendor-specific features and can
            therefore be deployed to any persistence provider.
        </description>
        <jta-data-source>jdbc/MyOrderDB</jta-data-source>
        <jar-file>MyOrderApp.jar</jar-file>
        <class>com.widgets.Order</class>
        <class>com.widgets.Customer</class>
    </persistence-unit>
</persistence>

This file defines a persistence unit named OrderManagement, which uses a JTA-aware data source jdbc/MyOrderDB. The jar-file and class elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses. The jar-file element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, while the class element explicitly names managed persistence classes.

In the case of Hibernate, have a look at the Chapter2. Setup and configuration too for more details.

EDIT: Actually, If you don't mind not being spec compliant, Hibernate supports auto-detection even in Java SE. To do so, add the hibernate.archive.autodetection property:

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
  <!-- This is required to be spec compliant, Hibernate however supports
       auto-detection even in JSE.
  <class>pl.michalmech.eventractor.domain.User</class>
  <class>pl.michalmech.eventractor.domain.Address</class>
  <class>pl.michalmech.eventractor.domain.City</class>
  <class>pl.michalmech.eventractor.domain.Country</class>
   -->

  <properties>
    <!-- Scan for annotated classes and Hibernate mapping XML files -->
    <property name="hibernate.archive.autodetection" value="class, hbm"/>

    <property name="hibernate.hbm2ddl.auto" value="validate" />
    <property name="hibernate.show_sql" value="true" />
  </properties>
</persistence-unit>

How to view the assembly behind the code using Visual C++?

The earlier version of this answer (a "hack" for rextester.com) is mostly redundant now that http://gcc.godbolt.org/ provides CL 19 RC for ARM, x86, and x86-64 (targeting the Windows calling convention, unlike gcc, clang, and icc on that site).

The Godbolt compiler explorer is designed for nicely formatting compiler asm output, removing the "noise" of directives, so I'd highly recommend using it to look at asm for simple functions that take args and return a value (so they won't be optimized away).

For a while, CL was available on http://gcc.beta.godbolt.org/ but not the main site, but now it's on both.


To get MSVC asm output from the http://rextester.com/l/cpp_online_compiler_visual online compiler: Add /FAs to the command line options. Have your program find its own path and work out the path to the .asm and dump it. Or run a disassembler on the .exe.

e.g. http://rextester.com/OKI40941

#include <string>
#include <boost/filesystem.hpp>
#include <Windows.h>

using namespace std;

static string my_exe(void){
    char buf[MAX_PATH];
    DWORD tmp = GetModuleFileNameA( NULL, // self
                                  buf, MAX_PATH);
    return buf;
}

int main() {
    string dircmd = "dir ";
    boost::filesystem::path p( my_exe() );
    //boost::filesystem::path dir = p.parent_path();

    // transform c:\foo\bar\1234\a.exe 
    // into      c:\foo\bar\1234\1234.asm
    p.remove_filename();
    system ( (dircmd + p.string()).c_str() );

    auto subdir = p.end();      // pointing at one-past the end
    subdir--;                   // pointing at the last directory name
    p /= *subdir;               // append the last dir name as a filename
    p.replace_extension(".asm");
    system ( (string("type ") + p.string()).c_str() );
//    std::cout << "Hello, world!\n";
}

... code of functions you want to see the asm for goes here ...

type is the DOS version of cat. I didn't want to include more code that would make it harder to find the functions I wanted to see the asm for. (Although using std::string and boost run counter to those goals! Some C-style string manipulation that makes more assumptions about the string it's processing (and ignores max-length safety / allocation by using a big buffer) on the result of GetModuleFileNameA would be much less total machine code.)

IDK why, but cout << p.string() << endl only shows the basename (i.e. the filename, without the directories), even though printing its length shows it's not just the bare name. (Chromium48 on Ubuntu 15.10). There's probably some backslash-escape processing at some point in cout, or between the program's stdout and the web browser.

Making an API call in Python with an API that requires a bearer token

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

Conditionally ignoring tests in JUnit 4

In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {
    public CTRunner(Class<?> klass) throws initializationError {
        super(klass);
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        if(shouldIgnore()) {
            return true;
        }
        return super.isIgnored(child);
    }

    private boolean shouldIgnore(class) {
        /* some custom criteria */
    }
}

Odd behavior when Java converts int to byte?

here is a very mechanical method without the distracting theories:

  1. Convert the number into binary representation (use a calculator ok?)
  2. Only copy the rightmost 8 bits (LSB) and discard the rest.
  3. From the result of step#2, if the leftmost bit is 0, then use a calculator to convert the number to decimal. This is your answer.
  4. Else (if the leftmost bit is 1) your answer is negative. Leave all rightmost zeros and the first non-zero bit unchanged. And reversed the rest, that is, replace 1's by 0's and 0's by 1's. Then use a calculator to convert to decimal and append a negative sign to indicate the value is negative.

This more practical method is in accordance to the much theoretical answers above. So, those still reading those Java books saying to use modulo, this is definitely wrong since the 4 steps I outlined above is definitely not a modulo operation.

Good PHP ORM Library?

A really good simple ORM is MyActiveRecord. MyActiveRecord documentation. I have been using it a lot and can say it's very simple and well tested.

What is the difference between logical data model and conceptual data model?

Conceptual Schema - covers entities and relationships. Should be created first. Contrary to some of the other answers; tables are not defined here. For example a 'many to many' table is not included in a conceptual data model but is defined as a 'many to many' relationship between entities.

Logical Schema - Covers tables, attributes, keys, mandatory role constraints, and referential integrity with no regards to the physical implementation. Things like indexes are not defined, attribute types should be kept logical, e.g. text instead of varchar2. Should be created based on the conceptual schema.

Why doesn't calling a Python string method do anything unless you assign its output?

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")
        newfilenames.append(x)
    else:
        newfilenames.append(i)


print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

Force IE8 Into IE7 Compatiblity Mode

If you add this to your meta tags:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

IE8 will render the page like IE7.

Expected response code 220 but got code "", with message "" in Laravel

That error message means that there was not response OR the server could not be connected.

The following settings worked on my end:

'stream' => [
        'ssl' => [
            'allow_self_signed' => true,
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ]

Note that my SMTP settings are:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=[full gmail address]
MAIL_PASSWORD=[App Password obtained after two step verification]
MAIL_ENCRYPTION=ssl

How do I show/hide a UIBarButtonItem?

Some helper methods I thought I'd share based upon lnafziger's accepted answer as I have multiple toolbars and multiple buttons in each:

-(void) hideToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    [toolbarButtons removeObject:button];
    [toolbar setItems:toolbarButtons animated:NO];
}

-(void) showToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar atIndex:(int) index{
    NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
    if (![toolbarButtons containsObject:button]){
        [toolbarButtons insertObject:button atIndex:index];
        [self setToolbarItems:toolbarButtons animated:YES];
    }
}

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

Try:

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

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

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}