Programs & Examples On #Python module

A module is a file containing Python definitions and statements.

How to do relative imports in Python?

explanation of nosklo's answer with examples

note: all __init__.py files are empty.

main.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       fun_a.py
    package_b/ ->
       __init__.py
       fun_b.py

app/package_a/fun_a.py

def print_a():
    print 'This is a function in dir package_a'

app/package_b/fun_b.py

from app.package_a.fun_a import print_a
def print_b():
    print 'This is a function in dir package_b'
    print 'going to call a function in dir package_a'
    print '-'*30
    print_a()

main.py

from app.package_b import fun_b
fun_b.print_b()

if you run $ python main.py it returns:

This is a function in dir package_b
going to call a function in dir package_a
------------------------------
This is a function in dir package_a
  • main.py does: from app.package_b import fun_b
  • fun_b.py does from app.package_a.fun_a import print_a

so file in folder package_b used file in folder package_a, which is what you want. Right??

Unable to import a module that is definitely installed

The Python import mechanism works, really, so, either:

  1. Your PYTHONPATH is wrong,
  2. Your library is not installed where you think it is
  3. You have another library with the same name masking this one

Python: OSError: [Errno 2] No such file or directory: ''

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

How to import other Python files?

There are many ways to import a python file, all with their pros and cons.

Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.

I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7

Example 1, Import a python module with python interpreter:

  1. Put this in /home/el/foo/fox.py:

    def what_does_the_fox_say():
      print("vixens cry")
    
  2. Get into the python interpreter:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 
    

    You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

  1. Put this in /home/el/foo2/mylib.py:

    def moobar():
      print("hi")
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from ... import ... functionality:

  1. Put this in /home/el/foo3/chekov.py:

    def question():
      print "where are the nuclear wessels?"
    
  2. Put this in /home/el/foo3/main.py:

    from chekov import question
    question()
    
  3. Run it like this:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?
    

    If you defined other functions in chekov.py, they would not be available unless you import *

Example 4, Import riaa.py if it's in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/riaa.py:

    def watchout():
      print "computers are transforming into a noose and a yoke for humans"
    
  2. Put this in /home/el/foo4/main.py:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
    from riaa import *
    watchout()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py 
    computers are transforming into a noose and a yoke for humans
    

    That imports everything in the foreign file from a different directory.

Example 5, use os.system("python yourfile.py")

import os
os.system("python yourfile.py")

Example 6, import your file via piggybacking the python startuphook:

Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.

See: https://docs.python.org/2/library/user.html

Put this code into your home directory in ~/.pythonrc.py

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

Put this code into your main.py (can be anywhere):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

Run it, you should get this:

$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.

Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.

Example 7, Most Robust: Import files in python with the bare import command:

  1. Make a new directory /home/el/foo5/
  2. Make a new directory /home/el/foo5/herp
  3. Make an empty file named __init__.py under herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.py file:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
    
  7. The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

    from herp.derp.yolo import skycake
    skycake()
    
  8. Run it:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!
    

    The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.

If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131

Installing python module within code

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

What does if __name__ == "__main__": do?

All the answers have pretty much explained the functionality. But I will provide one example of its usage which might help clearing out the concept further.

Assume that you have two Python files, a.py and b.py. Now, a.py imports b.py. We run the a.py file, where the "import b.py" code is executed first. Before the rest of the a.py code runs, the code in the file b.py must run completely.

In the b.py code there is some code that is exclusive to that file b.py and we don't want any other file (other than b.py file), that has imported the b.py file, to run it.

So that is what this line of code checks. If it is the main file (i.e., b.py) running the code, which in this case it is not (a.py is the main file running), then only the code gets executed.

How to import a module given the full path?

Do you mean load or import?

You can manipulate the sys.path list specify the path to your module, then import your module. For example, given a module at:

/foo/bar.py

You could do:

import sys
sys.path[0:0] = ['/foo'] # puts the /foo directory at the start of your path
import bar

How do I find out my python path using python?

Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:

sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
os.environ['PYTHONPATH'].split(os.pathsep)

How to write a Python module/package?

Make a file named "hello.py"

If you are using Python 2.x

def func():
    print "Hello"

If you are using Python 3.x

def func():
    print("Hello")

Run the file. Then, you can try the following:

>>> import hello
>>> hello.func()
Hello

If you want a little bit hard, you can use the following:

If you are using Python 2.x

def say(text):
    print text

If you are using Python 3.x

def say(text):
    print(text)

See the one on the parenthesis beside the define? That is important. It is the one that you can use within the define.

Text - You can use it when you want the program to say what you want. According to its name, it is text. I hope you know what text means. It means "words" or "sentences".

Run the file. Then, you can try the following if you are using Python 3.x:

>>> import hello
>>> hello.say("hi")
hi
>>> from hello import say
>>> say("test")
test

For Python 2.x - I guess same thing with Python 3? No idea. Correct me if I made a mistake on Python 2.x (I know Python 2 but I am used with Python 3)

Path to MSBuild

For Visual Studio 2017 without knowing the exact edition you could use this in a batch script:

FOR /F "tokens=* USEBACKQ" %%F IN (`where /r "%PROGRAMFILES(x86)%\Microsoft Visual 
Studio\2017" msbuild.exe ^| findstr /v /i "amd64"`) DO (SET msbuildpath=%%F)

The findstr command is to ignore certain msbuild executables (in this example the amd64).

Remove all git files from a directory?

cd to the repository then

find . -name ".git*" -exec rm -R {} \;

Make sure not to accidentally pipe a single dot, slash, asterisk, or other regex wildcard into find, or else rm will happily delete it.

Executing JavaScript after X seconds

onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"

Change 1000 to the number of milliseconds you want to delay.

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

How to put a delay on AngularJS instant search?

I think the easiest way here is to preload the json or load it once on$dirty and then the filter search will take care of the rest. This'll save you the extra http calls and its much faster with preloaded data. Memory will hurt, but its worth it.

Search for all files in project containing the text 'querystring' in Eclipse

Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)

https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

How can you determine a point is between two other points on a line segment?

You can use the wedge and dot product:

def dot(v,w): return v.x*w.x + v.y*w.y
def wedge(v,w): return v.x*w.y - v.y*w.x

def is_between(a,b,c):
   v = a - b
   w = b - c
   return wedge(v,w) == 0 and dot(v,w) > 0

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Appending an element to the end of a list in Scala

We can append or prepend two lists or list&array
Append:

var l = List(1,2,3)    
l = l :+ 4 
Result : 1 2 3 4  
var ar = Array(4, 5, 6)    
for(x <- ar)    
{ l = l :+ x }  
  l.foreach(println)

Result:1 2 3 4 5 6

Prepending:

var l = List[Int]()  
   for(x <- ar)  
    { l= x :: l } //prepending    
     l.foreach(println)   

Result:6 5 4 1 2 3

Unable to convert MySQL date/time value to System.DateTime

In a Stimulsoft report add this parameter to the connection string (right click on datasource->edit)

Convert Zero Datetime=True;

How to return rows from left table not found in right table?

I can't add anything but a code example to the other two answers: however, I find it can be useful to see it in action (the other answers, in my opinion, are better because they explain it).

DECLARE @testLeft TABLE (ID INT, SomeValue VARCHAR(1))
DECLARE @testRight TABLE (ID INT, SomeOtherValue VARCHAR(1))

INSERT INTO @testLeft (ID, SomeValue) VALUES (1, 'A')
INSERT INTO @testLeft (ID, SomeValue) VALUES (2, 'B')
INSERT INTO @testLeft (ID, SomeValue) VALUES (3, 'C')


INSERT INTO @testRight (ID, SomeOtherValue) VALUES (1, 'X')
INSERT INTO @testRight (ID, SomeOtherValue) VALUES (3, 'Z')

SELECT l.*
FROM 
    @testLeft l
     LEFT JOIN 
    @testRight r ON 
        l.ID = r.ID
WHERE r.ID IS NULL 

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

'heroku' does not appear to be a git repository

First, make sure you're logged into heroku:

heroku login 

Enter your credentials.

It's common to get this error when using a cloned git repo onto a new machine. Even if your heroku credentials are already on the machine, there is no link between the cloned repo and heroku locally yet. To do this, cd into the root dir of the cloned repo and run

heroku git:remote -a yourapp

How To Execute SSH Commands Via PHP

I've had a hard time with ssh2 in php mostly because the output stream sometimes works and sometimes it doesn't. I'm just gonna paste my lib here which works for me very well. If there are small inconsistencies in code it's because I have it plugged in a framework but you should be fine porting it:

<?php

class Components_Ssh {

    private $host;

    private $user;

    private $pass;

    private $port;

    private $conn = false;

    private $error;

    private $stream;

    private $stream_timeout = 100;

    private $log;

    private $lastLog;

    public function __construct ( $host, $user, $pass, $port, $serverLog ) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->port = $port;
        $this->sLog = $serverLog;

        if ( $this->connect ()->authenticate () ) {
            return true;
        }
    }

    public function isConnected () {
        return ( boolean ) $this->conn;
    }

    public function __get ( $name ) {
        return $this->$name;
    }

    public function connect () {
        $this->logAction ( "Connecting to {$this->host}" );
        if ( $this->conn = ssh2_connect ( $this->host, $this->port ) ) {
            return $this;
        }
        $this->logAction ( "Connection to {$this->host} failed" );
        throw new Exception ( "Unable to connect to {$this->host}" );
    }

    public function authenticate () {
        $this->logAction ( "Authenticating to {$this->host}" );
        if ( ssh2_auth_password ( $this->conn, $this->user, $this->pass ) ) {
            return $this;
        }
        $this->logAction ( "Authentication to {$this->host} failed" );
        throw new Exception ( "Unable to authenticate to {$this->host}" );
    }

    public function sendFile ( $localFile, $remoteFile, $permision = 0644 ) {
        if ( ! is_file ( $localFile ) ) throw new Exception ( "Local file {$localFile} does not exist" );
        $this->logAction ( "Sending file $localFile as $remoteFile" );

        $sftp = ssh2_sftp ( $this->conn );
        $sftpStream = @fopen ( 'ssh2.sftp://' . $sftp . $remoteFile, 'w' );
        if ( ! $sftpStream ) {
            //  if 1 method failes try the other one
            if ( ! @ssh2_scp_send ( $this->conn, $localFile, $remoteFile, $permision ) ) {
                throw new Exception ( "Could not open remote file: $remoteFile" );
            }
            else {
                return true;
            }
        }

        $data_to_send = @file_get_contents ( $localFile );

        if ( @fwrite ( $sftpStream, $data_to_send ) === false ) {
            throw new Exception ( "Could not send data from file: $localFile." );
        }

        fclose ( $sftpStream );

        $this->logAction ( "Sending file $localFile as $remoteFile succeeded" );
        return true;
    }

    public function getFile ( $remoteFile, $localFile ) {
        $this->logAction ( "Receiving file $remoteFile as $localFile" );
        if ( ssh2_scp_recv ( $this->conn, $remoteFile, $localFile ) ) {
            return true;
        }
        $this->logAction ( "Receiving file $remoteFile as $localFile failed" );
        throw new Exception ( "Unable to get file to {$remoteFile}" );
    }

    public function cmd ( $cmd, $returnOutput = false ) {
        $this->logAction ( "Executing command $cmd" );
        $this->stream = ssh2_exec ( $this->conn, $cmd );

        if ( FALSE === $this->stream ) {
            $this->logAction ( "Unable to execute command $cmd" );
            throw new Exception ( "Unable to execute command '$cmd'" );
        }
        $this->logAction ( "$cmd was executed" );

        stream_set_blocking ( $this->stream, true );
        stream_set_timeout ( $this->stream, $this->stream_timeout );
        $this->lastLog = stream_get_contents ( $this->stream );

        $this->logAction ( "$cmd output: {$this->lastLog}" );
        fclose ( $this->stream );
        $this->log .= $this->lastLog . "\n";
        return ( $returnOutput ) ? $this->lastLog : $this;
    }

    public function shellCmd ( $cmds = array () ) {
        $this->logAction ( "Openning ssh2 shell" );
        $this->shellStream = ssh2_shell ( $this->conn );

        sleep ( 1 );
        $out = '';
        while ( $line = fgets ( $this->shellStream ) ) {
            $out .= $line;
        }

        $this->logAction ( "ssh2 shell output: $out" );

        foreach ( $cmds as $cmd ) {
            $out = '';
            $this->logAction ( "Writing ssh2 shell command: $cmd" );
            fwrite ( $this->shellStream, "$cmd" . PHP_EOL );
            sleep ( 1 );
            while ( $line = fgets ( $this->shellStream ) ) {
                $out .= $line;
                sleep ( 1 );
            }
            $this->logAction ( "ssh2 shell command $cmd output: $out" );
        }

        $this->logAction ( "Closing shell stream" );
        fclose ( $this->shellStream );
    }

    public function getLastOutput () {
        return $this->lastLog;
    }

    public function getOutput () {
        return $this->log;
    }

    public function disconnect () {
        $this->logAction ( "Disconnecting from {$this->host}" );
        // if disconnect function is available call it..
        if ( function_exists ( 'ssh2_disconnect' ) ) {
            ssh2_disconnect ( $this->conn );
        }
        else { // if no disconnect func is available, close conn, unset var
            @fclose ( $this->conn );
            $this->conn = false;
        }
        // return null always
        return NULL;
    }

    public function fileExists ( $path ) {
        $output = $this->cmd ( "[ -f $path ] && echo 1 || echo 0", true );
        return ( bool ) trim ( $output );
    }
}

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

Try this : Here is the code which i'm using to send emails to multiple user.

 public string gmail_send()
    {
        using (MailMessage mailMessage =
        new MailMessage(new MailAddress(toemail),
    new MailAddress(toemail)))
        {
            mailMessage.Body = body;
            mailMessage.Subject = subject;
            try
            {
                SmtpClient SmtpServer = new SmtpClient();
                SmtpServer.Credentials =
                    new System.Net.NetworkCredential(email, password);
                SmtpServer.Port = 587;
                SmtpServer.Host = "smtp.gmail.com";
                SmtpServer.EnableSsl = true;
                mail = new MailMessage();
                String[] addr = toemail.Split(','); // toemail is a string which contains many email address separated by comma
                mail.From = new MailAddress(email);
                Byte i;
                for (i = 0; i < addr.Length; i++)
                    mail.To.Add(addr[i]);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.DeliveryNotificationOptions =
                    DeliveryNotificationOptions.OnFailure;
                //   mail.ReplyTo = new MailAddress(toemail);
                mail.ReplyToList.Add(toemail);
                SmtpServer.Send(mail);
                return "Mail Sent";
            }
            catch (Exception ex)
            {
                string exp = ex.ToString();
                return "Mail Not Sent ... and ther error is " + exp;
            }
        }
    }

Why am I getting a "401 Unauthorized" error in Maven?

Also, after you've updated your repository ids, make sure you run clean as release:prepare will pick up where it left off. So you can do:

mvn release:prepare -Dresume=false or

mvn release:clean release:prepare

Java Scanner class reading strings

You could have simply replaced

names[i] = in.nextLine(); with names[i] = in.next();

Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

This is a particularly involved problem on Windows, where it's not enough to just chmod the files correctly. You have to set up your environment.

On Windows, this worked for me:

  1. Install cygwin.

  2. Replace the msysgit ssh.exe with cygwin's ssh.exe.

  3. Using cygwin bash, chmod 600 the private key file, which was "id_rsa" for me.

  4. If it still doesn't work, go to Control Panel -> System Properties -> Advanced -> Environment Variables and add the following environment variable. Then repeat step 3.

    Variable      Value
    CYGWIN      sbmntsec

How to make a radio button look like a toggle button

I usually hide the real radio buttons with CSS (or make them into individual hidden inputs), put in the imagery I want (you could use an unordered list and apply your styles to the li element) and then use click events to toggle the inputs. That approach also means you can keep things accessible for users who aren't on a normal web browser-- just hide your ul by default and show the radio buttons.

One time page refresh after first page load

I'd say use hash, like this:

window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
}

Add one year in current date PYTHON

You can use Python-dateutil's relativedelta to increment a datetime object while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following:

from dateutil.relativedelta import relativedelta

new_date = old_date + relativedelta(years=1)

(This answer was given by @Max to a similar question).

But if your date is a string (i.e. not already a datetime object) you can convert it using datetime:

from datetime import datetime
from dateutil.relativedelta import relativedelta

your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"

datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + relativedelta(years=1)
new_date_string = datetime.strftime(new_date, format_string).replace(' 0', ' ')

new_date_string will contain "April 1, 2013".

NB: Unfortunately, datetime only outputs day values as "decimal numbers" - i.e. with leading zeros if they're single digit numbers. The .replace() at the end is a workaround to deal with this issue copied from @Alex Martelli (see this question for his and other approaches to this problem).

Styling HTML5 input type number

There are only 4 specific atrributes:

  1. value - Value is the default value of the input box when a page is first loaded. This is a common attribute for element regardless which type you are using.
  2. min - Obviously, the minimum value you of the number. I should have specified minimum value to 0 for my demo up there as a negative number doesn't make sense for number of movie watched in a week.
  3. max - Apprently, this represents the biggest number of the number input.
  4. step - Step scale factor, default value is 1 if this attribute is not specified.

So you cannot control length of what user type by keyword. But the implementation of browsers may change.

Show datalist labels but submit the actual value

The solution I use is the following:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.

How to set the From email address for mailx command?

The "-r" option is invalid on my systems. I had to use a different syntax for the "From" field.

-a "From: Foo Bar <[email protected]>"

How to hide a div after some time period?

_x000D_
_x000D_
$().ready(function(){_x000D_
_x000D_
  $('div.alert').delay(1500);_x000D_
   $('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
_x000D_
_x000D_

Maven Out of Memory Build Failure

I got same problem trying to compile "clean install" using a Lowend 512Mb ram VPS and good CPU. Run OutOfMemory and killed script repeatly.

I used export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=350m" and worked.

Still getting some other compiling failure because is the first time i need Maven, but OutOfMemory problem has gone.

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Cause: The error occurred since hibernate is not able to connect to the database.
Solution:
1. Please ensure that you have a database present at the server referred to in the configuration file eg. "hibernatedb" in this case.
2. Please see if the username and password for connecting to the db are correct.
3. Check if relevant jars required for the connection are mapped to the project.

What are Unwind segues for and how do you use them?

Something that I didn't see mentioned in the other answers here is how you deal with unwinding when you don't know where the initial segue originated, which to me is an even more important use case. For example, say you have a help view controller (H) that you display modally from two different view controllers (A and B):

A ? H
B ? H

How do you set up the unwind segue so that you go back to the correct view controller? The answer is that you declare an unwind action in A and B with the same name, e.g.:

// put in AViewController.swift and BViewController.swift
@IBAction func unwindFromHelp(sender: UIStoryboardSegue) {
    // empty
}

This way, the unwind will find whichever view controller (A or B) initiated the segue and go back to it.

In other words, think of the unwind action as describing where the segue is coming from, rather than where it is going to.

Adding a custom header to HTTP request using angular.js

What you see for OPTIONS request is fine. Authorisation headers are not exposed in it.

But in order for basic auth to work you need to add: withCredentials = true; to your var config.

From the AngularJS $http documentation:

withCredentials - {boolean} - whether to to set the withCredentials flag on the XHR object. See requests with credentials for more information.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How to pass props to {this.props.children}

Maybe you can also find useful this feature, though many people have considered this as an anti-pattern it still can be used if you're know what you're doing and design your solution well.

Function as Child Components

Changing CSS style from ASP.NET code

As a NOT TO DO - Another way would be to use:

divControl.Attributes.Add("style", "height: number");

But don't use this as its messy and the answer by AviewAnew is the correct way.

Visual Studio Code: format is not using indent settings

I think vscode is using autopep8 to format .py by default.

"PEP 8 -- Style Guide for Python Code | Python.org"

According to this website, the following may explain why vscode always use 4 spaces.

Use 4 spaces per indentation level.

Why do Sublime Text 3 Themes not affect the sidebar?

One simple way to do this is :
Go to Preferences -> Package Settings -> Your Theme Name -> Activation

In my case I installed Boxy Theme so the path will be
Preferences -> Package Settings -> Boxy Theme -> Activation

Then there will be a pop-up menu that will let you choose which type of the theme package you want to activate.
Use up and down arrow so choose then press enter or simply click the one you want to choose.

This is steps only applicable if the theme installed also customized the sublime text 3 sidebar.

Hope it help anyone!

Get first n characters of a string

It's best to abstract you're code like so (notice the limit is optional and defaults to 10):

print limit($string);


function limit($var, $limit=10)
{
    if ( strlen($var) > $limit )
    {
        return substr($string, 0, $limit) . '...';
    }
    else
    {
        return $var;
    }
}

Uploading both data and files in one form using Ajax?

<form id="form" method="post" action="otherpage.php" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button type='button' id='submit_btn'>Submit</button>
</form>

<script>
$(document).on("click", "#submit_btn", function (e) {
    //Prevent Instant Click  
    e.preventDefault();
    // Create an FormData object 
    var formData = $("#form").submit(function (e) {
        return;
    });
    //formData[0] contain form data only 
    // You can directly make object via using form id but it require all ajax operation inside $("form").submit(<!-- Ajax Here   -->)
    var formData = new FormData(formData[0]);
    $.ajax({
        url: $('#form').attr('action'),
        type: 'POST',
        data: formData,
        success: function (response) {
            console.log(response);
        },
        contentType: false,
        processData: false,
        cache: false
    });
    return false;
});
</script>

///// otherpage.php

<?php
    print_r($_FILES);
?>

Get the content of a sharepoint folder with Excel VBA

Use the UNC path rather than HTTP. This code works:

Public Sub ListFiles()
    Dim folder As folder
    Dim f As File
    Dim fs As New FileSystemObject
    Dim RowCtr As Integer

    RowCtr = 1
    Set folder = fs.GetFolder("\\SharePointServer\Path\MorePath\DocumentLibrary\Folder")
    For Each f In folder.Files
       Cells(RowCtr, 1).Value = f.Name
       RowCtr = RowCtr + 1
    Next f
End Sub

To get the UNC path to use, go into the folder in the document library, drop down the Actions menu and choose Open in Windows Explorer. Copy the path you see there and use that.

Can I use GDB to debug a running process?

Yes. Use the attach command. Check out this link for more information. Typing help attach at a GDB console gives the following:

(gdb) help attach

Attach to a process or file outside of GDB. This command attaches to another target, of the same type as your last "target" command ("info files" will show your target stack). The command may take as argument a process id, a process name (with an optional process-id as a suffix), or a device file. For a process id, you must have permission to send the process a signal, and it must have the same effective uid as the debugger. When using "attach" to an existing process, the debugger finds the program running in the process, looking first in the current working directory, or (if not found there) using the source file search path (see the "directory" command). You can also use the "file" command to specify the program, and to load its symbol table.


NOTE: You may have difficulty attaching to a process due to improved security in the Linux kernel - for example attaching to the child of one shell from another.

You'll likely need to set /proc/sys/kernel/yama/ptrace_scope depending on your requirements. Many systems now default to 1 or higher.

The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other
    process running under the same uid, as long as it is dumpable (i.e.
    did not transition uids, start privileged, or have called
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is
    unchanged.

1 - restricted ptrace: a process must have a predefined relationship
    with the inferior it wants to call PTRACE_ATTACH on. By default,
    this relationship is that of only its descendants when the above
    classic criteria is also met. To change the relationship, an
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare
    an allowed debugger PID to call PTRACE_ATTACH on the inferior.
    Using PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

Make install, but not to default directories?

try using INSTALL_ROOT.

make install INSTALL_ROOT=$INSTALL_DIRECTORY

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

Beware when comparing a .Net DateTime to SqlDateTime.MinValue or MaxValue. For example, the following will throw an exception:

DateTime dte = new DateTime(1000, 1, 1);
if (dte >= SqlDateTime.MinValue)
    //do something

The reason is that MinValue returns a SqlDateTime, not a DateTime. So .Net tries to convert dte to a SqlDateTime for comparison and because it's outside the acceptable SqlDateTime range it throws the exception.

One solution to this is to compare your DateTime to SqlDateTime.MinValue.Value.

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

I'll show you with a pic!

  1. Add a new File Add a new File

  2. Go to Project/Build Setting/APPl LLVM 6.0-Language Add a new File

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

Test process.env with Jest

Depending on how you can organize your code, another option can be to put the environment variable within a function that's executed at runtime.

In this file, the environment variable is set at import time and requires dynamic requires in order to test different environment variables (as described in this answer):

const env = process.env.MY_ENV_VAR;

const envMessage = () => `MY_ENV_VAR is set to ${env}!`;

export default myModule;

In this file, the environment variable is set at envMessage execution time, and you should be able to mutate process.env directly in your tests:

const envMessage = () => {
  const env = process.env.MY_VAR;
  return `MY_ENV_VAR is set to ${env}!`;
}

export default myModule;

Jest test:

const vals = [
  'ONE',
  'TWO',
  'THREE',
];

vals.forEach((val) => {
  it(`Returns the correct string for each ${val} value`, () => {
    process.env.MY_VAR = val;

    expect(envMessage()).toEqual(...

jQuery Scroll to Div

if the link element is:

<a id="misc" href="#misc">Miscellaneous</a>

and the Miscellaneous category is bounded by something like:

<p id="miscCategory" name="misc">....</p>

you can use jQuery to do the desired effect:

<script type="text/javascript">
  $("#misc").click(function() {
    $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});
  });
</script>

as far as I remember it correctly.. (though, I haven't tested it and wrote it from memory)

How do I programmatically force an onchange event on an input?

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

How to set up devices for VS Code for a Flutter emulator

You do not need to create a virtual device using android studio. You can use your android device running on android 8.0 or higher. All you have to do is to activate developer settings, then enable USB DEBUGGING in the developer settings. Your device will show at the bottom right side of the VS Code. Without enabling the USB debugging, the device may not show.enter image description here

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

To remove the blue overlay on mobiles, you can use one of the following:

-webkit-tap-highlight-color: transparent; /* transparent with keyword */
-webkit-tap-highlight-color: rgba(0,0,0,0); /* transparent with rgba */
-webkit-tap-highlight-color: hsla(0,0,0,0); /* transparent with hsla */
-webkit-tap-highlight-color: #00000000; /* transparent with hex with alpha */
-webkit-tap-highlight-color: #0000; /* transparent with short hex with alpha */

However, unlike other properties, you can't use

-webkit-tap-highlight-color: none; /* none keyword */

In DevTools, this will show up as an 'invalid property value' or something.


To remove the blue/black/orange outline when focused, use this:

:focus {
    outline: none; /* no outline - for most browsers */
    box-shadow: none; /* no box shadow - for some browsers or if you are using Bootstrap */
}

The reason why I removed the box-shadow is because Bootsrap (and some browsers) sometimes add it to focused elements, so you can remove it using this.

But if anyone is navigating with a keyboard, they will get very confused indeed, because they rely on this outline to navigate. So you can replace it instead

:focus {
    outline: 100px dotted #f0f; /* 100px dotted pink outline */
}

You can target taps on mobile using :hover or :active, so you could use those to help, possibly. Or it could get confusing.


Full code:

element {
    -webkit-tap-highlight-color: transparent; /* remove tap highlight */
}
element:focus {
    outline: none; /* remove outline */
    box-shadow: none; /* remove box shadow */
}

Other information:

  • If you would like to customise the -webkit-tap-highlight-color then you should set it to a semi-transparent color so the element underneath doesn't get hidden when tapped
  • Please don't remove the outline from focused elements, or add some more styles for them.
  • -webkit-tap-highlight-color has not got great browser support and is not standard. You can still use it, but watch out!

Create a .csv file with values from a Python list

Jupyter notebook

Let's say that your list name is A

Then you can code the following and you will have it as a csv file (columns only!)

R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Loose Coupling is the process of giving the dependency your class needs indirectly without providing all the information of the dependency(i.e in the from of interface) in case tight coupling you directly give in the dependency which is not good way of coding.

Function pointer to member function

Call member function on string command

#include <iostream>
#include <string>


class A 
{
public: 
    void call();
private:
    void printH();
    void command(std::string a, std::string b, void (A::*func)());
};

void A::printH()
{
    std::cout<< "H\n";
}

void A::call()
{
    command("a","a", &A::printH);
}

void A::command(std::string a, std::string b, void (A::*func)())
{
    if(a == b)
    {
        (this->*func)();
    }
}

int main()
{
    A a;
    a.call();
    return 0;
}

Pay attention to (this->*func)(); and the way to declare the function pointer with class name void (A::*func)()

How to create a inner border for a box in html?

Take a look at this , we can simply do this with outline-offset property

Output image look like

enter image description here

_x000D_
_x000D_
.black_box {_x000D_
    width:500px;_x000D_
    height:200px;_x000D_
    background:#000;_x000D_
    float:left;_x000D_
    border:2px solid #000;_x000D_
    outline: 1px dashed #fff;_x000D_
    outline-offset: -10px;_x000D_
}
_x000D_
<div class="black_box"></div>
_x000D_
_x000D_
_x000D_

How can I get the named parameters from a URL using Flask?

The URL parameters are available in request.args, which is an ImmutableMultiDict that has a get method, with optional parameters for default value (default) and type (type) - which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)

from flask import request

@app.route('/my-route')
def my_route():
  page = request.args.get('page', default = 1, type = int)
  filter = request.args.get('filter', default = '*', type = str)

Examples with the code above:

/my-route?page=34               -> page: 34  filter: '*'
/my-route                       -> page:  1  filter: '*'
/my-route?page=10&filter=test   -> page: 10  filter: 'test'
/my-route?page=10&filter=10     -> page: 10  filter: '10'
/my-route?page=*&filter=*       -> page:  1  filter: '*'

405 method not allowed Web API

For my part my POST handler was of this form:

[HttpPost("{routeParam}")]
public async Task<ActionResult> PostActuality ([FromRoute] int routeParam, [FromBody] PostData data)

I figured out that I had to swap the arguments, that is to say the body data first then the route parameter, as this:

[HttpPost("{routeParam}")]
public async Task<ActionResult> PostActuality ([FromBody] PostData data, [FromRoute] int routeParam)

Using JQuery to open a popup window and print

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

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

or

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

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.

DECLARE @TABLE TABLE
(  
ID INT,  
USERS VARCHAR(10),  
ACTIVITY VARCHAR(10),  
PAGEURL VARCHAR(10)  
)

INSERT INTO @TABLE  
VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')


SELECT T1.USERS, T1.ACTIVITY,   
        STUFF(  
        (  
        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  
        ),1,1,'')  
FROM @TABLE T1  
GROUP BY T1.USERS, T1.ACTIVITY

What is username and password when starting Spring Boot with Tomcat?

When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
        return new InMemoryUserDetailsManager(users);
    }
}

So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)

Note: This we should not use in production.

Resource files not found from JUnit test cases

You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.

All that stuff represents the default in Maven. So best practice is don't define it it's already done.

    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

Most efficient way to remove special characters from string

If you're worried about speed, use pointers to edit the existing string. You could pin the string and get a pointer to it, then run a for loop over each character, overwriting each invalid character with a replacement character. It would be extremely efficient and would not require allocating any new string memory. You would also need to compile your module with the unsafe option, and add the "unsafe" modifier to your method header in order to use pointers.

static void Main(string[] args)
{
    string str = "string!$%with^&*invalid!!characters";
    Console.WriteLine( str ); //print original string
    FixMyString( str, ' ' );
    Console.WriteLine( str ); //print string again to verify that it has been modified
    Console.ReadLine(); //pause to leave command prompt open
}


public static unsafe void FixMyString( string str, char replacement_char )
{
    fixed (char* p_str = str)
    {
        char* c = p_str; //temp pointer, since p_str is read-only
        for (int i = 0; i < str.Length; i++, c++) //loop through each character in string, advancing the character pointer as well
            if (!IsValidChar(*c)) //check whether the current character is invalid
                (*c) = replacement_char; //overwrite character in existing string with replacement character
    }
}

public static bool IsValidChar( char c )
{
    return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '.' || c == '_');
    //return char.IsLetterOrDigit( c ) || c == '.' || c == '_'; //this may work as well
}

make script execution to unlimited

You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:

ini_set('max_execution_time', 0);

Refer to the PHP documentation of max_execution_time

Note that:

set_time_limit(0);

will have the same effect.

Unable to run Java GUI programs with Ubuntu

This command worked for me.

Sudo dnf install java-1.8.0-openjdk (Fedora)

Sudo apt-get install java-1.8.0-openjdk

Should work for Ubuntu.

How does PHP 'foreach' actually work?

NOTE FOR PHP 7

To update on this answer as it has gained some popularity: This answer no longer applies as of PHP 7. As explained in the "Backward incompatible changes", in PHP 7 foreach works on copy of the array, so any changes on the array itself are not reflected on foreach loop. More details at the link.

Explanation (quote from php.net):

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So, in your first example you only have one element in the array, and when the pointer is moved the next element does not exist, so after you add new element foreach ends because it already "decided" that it it as the last element.

In your second example, you start with two elements, and foreach loop is not at the last element so it evaluates the array on the next iteration and thus realises that there is new element in the array.

I believe that this is all consequence of On each iteration part of the explanation in the documentation, which probably means that foreach does all logic before it calls the code in {}.

Test case

If you run this:

<?
    $array = Array(
        'foo' => 1,
        'bar' => 2
    );
    foreach($array as $k=>&$v) {
        $array['baz']=3;
        echo $v." ";
    }
    print_r($array);
?>

You will get this output:

1 2 3 Array
(
    [foo] => 1
    [bar] => 2
    [baz] => 3
)

Which means that it accepted the modification and went through it because it was modified "in time". But if you do this:

<?
    $array = Array(
        'foo' => 1,
        'bar' => 2
    );
    foreach($array as $k=>&$v) {
        if ($k=='bar') {
            $array['baz']=3;
        }
        echo $v." ";
    }
    print_r($array);
?>

You will get:

1 2 Array
(
    [foo] => 1
    [bar] => 2
    [baz] => 3
)

Which means that array was modified, but since we modified it when the foreach already was at the last element of the array, it "decided" not to loop anymore, and even though we added new element, we added it "too late" and it was not looped through.

Detailed explanation can be read at How does PHP 'foreach' actually work? which explains the internals behind this behaviour.

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

My error was solved by uninstalling all java updates and java from control panel and reinstalling JDK

How do I merge a git tag onto a branch

This is the only comprehensive and reliable way I've found to do this.

Assume you want to merge "tag_1.0" into "mybranch".

    $git checkout tag_1.0 (will create a headless branch)
    $git branch -D tagbranch (make sure this branch doesn't already exist locally)
    $git checkout -b tagbranch
    $git merge -s ours mybranch
    $git commit -am "updated mybranch with tag_1.0"
    $git checkout mybranch
    $git merge tagbranch

Get absolute path of initially run script

realpath($_SERVER['SCRIPT_FILENAME'])

For script run under web server $_SERVER['SCRIPT_FILENAME'] will contain the full path to the initially called script, so probably your index.php. realpath() is not required in this case.

For the script run from console $_SERVER['SCRIPT_FILENAME'] will contain relative path to your initially called script from your current working dir. So unless you changed working directory inside your script it will resolve to the absolute path.

Is there a Java API that can create rich Word documents?

You could use this: http://code.google.com/p/java2word

I implemented this API called Java2Word. with a few lines of code, you can generate one Microsoft Word Document.

Eg.:

IDocument myDoc = new Document2004();
myDoc.getBody().addEle(new Heading1("Heading01"));
myDoc.getBody().addEle(new Paragraph("This is a paragraph...")

There is some examples how to use. Basically you will need one jar file. Let me know if you need any further information how to set it up.

*I wrote this because we had one real necessity in a project. More in my blog:

http ://leonardo-pinho.blogspot.com/2010/07/java2word-word-document-generator-from.html *

cheers Leonardo

Edit : Project in link moved to https://github.com/leonardoanalista/java2word

Android: ListView elements with multiple clickable buttons

I Know it's late but this may help, this is an example how I write custom adapter class for different click actions

 public class CustomAdapter extends BaseAdapter {

    TextView title;
  Button button1,button2;

    public long getItemId(int position) {
        return position;
    }

    public int getCount() {
        return mAlBasicItemsnav.size();  // size of your list array
    }

    public Object getItem(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
        }

        title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById 
        title.setText(mAlBasicItemsnav.get(position));
      button1=(Button) convertView.findViewById(R.id.button1);
      button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

           // if you have different click action at different positions then
            if(position==0)
              {
                       //click action of 1st list item on button click
        }
           if(position==1)
              {
                       //click action of 2st list item on button click
        }
    });

 // similarly for button 2

   button2=(Button) convertView.findViewById(R.id.button2);
      button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

    });



        return convertView;
    }
}

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to remove extension from string (only real extension!)

Use this:

strstr('filename.ext','.',true);
//result filename

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Below are three functions you can use to alter and use the MS Access 2010 Import Specification. The third sub changes the name of an existing import specification. The second sub allows you to change any xml text in the import spec. This is useful if you need to change column names, data types, add columns, change the import file location, etc.. In essence anything you want modify for an existing spec. The first Sub is a routine that allows you to call an existing import spec, modify it for a specific file you are attempting to import, importing that file, and then deleting the modified spec, keeping the import spec "template" unaltered and intact. Enjoy.

Public Sub MyExcelTransfer(myTempTable As String, myPath As String)
On Error GoTo ERR_Handler:
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Dim x As Integer

    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTempTable)
    CurrentProject.ImportExportSpecifications.Add "TemporaryImport", mySpec.XML
    Set myNewSpec = CurrentProject.ImportExportSpecifications.Item("TemporaryImport")

    myNewSpec.XML = Replace(myNewSpec.XML, "\\MyComputer\ChangeThis", myPath)
    myNewSpec.Execute
    myNewSpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
    exit_ErrHandler:
    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
Exit Sub    
ERR_Handler:
    MsgBox Err.Description
    Resume exit_ErrHandler
End Sub

Public Sub fixImportSpecs(myTable As String, strFind As String, strRepl As String)
    Dim mySpec As ImportExportSpecification    
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTable)    
    mySpec.XML = Replace(mySpec.XML, strFind, strRepl)
    Set mySpec = Nothing
End Sub


Public Sub MyExcelChangeName(OldName As String, NewName As String)
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(OldName)    
    CurrentProject.ImportExportSpecifications.Add NewName, mySpec.XML
    mySpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
End Sub

Run multiple python scripts concurrently

You try the following ways to run the multiple python scripts:

  import os
  print "Starting script1"
  os.system("python script1.py arg1 arg2 arg3")
  print "script1 ended"
  print "Starting script2"
  os.system("python script2.py arg1 arg2 arg3")
  print "script2 ended"

Note: The execution of multiple scripts depends purely underlined operating system, and it won't be concurrent, I was new comer in Python when I answered it.

Update: I found a package: https://pypi.org/project/schedule/ Above package can be used to run multiple scripts and function, please check this and maybe on weekend will provide some example too.

i.e:

 import schedule
 import time
 import script1, script2

 def job():
     print("I'm working...")

 schedule.every(10).minutes.do(job)
 schedule.every().hour.do(job)
 schedule.every().day.at("10:30").do(job)
 schedule.every(5).to(10).days.do(job)
 schedule.every().monday.do(job)
 schedule.every().wednesday.at("13:15").do(job)

 while True:
     schedule.run_pending()
     time.sleep(1)

What's the syntax for mod in java

The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).

Java ArrayList for integers

The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values. Just use

List<Integer> list = new ArrayList<>();

to create the ArrayList and it will work.

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

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

List passed by ref - help me explain this behaviour

Use the ref keyword.

Look at the definitive reference here to understand passing parameters.
To be specific, look at this, to understand the behavior of the code.

EDIT: Sort works on the same reference (that is passed by value) and hence the values are ordered. However, assigning a new instance to the parameter won't work because parameter is passed by value, unless you put ref.

Putting ref lets you change the pointer to the reference to a new instance of List in your case. Without ref, you can work on the existing parameter, but can't make it point to something else.

Can you recommend a free light-weight MySQL GUI for Linux?

Try Adminer. The whole application is in one PHP file, which means that the deployment is as easy as it can get. It's more powerful than phpMyAdmin; it can edit views, procedures, triggers, etc.

Adminer is also a universal tool, it can connect to MySQL, PostgreSQL, SQLite, MS SQL, Oracle, SimpleDB, Elasticsearch and MongoDB.

You should definitely give it a try.

enter image description here

You can install on Ubuntu with sudo apt-get install adminer or you can also download the latest version from adminer.org

Running javascript in Selenium using Python

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

java.lang.IllegalArgumentException: contains a path separator

The solution is:

FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE));  // 2nd line

The openFileInput method doesn't accept path separators.

Don't forget to

fis.close();

at the end.

Does reading an entire file leave the file handle open?

The answer to that question depends somewhat on the particular Python implementation.

To understand what this is all about, pay particular attention to the actual file object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read() call returns.

This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".

in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.

A better solution, to make sure that the file is closed, is this pattern:

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

which will always close the file immediately after the block ends; even if an exception occurs.

Edit: To put a finer point on it:

Other than file.__exit__(), which is "automatically" called in a with context manager setting, the only other way that file.close() is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__(). This leads us to the question of when does __del__() get called?

A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.

-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203

In particular:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

[...]

CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.

-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types

(Emphasis mine)

but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!

Laravel redirect back to original destination after login

Laravel 5.2

If you are using a another Middleware like Admin middleware you can set a session for url.intended by using this following:

Basically we need to set manually \Session::put('url.intended', \URL::full()); for redirect.

Example

  if (\Auth::guard($guard)->guest()) {
      if ($request->ajax() || $request->wantsJson()) {
         return response('Unauthorized.', 401);
      } else {
        \Session::put('url.intended', \URL::full());
        return redirect('login');
      }
  }

On login attempt

Make sure on login attempt use return \Redirect::intended('default_path');

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Make sure you open the .xcworkspace file not the project file from xCode Project menu when working with pods. That should solve the issue with linking.

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

This can also come if the target folder is used by some other processes. Close all the programs which may use the target folder and try.

You may use resource monitor(windows tool) to check the processes which uses your target folder.

This worked for me!.

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

Function names in C++: Capitalize or not?

There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.

Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

milliseconds to days

In case you solve a more complex task of logging execution statistics in your code:

public void logExecutionMillis(LocalDateTime start, String callerMethodName) {

  LocalDateTime end = getNow();
  long difference = Duration.between(start, end).toMillis();

  Logger logger = LoggerFactory.getLogger(ProfilerInterceptor.class);

  long millisInDay = 1000 * 60 * 60 * 24;
  long millisInHour = 1000 * 60 * 60;
  long millisInMinute = 1000 * 60;
  long millisInSecond = 1000;

  long days = difference / millisInDay;
  long daysDivisionResidueMillis = difference - days * millisInDay;

  long hours = daysDivisionResidueMillis / millisInHour;
  long hoursDivisionResidueMillis = daysDivisionResidueMillis - hours * millisInHour;

  long minutes = hoursDivisionResidueMillis / millisInMinute;
  long minutesDivisionResidueMillis = hoursDivisionResidueMillis - minutes * millisInMinute;

  long seconds = minutesDivisionResidueMillis / millisInSecond;
  long secondsDivisionResidueMillis = minutesDivisionResidueMillis - seconds * millisInSecond;

  logger.info(
      "\n************************************************************************\n"
          + callerMethodName
          + "() - "
          + difference
          + " millis ("
          + days
          + " d. "
          + hours
          + " h. "
          + minutes
          + " min. "
          + seconds
          + " sec."
          + secondsDivisionResidueMillis
          + " millis).");
}

P.S. Logger can be replaced with simple System.out.println() if you like.

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

    (function() {
        window.spawn = window.spawn || function(gen) {
            function continuer(verb, arg) {
                var result;
                try {
                    result = generator[verb](arg);
                } catch (err) {
                    return Promise.reject(err);
                }
                if (result.done) {
                    return result.value;
                } else {
                    return Promise.resolve(result.value).then(onFulfilled, onRejected);
                }
            }
            var generator = gen();
            var onFulfilled = continuer.bind(continuer, 'next');
            var onRejected = continuer.bind(continuer, 'throw');
            return onFulfilled();
        };
        window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
            url = url || ''; //URL of a dialog
            arg = arg || null; //arguments to a dialog
            opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
            var caller = showModalDialog.caller.toString();
            var dialog = document.body.appendChild(document.createElement('dialog'));
            dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
            dialog.innerHTML = '<a href="#" id="dialog-close" style="position: absolute; top: 0; right: 4px; font-size: 20px; color: #000; text-decoration: none; outline: none;">&times;</a><iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
            document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
            document.getElementById('dialog-close').addEventListener('click', function(e) {
                e.preventDefault();
                dialog.close();
            });
            dialog.showModal();
            //if using yield
            if(caller.indexOf('yield') >= 0) {
                return new Promise(function(resolve, reject) {
                    dialog.addEventListener('close', function() {
                        var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
                        document.body.removeChild(dialog);
                        resolve(returnValue);
                    });
                });
            }
            //if using eval
            var isNext = false;
            var nextStmts = caller.split('\n').filter(function(stmt) {
                if(isNext || stmt.indexOf('showModalDialog(') >= 0)
                    return isNext = true;
                return false;
            });
            dialog.addEventListener('close', function() {
                var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
                document.body.removeChild(dialog);
                nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
                eval('{\n' + nextStmts.join('\n'));
            });
            throw 'Execution stopped until showModalDialog is closed';
        };
    })()

;

**Explanation:
------------**
The best way to deal with showModalDialog for older application conversions is use to `https://github.com/niutech/showModalDialog` inorder to work with show modal dialogs  and if modal dailog has ajax calls you need to create object and set the parameters of function to object and pass below...before that check for browser and set the useragent...example: agentStr = navigator.userAgent; and then check for chrome

var objAcceptReject={}; // create empty object and set the parameters to object and send to the other functions as dialog when opened in chrome breaks the functionality
    function rejectClick(index, transferId) {
        objAcceptReject.index=index;
        objAcceptReject.transferId=transferId;

     agentStr = navigator.userAgent;

                var msie = ua.indexOf("MSIE ");

                if (msie > 0) // If Internet Explorer, return version number
                {
                    var ret = window.showModalDialog("/abc.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {
                        doSomeClick(index);
                    }

                } else if ((agentStr.indexOf("Chrome")) >- 1){
                spawn(function() {

                    var ret = window.showModalDialog("/abcd.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {// create an object and store values in objects and send as parameters
                        doSomeClick(objAcceptReject.index);
                    }

                });

                }
                else {
                    var ret = window.showModalDialog("/xtz.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {
                        doSomeClick(index);
                    }
                }

Select Specific Columns from Spark DataFrame

Problem was to select columns of on dataframe after joining with other dataframe.

I tried below and select the columns of salaryDf from the joined dataframe.

Hope this will help

        val empDf=spark.read.option("header","true").csv("/data/tech.txt")

        val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")

        val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and  empDf.col("last") === salaryDf.col("last"))

      //**below will select the colums of salaryDf only**

     val finalDF=joinData.select(salaryDf.columns map  salaryDf.col:_*)

//same way we can select the columns of empDf
joinData.select(empDf.columns map  empDf.col:_*)

How to iterate over a std::map full of strings in C++

iter->first and iter->second are variables, you are attempting to call them as methods.

Delete specific line number(s) from a text file using sed?

If you want to delete lines 5 through 10 and 12:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will back the file up to file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

How to mount host volumes into docker containers in Dockerfile during build

I think you can do what you want to do by running the build via a docker command which itself is run inside a docker container. See Docker can now run within Docker | Docker Blog. A technique like this, but which actually accessed the outer docker from with a container, was used, e.g., while exploring how to Create the smallest possible Docker container | Xebia Blog.

Another relevant article is Optimizing Docker Images | CenturyLink Labs, which explains that if you do end up downloading stuff during a build, you can avoid having space wasted by it in the final image by downloading, building and deleting the download all in one RUN step.

React native ERROR Packager can't listen on port 8081

That picture indeed shows that your 8081 is not in use. If suggestions above haven't helped, and your mobile device is connected to your computer via usb (and you have Android 5.0 (Lollipop) or above) you could try:

$ adb reconnect

This is not necessary in most cases, but just in case, let's reset your connection with your mobile and restart adb server. Finally:

$ adb reverse tcp:8081 tcp:8081

So, whenever your mobile device tries to access any port 8081 on itself it will be routed to the 8081 port on your PC.

Or, one could try

$ killall node

__FILE__, __LINE__, and __FUNCTION__ usage in C++

I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.

What is parsing in terms that a new programmer would understand?

Simple explanation: Parsing is breaking a block of data into smaller pieces (tokens) by following a set of rules (using delimiters for example), so that this data could be processes piece by piece (managed, analysed, interpreted, transmitted, ets).

Examples: Many applications (like Spreadsheet programs) use CSV (Comma Separated Values) file format to import and export data. CSV format makes it possible for the applications to process this data with a help of a special parser. Web browsers have special parsers for HTML and CSS files. JSON parsers exist. All special file formats must have some parsers designed specifically for them.

How to get twitter bootstrap modal to close (after initial launch)

Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh

I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:

HTML (modal footer):

 <div class="modal-footer form-footer"><br>
              <span class="caption">
                <button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart&nbsp; <i class="fa fa-shopping-cart"></i></button>     
                <button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel&nbsp; <i class="fa fa-close"></i></a>
              </span>
      </div>

jQUERY:

$(document).ready(function(){
// Allow enter key to trigger preloadorders form
    $(document).keypress(function(e) {       
      if(e.which == 13) {   
          e.preventDefault();   
                if($(".trigger").is(".ok")) 
                   $("#PreLoadOrders").trigger("click");
                else
                    return;
      }
    });
});

As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":

HTML:

<div class="modal-footer caption">
                <button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
            </div>

jQuery (include global.inc):

  $(document).ready(function(){
         // Allow enter key to trigger a particular button anywhere on page
        $(document).keypress(function(e) {
                if(e.which == 13) {
                   if($(".modal").is(":visible")){   
                        $(".modal:visible").find(".modal-close").trigger('click');
                    }
                }
         });
    });

Combining a class selector and an attribute selector with jQuery

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

Set TextView text from html-formatted string resource in XML

Android does not have a specification to indicate the type of resource string (e.g. text/plain or text/html). There is a workaround, however, that will allow the developer to specify this within the XML file.

  1. Define a custom attribute to specify that the android:text attribute is html.
  2. Use a subclassed TextView.

Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. I'm rather surprised that this approach is not part of the API.

This solution works to the degree that the Android studio simulator will display the text as rendered HTML.

enter image description here

res/values/strings.xml (the string resource as HTML)

<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
       <em>Hello</em> <strong>World</strong>!
 ]]></string>
</resources>

layout.xml (only the relevant parts)

Declare the custom attribute namespace, and add the android_ex:isHtml attribute. Also use the subclass of TextView.

<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>

<tv.twelvetone.samples.textviewex.TextViewEx
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_html"
    android_ex:isHtml="true"
    />
 </RelativeLayout>

res/values/attrs.xml (define the custom attributes for the subclass)

 <resources>
<declare-styleable name="TextViewEx">
    <attr name="isHtml" format="boolean"/>
    <attr name="android:text" />
</declare-styleable>
</resources>

TextViewEx.java (the subclass of TextView)

 package tv.twelvetone.samples.textviewex;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.support.annotation.Nullable;
 import android.text.Html;
 import android.util.AttributeSet;
 import android.widget.TextView;

public TextViewEx(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
    try {
        boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
        if (isHtml) {
            String text = a.getString(R.styleable.TextViewEx_android_text);
            if (text != null) {
                setText(Html.fromHtml(text));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }
}
}

Should I use != or <> for not equal in T-SQL?

You can use whichever you like in T-SQL. The documentation says they both function the same way. I prefer !=, because it reads "not equal" to my (C/C++/C# based) mind, but database gurus seem to prefer <>.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to handle login pop up window using Selenium WebDriver?

I was getting windows security alert whenever my application was opening. to resolve this issue i used following procedure

import org.openqa.selenium.security.UserAndPassword;
UserAndPassword UP = new UserAndPassword("userName","Password");
driver.switchTo().alert().authenticateUsing(UP);

this resolved my issue of logging into application. I hope this might help who are all looking for authenticating windows security alert.

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

That work sharp for me

SELECT * 
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL

Call child component method from parent class - Angular

Consider the following example,

    import import { AfterViewInit, ViewChild } from '@angular/core';
    import { Component } from '@angular/core';
    import { CountdownTimerComponent }  from './countdown-timer.component';
    @Component({
        selector: 'app-countdown-parent-vc',
        templateUrl: 'app-countdown-parent-vc.html',
        styleUrl: [app-countdown-parent-vc.css]
    export class CreateCategoryComponent implements OnInit {
         @ViewChild(CountdownTimerComponent, {static: false})
         private timerComponent: CountdownTimerComponent;
         ngAfterViewInit() {
             this.timerComponent.startTimer();
         }

         submitNewCategory(){
            this.ngAfterViewInit();     
         }

Read more about @ViewChild here.

Chart.js v2 hide dataset labels

new Chart('idName', {
      type: 'typeChar',
      data: data,
      options: {
        legend: {
          display: false
        }
      }
    });

How could I convert data from string to long in c#

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value

SSH to Elastic Beanstalk instance

Elastic Beanstalk can bind a single EC2 keypair to an instance profile. A manual solution to have multiple users ssh into EBS is to add their public keys in authorized_keys file.

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

How can I make a CSS glass/blur effect work for an overlay?

I came up with this solution.

Click to view image of blurry effect

It is kind of a trick which uses an absolutely positioned child div, sets its background image same as the parent div and then uses the background-attachment:fixed CSS property together with the same background properties set on the parent element.

Then you apply filter:blur(10px) (or any value) on the child div.

_x000D_
_x000D_
*{
    margin:0;
    padding:0;
    box-sizing: border-box;
}
.background{
    position: relative;
    width:100%;
    height:100vh;
    background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-size:cover;
    background-position: center;
    background-repeat:no-repeat;
}

.blur{
    position: absolute;
    top:0;
    left:0;
    width:50%;
    height:100%;
    background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size:cover;
    filter:blur(10px);
    transition:filter .5s ease;
    backface-visibility: hidden;
}

.background:hover .blur{
    filter:blur(0);
}
.text{
    display: inline-block;
    font-family: sans-serif;
    color:white;
    font-weight: 600;
    text-align: center;
    position: relative;
    left:25%;
    top:50%;
    transform:translate(-50%,-50%);
}
_x000D_
<head>
    <title>Blurry Effect</title>
</head>
<body>
    <div class="background">
        <div class="blur"></div>
        <h1 class="text">This is the <br>blurry side</h1>
    </div>
</body>
_x000D_
_x000D_
_x000D_

view on codepen

When to use 'npm start' and when to use 'ng serve'?

Best answer is great, short and on point, but I would like to put my pennyworth.

Basically npm start and ng serve can be used interchangeably in Angular projects as long as you do not want the command to do additional stuff. Let me elaborate on this one.

For example you may want to configure your proxy in package.json start script like this: "start": "ng serve --proxy-config proxy.config.json",

Obviously sole use of ng serve will not be enough.

Another instance is when instead of using the defaults you need to use some additional options ad hoc like define the temporary port: ng serve --port 4444

Some parameters are only available to ng serve, others to npm start. Notice that port option works for both, so in that case it is up to your taste, again. :)

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

How to ensure a <select> form field is submitted when it is disabled?

Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.

Changing route doesn't scroll to top in the new page

The problem is that your ngView retains the scroll position when it loads a new view. You can instruct $anchorScroll to "scroll the viewport after the view is updated" (the docs are a bit vague, but scrolling here means scrolling to the top of the new view).

The solution is to add autoscroll="true" to your ngView element:

<div class="ng-view" autoscroll="true"></div>

Convert String to int array in java

String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");

int[] results = new int[items.length];

for (int i = 0; i < items.length; i++) {
    try {
        results[i] = Integer.parseInt(items[i]);
    } catch (NumberFormatException nfe) {
        //NOTE: write something here if you need to recover from formatting errors
    };
}

How do I extract text that lies between parentheses (round brackets)?

I'm finding that regular expressions are extremely useful but very difficult to write. So, I did some research and found this tool that makes writing them so easy.

Don't shy away from them because the syntax is difficult to figure out. They can be so powerful.

Java Multithreading concept and join() method

See the concept is very simple.

1) All threads are started in the constructor and thus are in ready to run state. Main is already the running thread.

2) Now you called the t1.join(). Here what happens is that the main thread gets knotted behind the t1 thread. So you can imagine a longer thread with main attached to the lower end of t1.

3) Now there are three threads which could run: t2, t3 and combined thread(t1 + main).

4)Now since till t1 is finished main can't run. so the execution of the other two join statements has been stopped.

5) So the scheduler now decides which of the above mentioned(in point 3) threads run which explains the output.

window.onunload is not working properly in Chrome browser. Can any one help me?

The onunload event won't fire if the onload event did not fire. Unfortunately the onload event waits for all binary content (e.g. images) to load, and inline scripts run before the onload event fires. DOMContentLoaded fires when the page is visible, before onload does. And it is now standard in HTML 5, and you can test for browser support but note this requires the <!DOCTYPE html> (at least in Chrome). However, I can not find a corresponding event for unloading the DOM. And such a hypothetical event might not work because some browsers may keep the DOM around to perform the "restore tab" feature.

The only potential solution I found so far is the Page Visibility API, which appears to require the <!DOCTYPE html>.

Centering a background image, using CSS

Try this background-position: center top;

This will do the trick for you.

Get Enum from Description attribute

You need to iterate through all the enum values in Animal and return the value that matches the description you need.

php REQUEST_URI

You can simply use $_GET especially if you know the othervar's name. If you want to be on the safe side, use if (isset ($_GET ['varname'])) to test for existence.

Multiple "style" attributes in a "span" tag: what's supposed to happen?

Separate your rules with a semi colon in a single declaration:

<span style="color:blue;font-style:italic">Test</span>

Truncating all tables in a Postgres database

In this case it would probably be better to just have an empty database that you use as a template and when you need to refresh, drop the existing database and create a new one from the template.

Setting an int to Infinity in C++

int is inherently finite; there's no value that satisfies your requirements.

If you're willing to change the type of b, though, you can do this with operator overrides:

class infinitytype {};

template<typename T>
bool operator>(const T &, const infinitytype &) {
  return false;
}

template<typename T>
bool operator<(const T &, const infinitytype &) {
  return true;
}

bool operator<(const infinitytype &, const infinitytype &) {
  return false;
}


bool operator>(const infinitytype &, const infinitytype &) {
  return false;
}

// add operator==, operator!=, operator>=, operator<=...

int main() {
  std::cout << ( INT_MAX < infinitytype() ); // true
}

How to force remounting on React components?

I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.

import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';

const LifeActionCreate = () => {
  let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();

  const onCreate = e => {
    const db = firebase.firestore();

    db.collection('actions').add({
      label: newLifeActionLabel
    });
    alert('New Life Insurance Added');
    setNewLifeActionLabel('');
  };

  return (
    <Card style={{ padding: '15px' }}>
      <form onSubmit={onCreate}>
        <label>Name</label>
        <input
          value={newLifeActionLabel}
          onChange={e => {
            setNewLifeActionLabel(e.target.value);
          }}
          placeholder={'Name'}
        />

        <Button onClick={onCreate}>Create</Button>
      </form>
    </Card>
  );
};

Some React Hooks in there

Combining C++ and C - how does #ifdef __cplusplus work?

It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.

Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.

While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.

People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:

First

  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)

Second

  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)

References:

Example:

<location path="upl">
   <system.web>
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering>          
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />
       </requestFiltering>
     </security>
   </system.webServer>
 </location>

How do you detect the clearing of a "search" HTML5 input?

The search or onclick works... but the issue I found was with the older browsers - the search fails. Lots of plugins (jquery ui autocomplete or fancytree filter) have blur and focus handlers. Adding this to an autocomplete input box worked for me(used this.value == "" because it was faster to evaluate). The blur then focus kept the cursor in the box when you hit the little 'x'.

The PropertyChange and input worked for both IE 10 and IE 8 as well as other browsers:

$("#INPUTID").on("propertychange input", function(e) { 
    if (this.value == "") $(this).blur().focus(); 
});

For FancyTree filter extension, you can use a reset button and force it's click event as follows:

var TheFancyTree = $("#FancyTreeID").fancytree("getTree");

$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
    var n,
    leavesOnly = false,
    match = $(this).val();
    // check for the escape key or empty filter
    if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
        $("button#btnResetSearch").click();
        return;
    }

    n = SiteNavTree.filterNodes(function (node) {
        return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
        }, leavesOnly);

    $("button#btnResetSearch").attr("disabled", false);
    $("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();

// handle the reset and check for empty filter field... 
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
    if ($("input[name=FT_FilterINPUT]").val() != "")
        $("input[name=FT_FilterINPUT]").val("");
    $("span#SiteNavMatches").text("");
    SiteNavTree.clearFilter();
}).attr("disabled", true);

Should be able to adapt this for most uses.

How to use the IEqualityComparer

The inclusion of your comparison class (or more specifically the AsEnumerable call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.

You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.

jQuery .get error response function?

If you want a generic error you can setup all $.ajax() (which $.get() uses underneath) requests jQuery makes to display an error using $.ajaxSetup(), for example:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("An AJAX error occured: " + status + "\nError: " + error);
  }
});

Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error option to default to the handler/function above, if you made a full $.ajax() call and specified the error handler then what you had would override the above.

When to use NSInteger vs. int

As of currently (September 2014) I would recommend using NSInteger/CGFloat when interacting with iOS API's etc if you are also building your app for arm64. This is because you will likely get unexpected results when you use the float, long and int types.

EXAMPLE: FLOAT/DOUBLE vs CGFLOAT

As an example we take the UITableView delegate method tableView:heightForRowAtIndexPath:.

In a 32-bit only application it will work fine if it is written like this:

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

float is a 32-bit value and the 44 you are returning is a 32-bit value. However, if we compile/run this same piece of code in a 64-bit arm64 architecture the 44 will be a 64-bit value. Returning a 64-bit value when a 32-bit value is expected will give an unexpected row height.

You can solve this issue by using the CGFloat type

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

This type represents a 32-bit float in a 32-bit environment and a 64-bit double in a 64-bit environment. Therefore when using this type the method will always receive the expected type regardless of compile/runtime environment.

The same is true for methods that expect integers. Such methods will expect a 32-bit int value in a 32-bit environment and a 64-bit long in a 64-bit environment. You can solve this case by using the type NSInteger which serves as an int or a long based on the compile/runtime environemnt.

How to set a cookie for another domain

In this link, we will find the solution Link.

setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "b.com", 1);

Folder is locked and I can't unlock it

I had this happen after having Tortoise get corrupted and crash while trying to update folders. I ended up re-installing Tortoise, but the ghost lock was still present. From there I had to delete the folder and do a new checkout. Obviously I got really lucky that I didn't have any new changes to commit at the time. Anyhow, not great news, and if anyone has a better solution I'd love to hear it myself. Even using "Break Lock" ie unlock with the force option did not change anything.

CSS to keep element at "fixed" position on screen

The easiest way is to use position: fixed:

.element {
  position: fixed;
  bottom: 0;
  right: 0;
}

http://www.w3.org/TR/CSS21/visuren.html#choose-position

(note that position fixed is buggy / doesn't work on ios and android browsers)

how to get the attribute value of an xml node using java

try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<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"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

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

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

MessageBox.Show(
  "your message",
  "window title", 
  MessageBoxButtons.OK, 
  MessageBoxIcon.Asterisk //For Info Asterisk
  MessageBoxIcon.Exclamation //For triangle Warning 
)

Call a PHP function after onClick HTML event

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

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

I did it like this in Internet Explorer.

function getWindowRelativeOffset(parentWindow, elem) {
    var offset = {
        left : 0,
        top : 0
    };
    // relative to the target field's document
    offset.left = elem.getBoundingClientRect().left;
    offset.top = elem.getBoundingClientRect().top;
    // now we will calculate according to the current document, this current
    // document might be same as the document of target field or it may be
    // parent of the document of the target field
    var childWindow = elem.document.frames.window;
    while (childWindow != parentWindow) {
        offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
        offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
        childWindow = childWindow.parent;
    }

    return offset;
};

=================== you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus on IE only as per my focus but similar things can be done for other browsers.

How to create a numpy array of all True or all False?

ones and zeros, which create arrays full of ones and zeros respectively, take an optional dtype parameter:

>>> numpy.ones((2, 2), dtype=bool)
array([[ True,  True],
       [ True,  True]], dtype=bool)
>>> numpy.zeros((2, 2), dtype=bool)
array([[False, False],
       [False, False]], dtype=bool)

How do I show the number keyboard on an EditText in android?

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...
    android:inputType="number|phone"/> 

will show the large number pad as dialer.

How should I throw a divide by zero exception in Java without actually dividing by zero?

Do this:

if (denominator == 0) throw new ArithmeticException("denominator == 0");

ArithmeticException is the exception which is normally thrown when you divide by 0.

What does getActivity() mean?

getActivity() is used for fragment. For activity, wherever you can use this, you can replace the this in fragment in similar cases with getActivity().

NSAttributedString add text alignment

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

Linux cmd to search for a class file among jars irrespective of jar path

   locate *.jar | grep Hello.class.jar

The locate command to search the all path of the particular file and display full path of the file.

example

locate *.jar | grep classic.jar

/opt/ltsp/i386/usr/share/firefox/chrome/classic.jar

/opt/ltsp/i386/usr/share/thunderbird/chrome/classic.jar

/root/.wine/drive_c/windows/gecko/0.1.0/wine_gecko/chrome/classic.jar

/usr/lib/firefox-3.0.14/chrome/classic.jar

/usr/lib/firefox-3.5.2/chrome/classic.jar

/usr/lib/xulrunner-1.9.1.2/chrome/classic.jar

/usr/share/firefox/chrome/classic.jar

/usr/share/thunderbird/chrome/classic.jar

How can I connect to a Tor hidden service using cURL in PHP?

TL;DR: Set CURLOPT_PROXYTYPE to use CURLPROXY_SOCKS5_HOSTNAME if you have a modern PHP, the value 7 otherwise, and/or correct the CURLOPT_PROXY value.

As you correctly deduced, you cannot resolve .onion domains via the normal DNS system, because this is a reserved top-level domain specifically for use by Tor and such domains by design have no IP addresses to map to.

Using CURLPROXY_SOCKS5 will direct the cURL command to send its traffic to the proxy, but will not do the same for domain name resolution. The DNS requests, which are emitted before cURL attempts to establish the actual connection with the Onion site, will still be sent to the system's normal DNS resolver. These DNS requests will surely fail, because the system's normal DNS resolver will not know what to do with a .onion address unless it, too, is specifically forwarding such queries to Tor.

Instead of CURLPROXY_SOCKS5, you must use CURLPROXY_SOCKS5_HOSTNAME. Alternatively, you can also use CURLPROXY_SOCKS4A, but SOCKS5 is much preferred. Either of these proxy types informs cURL to perform both its DNS lookups and its actual data transfer via the proxy. This is required to successfully resolve any .onion domain.

There are also two additional errors in the code in the original question that have yet to be corrected by previous commenters. These are:

  • Missing semicolon at end of line 1.
  • The proxy address value is set to an HTTP URL, but its type is SOCKS; these are incompatible. For SOCKS proxies, the value must be an IP or domain name and port number combination without a scheme/protocol/prefix.

Here is the correct code in full, with comments to indicate the changes.

<?php
$url = 'http://jhiwjjlqpyawmpjx.onion/'; // Note the addition of a semicolon.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:9050"); // Note the address here is just `IP:port`, not an HTTP URL.
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); // Note use of `CURLPROXY_SOCKS5_HOSTNAME`.
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);

You can also omit setting CURLOPT_PROXYTYPE entirely by changing the CURLOPT_PROXY value to include the socks5h:// prefix:

// Note no trailing slash, as this is a SOCKS address, not an HTTP URL.
curl_setopt(CURLOPT_PROXY, 'socks5h://127.0.0.1:9050');

sudo: npm: command not found

The npm file should be in /usr/local/bin/npm. If it's not there, install node.js again with the package on their website. This worked in my case.

d3.select("#element") not working when code above the html element

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

How to create Select List for Country and States/province in MVC

I too liked Jordan's answer and implemented it myself. I only needed to abbreviations so in case someone else needs the same:

    public static IEnumerable<SelectListItem> GetStatesList()
    {
        IList<SelectListItem> states = new List<SelectListItem>
        {
            new SelectListItem() {Text="AL", Value="AL"},
            new SelectListItem() { Text="AK", Value="AK"},
            new SelectListItem() { Text="AZ", Value="AZ"},
            new SelectListItem() { Text="AR", Value="AR"},
            new SelectListItem() { Text="CA", Value="CA"},
            new SelectListItem() { Text="CO", Value="CO"},
            new SelectListItem() { Text="CT", Value="CT"},
            new SelectListItem() { Text="DC", Value="DC"},
            new SelectListItem() { Text="DE", Value="DE"},
            new SelectListItem() { Text="FL", Value="FL"},
            new SelectListItem() { Text="GA", Value="GA"},
            new SelectListItem() { Text="HI", Value="HI"},
            new SelectListItem() { Text="ID", Value="ID"},
            new SelectListItem() { Text="IL", Value="IL"},
            new SelectListItem() { Text="IN", Value="IN"},
            new SelectListItem() { Text="IA", Value="IA"},
            new SelectListItem() { Text="KS", Value="KS"},
            new SelectListItem() { Text="KY", Value="KY"},
            new SelectListItem() { Text="LA", Value="LA"},
            new SelectListItem() { Text="ME", Value="ME"},
            new SelectListItem() { Text="MD", Value="MD"},
            new SelectListItem() { Text="MA", Value="MA"},
            new SelectListItem() { Text="MI", Value="MI"},
            new SelectListItem() { Text="MN", Value="MN"},
            new SelectListItem() { Text="MS", Value="MS"},
            new SelectListItem() { Text="MO", Value="MO"},
            new SelectListItem() { Text="MT", Value="MT"},
            new SelectListItem() { Text="NE", Value="NE"},
            new SelectListItem() { Text="NV", Value="NV"},
            new SelectListItem() { Text="NH", Value="NH"},
            new SelectListItem() { Text="NJ", Value="NJ"},
            new SelectListItem() { Text="NM", Value="NM"},
            new SelectListItem() { Text="NY", Value="NY"},
            new SelectListItem() { Text="NC", Value="NC"},
            new SelectListItem() { Text="ND", Value="ND"},
            new SelectListItem() { Text="OH", Value="OH"},
            new SelectListItem() { Text="OK", Value="OK"},
            new SelectListItem() { Text="OR", Value="OR"},
            new SelectListItem() { Text="PA", Value="PA"},
            new SelectListItem() { Text="PR", Value="PR"},
            new SelectListItem() { Text="RI", Value="RI"},
            new SelectListItem() { Text="SC", Value="SC"},
            new SelectListItem() { Text="SD", Value="SD"},
            new SelectListItem() { Text="TN", Value="TN"},
            new SelectListItem() { Text="TX", Value="TX"},
            new SelectListItem() { Text="UT", Value="UT"},
            new SelectListItem() { Text="VT", Value="VT"},
            new SelectListItem() { Text="VA", Value="VA"},
            new SelectListItem() { Text="WA", Value="WA"},
            new SelectListItem() { Text="WV", Value="WV"},
            new SelectListItem() { Text="WI", Value="WI"},
            new SelectListItem() { Text="WY", Value="WY"}
        };
        return states;
    }

What does "Table does not support optimize, doing recreate + analyze instead" mean?

That's really an informational message.

Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).

InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.

The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:

Table does not support optimize is the InnoDB storage engine saying...

"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."

"doing recreate + analyze instead" is the InnoDB storage engine saying...

"I have decided to perform a different set of operations which will achieve an equivalent result."

Run an OLS regression with Pandas Data Frame

I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas' optional dependencies before pandas' version 0.20.0 (it was used for a few things in pandas.stats.)

>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept    14.952480
B             0.401182
C             0.000352
dtype: float64
>>> print(result.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.579
Model:                            OLS   Adj. R-squared:                  0.158
Method:                 Least Squares   F-statistic:                     1.375
Date:                Thu, 14 Nov 2013   Prob (F-statistic):              0.421
Time:                        20:04:30   Log-Likelihood:                -18.178
No. Observations:                   5   AIC:                             42.36
Df Residuals:                       2   BIC:                             41.19
Df Model:                           2                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept     14.9525     17.764      0.842      0.489       -61.481    91.386
B              0.4012      0.650      0.617      0.600        -2.394     3.197
C              0.0004      0.001      0.650      0.583        -0.002     0.003
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   1.061
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.498
Skew:                          -0.123   Prob(JB):                        0.780
Kurtosis:                       1.474   Cond. No.                     5.21e+04
==============================================================================

Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

Free c# QR-Code generator

ZXing is an open source project that can detect and parse a number of different barcodes. It can also generate QR-codes. (Only QR-codes, though).

There are a number of variants for different languages: ActionScript, Android (java), C++, C#, IPhone (Obj C), Java ME, Java SE, JRuby, JSP. Support for generating QR-codes comes with some of those: ActionScript, Android, C# and the Java variants.

How to exit if a command failed?

Using exit directly may be tricky as the script may be sourced from other places (e.g. from terminal). I prefer instead using subshell with set -e (plus errors should go into cerr, not cout) :

set -e
ERRCODE=0
my_command || ERRCODE=$?
test $ERRCODE == 0 ||
    (>&2 echo "My command failed ($ERRCODE)"; exit $ERRCODE)

Cannot send a content-body with this verb-type

Don't get the request stream, quite simply. GET requests don't usually have bodies (even though it's not technically prohibited by HTTP) and WebRequest doesn't support it - but that's what calling GetRequestStream is for, providing body data for the request.

Given that you're trying to read from the stream, it looks to me like you actually want to get the response and read the response stream from that:

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

What do the different readystates in XMLHttpRequest mean, and how can I use them?

kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,

so here is the original documentation quoted to rightly understand what readystate represents :

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)
The object has been constructed.

OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)
The response entity body is being received.

DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

Please Read here : W3C Explaination Of ReadyState

equals vs Arrays.equals in Java

It's an infamous problem: .equals() for arrays is badly broken, just don't use it, ever.

That said, it's not "broken" as in "someone has done it in a really wrong way" — it's just doing what's defined and not what's usually expected. So for purists: it's perfectly fine, and that also means, don't use it, ever.

Now the expected behaviour for equals is to compare data. The default behaviour is to compare the identity, as Object does not have any data (for purists: yes it has, but it's not the point); assumption is, if you need equals in subclasses, you'll implement it. In arrays, there's no implementation for you, so you're not supposed to use it.

So the difference is, Arrays.equals(array1, array2) works as you would expect (i.e. compares content), array1.equals(array2) falls back to Object.equals implementation, which in turn compares identity, and thus better replaced by == (for purists: yes I know about null).

Problem is, even Arrays.equals(array1, array2) will bite you hard if elements of array do not implement equals properly. It's a very naive statement, I know, but there's a very important less-than-obvious case: consider a 2D array.

2D array in Java is an array of arrays, and arrays' equals is broken (or useless if you prefer), so Arrays.equals(array1, array2) will not work as you expect on 2D arrays.

Hope that helps.

Why am I getting the message, "fatal: This operation must be run in a work tree?"

Also, you are probably inside the .git subfolder, move up one folder to your project root.

Viewing full output of PS command

Evidence for truncation mentioned by others, (a personal example)

foo=$(ps -p 689 -o command); echo "$foo"

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtime/kernel-5732db1a-d484-4a58-9d67-de6ef5ac721b.json

That ^^ captures that long output in a variable As opposed to

ps -p 689 -o command

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtim

Since I was trying this from a Docker jupyter notebook, I needed to run this with the bang of course ..

!foo=$(ps -p 689 -o command); echo "$foo"

Surprisingly jupyter notebooks let you execute even that! But glad to help find the offending notebook taking up all my memory =D

Java: unparseable date exception

I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.

This from the accepted answer helped me solve this problem:

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern

The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema

I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.

jQuery: count number of rows in a table

Here's my take on it:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

USAGE:

var rowCount = $('#productTypesTable').rowCount();

How to use log4net in Asp.net core 2.0

Still looking for a solution? I got mine from this link .

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet.
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.

how to store Image as blob in Sqlite & how to retrieve it?

you may also want to encode and decode to/from base64

    function uncompress(str:String):ByteArray {
            import mx.utils.Base64Decoder;
            var dec:Base64Decoder = new Base64Decoder();
            dec.decode(str);
            var newByteArr:ByteArray=dec.toByteArray();        
            return newByteArr;
        }


    // Compress a ByteArray into a Base64 String.
    function compress(bytes:ByteArray):String { 
        import mx.utils.Base64Decoder; //Transform String in a ByteArray.
        import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
        var enc:Base64Encoder = new Base64Encoder();    
        enc.encodeBytes(bytes);
        return enc.drain().split("\n").join("");
    }

Resizable table columns with jQuery

I have tried several solutions today, the one working best for me is Jo-Geek/jQuery-ResizableColumns. Is is very simple, yet it handles tables placed in flex containers, which many of the other ones fail with.

<table class="resizable">
</table>
$('table.resizable').resizableColumns();

_x000D_
_x000D_
$(function() {_x000D_
  $('table.resizable').resizableColumns();_x000D_
})
_x000D_
body {_x000D_
  margin: 0px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  width: 100%;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>_x000D_
<table class="resizable" border="true">_x000D_
  <thead>_x000D_
  <tr>_x000D_
    <th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

In C - check if a char exists in a char array

use strchr function when dealing with C strings.

const char * strchr ( const char * str, int character );

Here is an example of what you want to do.

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char invalids[] = ".@<>#";
  char * pch;
  pch=strchr(invalids,'s');//is s an invalid character?
  if (pch!=NULL)
  {
    printf ("Invalid character");
  }
  else 
  {
     printf("Valid character");
  } 
  return 0;
}

Use memchr when dealing with memory blocks (as not null terminated arrays)

const void * memchr ( const void * ptr, int value, size_t num );

/* memchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char * pch;
  char invalids[] = "@<>#";
  pch = (char*) memchr (invalids, 'p', strlen(invalids));
  if (pch!=NULL)
    printf (p is an invalid character);
  else
    printf ("p valid character.\n");
  return 0;
}

http://www.cplusplus.com/reference/clibrary/cstring/memchr/

http://www.cplusplus.com/reference/clibrary/cstring/strchr/

JavaScript string newline character?

I've just tested a few browsers using this silly bit of JavaScript:

_x000D_
_x000D_
function log_newline(msg, test_value) {_x000D_
  if (!test_value) { _x000D_
    test_value = document.getElementById('test').value;_x000D_
  }_x000D_
  console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')_x000D_
              + ' ' + (test_value.match(/\n/) ? 'LF' : ''));_x000D_
}_x000D_
_x000D_
log_newline('HTML source');_x000D_
log_newline('JS string', "foo\nbar");_x000D_
log_newline('JS template literal', `bar_x000D_
baz`);
_x000D_
<textarea id="test" name="test">_x000D_
_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

IE8 and Opera 9 on Windows use \r\n. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n. They can all handle \n just fine when setting the value, though IE and Opera will convert that back to \r\n again internally. There's a SitePoint article with some more details called Line endings in Javascript.

Note also that this is independent of the actual line endings in the HTML file itself (both \n and \r\n give the same results).

When submitting a form, all browsers canonicalize newlines to %0D%0A in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)

I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:

lines = foo.value.split(/\r\n|\r|\n/g);

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

ORA-00979 not a group by expression

Include in the GROUP BY clause all SELECT expressions that are not group function arguments.

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)

How to Iterate over a Set/HashSet without an Iterator?

There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
  System.out.println(e.nextElement());
}

Method 2

for (String movie : movies) {
  System.out.println(movie);
}

Method 3

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
  System.out.println(movieArray[i]);
}

Method 4

// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
  System.out.println(movie);
});

Method 5

// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));

Method 6

// Supported in Java 8 and above
movies.stream().forEach(System.out::println);

This is the HashSet which I used for my examples:

Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

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

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Render is

def render(request, *args, **kwargs):
    """ Simple wrapper for render_to_response. """
    kwargs['context_instance'] = RequestContext(request)
    return render_to_response(*args, **kwargs)

So there is really no difference between render_to_response except it wraps your context making the template pre-processors work.

Direct to template is a generic view.

There is really no sense in using it here because there is overhead over render_to_response in the form of view function.

Command-line svn for Windows?

cygwin is another option. It has a port of svn.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

I got this error when I tried to update an object with an id that did not exist in the database. The reason for my mistake was that I had manually assigned a property with the name 'id' to the client side JSON-representation of the object and then when deserializing the object on the server side this 'id' property would overwrite the instance variable (also called 'id') that Hibernate was supposed to generate. So be careful of naming collisions if you are using Hibernate to generate identifiers.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

Delete dynamically-generated table row using jQuery

  $(document.body).on('click', 'buttontrash', function () { // <-- changes
    alert("aa");
   /$(this).closest('tr').remove();
    return false;
});

This works perfectly, take not of document.body

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:

 (?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

Aliases in Windows command prompt

Expanding on roryhewitt answer.

An advantage to using .cmd files over DOSKEY is that these "aliases" are then available in other shells such as PowerShell or WSL (Windows subsystem for Linux).

The only gotcha with using these commands in bash is that it may take a bit more setup since you might need to do some path manipulation before calling your "alias".

eg I have vs.cmd which is my "alias" for editing a file in Visual Studio

@echo off
if [%1]==[] goto nofiles
start "" "c:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" /edit %1
goto end
:nofiles
start "" "C:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" "[PATH TO MY NORMAL SLN]"
:end

Which fires up VS (in this case VS2012 - but adjust to taste) using my "normal" project with no file given but when given a file will attempt to attach to a running VS opening that file "within that project" rather than starting a new instance of VS.

For using this from bash I then add an extra level of indirection since "vs Myfile" wouldn't always work

alias vs='/usr/bin/run_visual_studio.sh'

Which adjusts the paths before calling the vs.cmd

#!/bin/bash
cmd.exe /C 'c:\Windows\System32\vs.cmd' "`wslpath.sh -w -r $1`"

So this way I can just do

vs SomeFile.txt

In either a command prompt, Power Shell or bash and it opens in my running Visual Studio for editing (which just saves my poor brain from having to deal with VI commands or some such when I've just been editing in VS for hours).

Using underscores in Java variables and method names

The reason people do it (in my experience) is to differentiate between member variables and function parameters. In Java you can have a class like this:

public class TestClass {
  int var1;

  public void func1(int var1) {
     System.out.println("Which one is it?: " + var1);
  }
}

If you made the member variable _var1 or m_var1, you wouldn't have the ambiguity in the function.

So it's a style, and I wouldn't call it bad.

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

Java Web Service client basic authentication

It turned out that there's a simple, standard way to achieve what I wanted:

import java.net.Authenticator;
import java.net.PasswordAuthentication;

Authenticator myAuth = new Authenticator() 
{
    @Override
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication("german", "german".toCharArray());
    }
};

Authenticator.setDefault(myAuth);

No custom "sun" classes or external dependencies, and no manually encode anything.

I'm aware that BASIC security is not, well, secure, but we are also using HTTPS.

How do I install the yaml package for Python?

Update: Nowadays installing is done with pip, but libyaml is still required to build the C extension (on mac):

brew install libyaml
python -m pip install pyyaml

Outdated method:

For MacOSX (mavericks), the following seems to work:

brew install libyaml
sudo python -m easy_install pyyaml

How to add elements to an empty array in PHP?

Based on my experience, solution which is fine(the best) when keys are not important:

$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;

How can I open a website in my web browser using Python?

If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website. e.g.

 import webbrowser

 webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)

Can't clone a github repo on Linux via HTTPS

Make sure you have git 1.7.10 or later, it now prompts for user/password correctly. (You can download the latest version here)

How do I remove the first characters of a specific column in a table?

Stuff(someColumn, 1, 4, '')

This says, starting with the first 1 character position, replace 4 characters with nothing ''

Separation of business logic and data access in django

An old question, but I'd like to offer my solution anyway. It's based on acceptance that model objects too require some additional functionality while it's awkward to place it within the models.py. Heavy business logic may be written separately depending on personal taste, but I at least like the model to do everything related to itself. This solution also supports those who like to have all the logic placed within models themselves.

As such, I devised a hack that allows me to separate logic from model definitions and still get all the hinting from my IDE.

The advantages should be obvious, but this lists a few that I have observed:

  • DB definitions remain just that - no logic "garbage" attached
  • Model-related logic is all placed neatly in one place
  • All the services (forms, REST, views) have a single access point to logic
  • Best of all: I did not have to rewrite any code once I realised that my models.py became too cluttered and had to separate the logic away. The separation is smooth and iterative: I could do a function at a time or entire class or the entire models.py.

I have been using this with Python 3.4 and greater and Django 1.8 and greater.

app/models.py

....
from app.logic.user import UserLogic

class User(models.Model, UserLogic):
    field1 = models.AnyField(....)
    ... field definitions ...

app/logic/user.py

if False:
    # This allows the IDE to know about the User model and its member fields
    from main.models import User

class UserLogic(object):
    def logic_function(self: 'User'):
        ... code with hinting working normally ...

The only thing I can't figure out is how to make my IDE (PyCharm in this case) recognise that UserLogic is actually User model. But since this is obviously a hack, I'm quite happy to accept the little nuisance of always specifying type for self parameter.

jQuery How do you get an image to fade in on load?

The key is to use $(window).load(function(){} so we know the image is loaded. Hide the image via the css function then fade it in using fadeIn:

$(function() {

  $(window).load(function(){
    $('#logo').css({visibility: 'visible', opacity: 0}).fadeIn(1000);
  });

});

Idea from: http://www.getpeel.com/

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

What are the differences between a HashMap and a Hashtable in Java?

Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.

Java Collection Matrix

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

I just opened the dump.sql file in Notepad++ and hit CTRL+H to find and replace the string "utf8mb4_0900_ai_ci" and replaced it with "utf8mb4_general_ci". Source link https://www.freakyjolly.com/resolved-when-i-faced-1273-unknown-collation-utf8mb4_0900_ai_ci-error/

How do I calculate a trendline for a graph?

OK, here's my best pseudo math:

The equation for your line is:

Y = a + bX

Where:

b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)

a = sum(y)/n - b(sum(x)/n)

Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)

... and now with added Sigma

b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)

a = (Σy)/n - b((Σx)/n)

Where Σ(xy) is the sum of all x*y etc. and n is the number of points

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

How to execute 16-bit installer on 64-bit Win7?

16 bit installer will not work on windows 7 it's no longer supported by win 7 the most recent supported version of windows that can run 16 bit installer is vista 32-bit even vista 64-bit doesn't support 16-bit installer.... reference http://support.microsoft.com/kb/946765