Programs & Examples On #Asciidoc

AsciiDoc is a lightweight markup format similar to Markdown, but it was designed for technical writing with programmatic capabilities as well as semantic structure.

Homebrew: Could not symlink, /usr/local/bin is not writable

If you already have a directory in /usr/local for the package you're installing, you can try deleting this directory.

In my case I had previously installed the package I was trying to install without using brew, and had then uninstalled it. There was a directory /usr/local/<my_package>/ left over from that previous install. I deleted this folder (sudo rm -rf /usr/local/<my_package>/) and after that the brew link step was successful.

Cannot push to GitHub - keeps saying need merge

This can cause the remote repository to lose commits; use it with care.

If you do not wish to merge the remote branch into your local branch (see differences with git diff), and want to do a force push, use the push command with -f

git push -f origin <branch>

where origin is the name of your remote repo.

Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. This can cause the remote repository to lose commits; use it with care.

No provider for HttpClient

Just import the HttpModule and the HttpClientModule only:

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

No need for the HttpClient.

Android Studio update -Error:Could not run build action using Gradle distribution

I had same issue. I have tried many things but nothing worked Until I try following:

  1. Close Android Studio
  2. Delete any directory matching gradle-[version]-all within C:\Users\<username>\.gradle\wrapper\dists\. If you encounter a "File in use" error (or similar), terminate any running Java executables.
  3. Open Android Studio as Administrator.
  4. Try to sync project files.
  5. If the above does not work, try restarting your computer and/or delete the project's .gradle directory.
  6. Open the problem project and trigger a Gradle sync.

jQuery counting elements by class - what is the best way to implement this?

Getting a count of the number of elements that refer to the same class is as simple as this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>

How do I hide certain files from the sidebar in Visual Studio Code?

You can configure patterns to hide files and folders from the explorer and searches.

  1. Open VS User Settings (Main menu: File > Preferences > Settings). This will open the setting screen.
  2. Search for files:exclude in the search at the top.
  3. Configure the User Setting with new glob patterns as needed. In this case add this pattern node_modules/ then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic.

When you are done it should look something like this: enter image description here

If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:

"files.exclude": {
    "node_modules/": true
}

To hide all files that start with ._ such as ._.DS_Store files found on OSX:

"files.exclude": {
    "**/._*": true
}

You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings). Workspace settings will create a .vscode/settings.json file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.

Check if a string is a valid Windows directory (folder) path

I haven't had any problems with this code:

private bool IsValidPath(string path, bool exactPath = true)
{
    bool isValid = true;

    try
    {
        string fullPath = Path.GetFullPath(path);

        if (exactPath)
        {
            string root = Path.GetPathRoot(path);
            isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
        }
        else
        {
            isValid = Path.IsPathRooted(path);
        }
    }
    catch(Exception ex)
    {
        isValid = false;
    }

    return isValid;
}

For example these would return false:

IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", false);

And these would return true:

IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", false);

jQuery counter to count up to a target number

You can use the jQuery animate function

// Enter num from and to
$({countNum: 99}).animate({countNum: 1000}, {
  duration: 8000,
  easing:'linear',
  step: function() {
    // What todo on every count
    console.log(Math.floor(this.countNum));
  },
  complete: function() {
    console.log('finished');
  }
});

http://jsbin.com/upazas/958/

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

How to convert byte[] to InputStream?

ByteArrayInputStream extends InputStream:

InputStream myInputStream = new ByteArrayInputStream(myBytes); 

How to increase editor font size?

I have the latest version of Android Studio installed (3.6.1).

I navigated to: File->Settings->Editor->Font. The dialog displays a warning message (yellow triangle) indicating that the Font is defined in the color scheme.

(Editing the Font here had no effect.)

Editor Font

I clicked on the dialog's warning message link.

This navigated to: File->Settings->Editor->Color Scheme->Color Scheme Font.

(Now I could edit the Font for my current scheme.)

Editor Color Scheme Color Scheme Font

How to open up a form from another form in VB.NET?

You can also use showdialog

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                      Handles Button3.Click

     dim mydialogbox as new aboutbox1
     aboutbox1.showdialog()

End Sub

How do you query for "is not null" in Mongo?

db.<collectionName>.find({"IMAGE URL":{"$exists":"true"}, "IMAGE URL": {$ne: null}})

UIScrollView Scrollable Content Size Ambiguity

I made a video on youTube
Scroll StackViews using only Storyboard in Xcode

I think 2 kind of scenarios can appear here.

The view inside the scrollView -

  1. does not have any intrinsic content Size (e.g UIView)
  2. does have its own intrinsic content Size (e.g UIStackView)

For a vertically scrollable view in both cases you need to add these constraints:

  1. 4 constraints from top, left, bottom and right.

  2. Equal width to scrollview (to stop scrolling horizontally)

You don't need any other constraints for views which have his own intrinsic content height.

enter image description here


For views which do not have any intrinsic content height, you need to add a height constraint. The view will scroll only if the height constraint is more than the height of the scrollView.

enter image description here

Execute command on all files in a directory

Maxdepth

I found it works nicely with Jim Lewis's answer just add a bit like this:

$ export DIR=/path/dir && cd $DIR && chmod -R +x *
$ find . -maxdepth 1 -type f -name '*.sh' -exec {} \; > results.out

Sort Order

If you want to execute in sort order, modify it like this:

$ export DIR=/path/dir && cd $DIR && chmod -R +x *
find . -maxdepth 2 -type f -name '*.sh' | sort | bash > results.out

Just for an example, this will execute with following order:

bash: 1: ./assets/main.sh
bash: 2: ./builder/clean.sh
bash: 3: ./builder/concept/compose.sh
bash: 4: ./builder/concept/market.sh
bash: 5: ./builder/concept/services.sh
bash: 6: ./builder/curl.sh
bash: 7: ./builder/identity.sh
bash: 8: ./concept/compose.sh
bash: 9: ./concept/market.sh
bash: 10: ./concept/services.sh
bash: 11: ./product/compose.sh
bash: 12: ./product/market.sh
bash: 13: ./product/services.sh
bash: 14: ./xferlog.sh

Unlimited Depth

If you want to execute in unlimited depth by certain condition, you can use this:

export DIR=/path/dir && cd $DIR && chmod -R +x *
find . -type f -name '*.sh' | sort | bash > results.out

then put on top of each files in the child directories like this:

#!/bin/bash
[[ "$(dirname `pwd`)" == $DIR ]] && echo "Executing `realpath $0`.." || return

and somewhere in the body of parent file:

if <a condition is matched>
then
    #execute child files
    export DIR=`pwd`
fi

Block direct access to a file over http but allow php script access

Are the files on the same server as the PHP script? If so, just keep the files out of the web root and make sure your PHP script has read permissions for wherever they're stored.

How to convert buffered image to image and vice-versa?

You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.

EDIT:

try {
    // Retrieve Image
    BufferedImage buffer = ImageIO.read(new File("old.png"));;
    // Here you can rotate your image as you want (making your magic)
    File outputfile = new File("saved.png");
    ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}

jquery how to get the page's current screen top position?

Use this to get the page scroll position.

var screenTop = $(document).scrollTop();

$('#content').css('top', screenTop);

How to get current class name including package name in Java?

There is a class, Class, that can do this:

Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass();          // if you want to use the current class

System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());

If c represented the class MyClass in the package mypackage, the above code would print:

Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass

You can take this information and modify it for whatever you need, or go check the API for more information.

MySQL Trigger - Storing a SELECT in a variable

You can declare local variables in MySQL triggers, with the DECLARE syntax.

Here's an example:

DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
  i SERIAL PRIMARY KEY
);

DELIMITER //
DROP TRIGGER IF EXISTS bar //

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = NEW.i;
  SET @a = x; -- set user variable outside trigger
END//

DELIMITER ;

SET @a = 0;

SELECT @a; -- returns 0

INSERT INTO foo () VALUES ();

SELECT @a; -- returns 1, the value it got during the trigger

When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT age FROM users WHERE name = 'Bill'); 
  -- ERROR 1242 if more than one row with 'Bill'
END//

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
  -- OK even when more than one row with 'Bill'
END//

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

SQL : BETWEEN vs <= and >=

I have a slight preference for BETWEEN because it makes it instantly clear to the reader that you are checking one field for a range. This is especially true if you have similar field names in your table.

If, say, our table has both a transactiondate and a transitiondate, if I read

transactiondate between ...

I know immediately that both ends of the test are against this one field.

If I read

transactiondate>='2009-04-17' and transactiondate<='2009-04-22'

I have to take an extra moment to make sure the two fields are the same.

Also, as a query gets edited over time, a sloppy programmer might separate the two fields. I've seen plenty of queries that say something like

where transactiondate>='2009-04-17'
  and salestype='A'
  and customernumber=customer.idnumber
  and transactiondate<='2009-04-22'

If they try this with a BETWEEN, of course, it will be a syntax error and promptly fixed.

How do I check if a number is a palindrome?

Push each individual digit onto a stack, then pop them off. If it's the same forwards and back, it's a palindrome.

How to stop a PowerShell script on the first error?

I came here looking for the same thing. $ErrorActionPreference="Stop" kills my shell immediately when I'd rather see the error message (pause) before it terminates. Falling back on my batch sensibilities:

IF %ERRORLEVEL% NEQ 0 pause & GOTO EOF

I found that this works pretty much the same for my particular ps1 script:

Import-PSSession $Session
If ($? -ne "True") {Pause; Exit}

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

How to emulate GPS location in the Android Emulator?

The following solution worked for me - open command line and write:

adb emu geo fix [longtitude] [latitude]

Hibernate Query By Example and Projections

Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).

getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();

I've never used the alaistToBean, but I just read about it. You could also just loop over the results..

List<Object> rows = criteria.list();
for(Object r: rows){
  Object[] row = (Object[]) r;
  Type t = ((<Type>) row[0]);
}

If you have to you can manually populate User yourself that way.

Its sort of hard to look into the issue without some more information to diagnose the issue.

How do I vertically center an H1 in a div?

HTML

<div id='sample'>
<span class='vertical'>Test Message</span>
</div>

CSS

    #sample 
    {
        height:100px;
         width:100%;
        background-color:#003366;
        display:table;
        text-align: center;

    }
    .vertical 
    {
           color:white;
         display:table-cell;
        vertical-align:middle;
}

Fiddle : Demo

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

How to trim a file extension from a String in JavaScript?

Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-

path.replace(path.substr(path.lastIndexOf('.')), '')

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

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

        }

    }

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Why use double indirection? or Why use pointers to pointers?

For example, you might want to make sure that when you free the memory of something you set the pointer to null afterwards.

void safeFree(void** memory) {
    if (*memory) {
        free(*memory);
        *memory = NULL;
    }
}

When you call this function you'd call it with the address of a pointer

void* myMemory = someCrazyFunctionThatAllocatesMemory();
safeFree(&myMemory);

Now myMemory is set to NULL and any attempt to reuse it will be very obviously wrong.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

I had the same issue. But in my case it was due to my branch's name. The branch's name automatically set in my GitHub repo as main instead of master.

git pull origin master (did not work).

I confirmed in GitHub if the name of the branch was actually master and found the the actual name was main. so the commands below worked for me. git pull origin main

Python: Assign Value if None Exists

var1 = var1 or 4

The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue.

Multiline strings in VB.NET

Available in Visual Basic 14 as part of Visual Studio 2015 https://msdn.microsoft.com/en-us/magazine/dn890368.aspx

But not yet supported by R#. The good news is they will be supported soon! Please vote on Youtrack to notify JetBrains you need them also.

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

printing a two dimensional array in python

print(mat.__str__())

where mat is variable refering to your matrix object

Meaning of @classmethod and @staticmethod for beginner?

Rostyslav Dzinko's answer is very appropriate. I thought I could highlight one other reason you should choose @classmethod over @staticmethod when you are creating an additional constructor.

In the example above, Rostyslav used the @classmethod from_string as a Factory to create Date objects from otherwise unacceptable parameters. The same can be done with @staticmethod as is shown in the code below:

class Date:
  def __init__(self, month, day, year):
    self.month = month
    self.day   = day
    self.year  = year


  def display(self):
    return "{0}-{1}-{2}".format(self.month, self.day, self.year)


  @staticmethod
  def millenium(month, day):
    return Date(month, day, 2000)

new_year = Date(1, 1, 2013)               # Creates a new Date object
millenium_new_year = Date.millenium(1, 1) # also creates a Date object. 

# Proof:
new_year.display()           # "1-1-2013"
millenium_new_year.display() # "1-1-2000"

isinstance(new_year, Date) # True
isinstance(millenium_new_year, Date) # True

Thus both new_year and millenium_new_year are instances of the Date class.

But, if you observe closely, the Factory process is hard-coded to create Date objects no matter what. What this means is that even if the Date class is subclassed, the subclasses will still create plain Date objects (without any properties of the subclass). See that in the example below:

class DateTime(Date):
  def display(self):
      return "{0}-{1}-{2} - 00:00:00PM".format(self.month, self.day, self.year)


datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # False

datetime1.display() # returns "10-10-1990 - 00:00:00PM"
datetime2.display() # returns "10-10-2000" because it's not a DateTime object but a Date object. Check the implementation of the millenium method on the Date class for more details.

datetime2 is not an instance of DateTime? WTF? Well, that's because of the @staticmethod decorator used.

In most cases, this is undesired. If what you want is a Factory method that is aware of the class that called it, then @classmethod is what you need.

Rewriting Date.millenium as (that's the only part of the above code that changes):

@classmethod
def millenium(cls, month, day):
    return cls(month, day, 2000)

ensures that the class is not hard-coded but rather learnt. cls can be any subclass. The resulting object will rightly be an instance of cls.
Let's test that out:

datetime1 = DateTime(10, 10, 1990)
datetime2 = DateTime.millenium(10, 10)

isinstance(datetime1, DateTime) # True
isinstance(datetime2, DateTime) # True


datetime1.display() # "10-10-1990 - 00:00:00PM"
datetime2.display() # "10-10-2000 - 00:00:00PM"

The reason is, as you know by now, that @classmethod was used instead of @staticmethod

Javascript: how to validate dates in format MM-DD-YYYY?

You can simplify it somewhat by changing the first two lines of the function to this:

var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);

Or, just change the parameter to the RegExp constructor to be

^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$

Backup a single table with its data from a database in sql server 2008

To get a copy in a file on the local file-system, this rickety utility from the Windows start button menu worked: "C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe"

find files by extension, *.html under a folder in nodejs

I just noticed, you are using sync fs methods, that might block you application, here is a promise-based async way using async and q, you can execute it with START=/myfolder FILTER=".jpg" node myfile.js, assuming you put the following code in a file called myfile.js:

Q = require("q")
async = require("async")
path = require("path")
fs = require("fs")

function findFiles(startPath, filter, files){
    var deferred;
    deferred = Q.defer(); //main deferred

    //read directory
    Q.nfcall(fs.readdir, startPath).then(function(list) {
        var ideferred = Q.defer(); //inner deferred for resolve of async each
        //async crawling through dir
        async.each(list, function(item, done) {

            //stat current item in dirlist
            return Q.nfcall(fs.stat, path.join(startPath, item))
                .then(function(stat) {
                    //check if item is a directory
                    if (stat.isDirectory()) {
                        //recursive!! find files in subdirectory
                        return findFiles(path.join(startPath, item), filter, files)
                            .catch(function(error){
                                console.log("could not read path: " + error.toString());
                            })
                            .finally(function() {
                                //resolve async job after promise of subprocess of finding files has been resolved
                                return done();
                             });
                    //check if item is a file, that matches the filter and add it to files array
                    } else if (item.indexOf(filter) >= 0) {
                        files.push(path.join(startPath, item));
                        return done();
                    //file is no directory and does not match the filefilter -> don't do anything
                    } else {
                        return done();
                    }
                })
                .catch(function(error){
                    ideferred.reject("Could not stat: " + error.toString());
                });
        }, function() {
            return ideferred.resolve(); //async each has finished, so resolve inner deferred
        });
        return ideferred.promise;
    }).then(function() {
        //here you could do anything with the files of this recursion step (otherwise you would only need ONE deferred)
        return deferred.resolve(files); //resolve main deferred
    }).catch(function(error) {
        deferred.reject("Could not read dir: " + error.toString());
        return
    });
    return deferred.promise;
}


findFiles(process.env.START, process.env.FILTER, [])
    .then(function(files){
        console.log(files);
    })
    .catch(function(error){
        console.log("Problem finding files: " + error);
})

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

How can I declare a two dimensional string array?

I assume you're looking for this:

        string[,] Tablero = new string[3,3];

The syntax for a jagged array is:

        string[][] Tablero = new string[3][];
        for (int ix = 0; ix < 3; ++ix) {
            Tablero[ix] = new string[3];
        }

Creating virtual directories in IIS express

@Be.St.'s aprroach is true, but incomplete. I'm just copying his explanation with correcting the incorrect part.

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
   <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Instead of adding a new application block, you should just add a new virtualDirectory element to the application parent element.

Edit - Visual Studio 2015

If you're looking for the applicationHost.config file and you're using VS2015 you'll find it in:

[solution_directory]/.vs/config/applicationHost.config

How to capture the android device screen content?

For newer Android platforms, one can execute a system utility screencap in /system/bin to get the screenshot without root permission. You can try /system/bin/screencap -h to see how to use it under adb or any shell.

By the way, I think this method is only good for single snapshot. If we want to capture multiple frames for screen play, it will be too slow. I don't know if there exists any other approach for a faster screen capture.

How to convert a string to utf-8 in Python

If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:

stringnamehere.decode('utf-8', 'ignore')

How to have Android Service communicate with Activity

You may also use LiveData that works like an EventBus.

class MyService : LifecycleService() {
    companion object {
        val BUS = MutableLiveData<Any>()
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        val testItem : Object

        // expose your data
        if (BUS.hasActiveObservers()) {
            BUS.postValue(testItem)
        }

        return START_NOT_STICKY
    }
}

Then add an observer from your Activity.

MyService.BUS.observe(this, Observer {
    it?.let {
        // Do what you need to do here
    }
})

You can read more from this blog.

Android button font size

You define these attributes in xml as you would anything else, for example:

<Button android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/next"
            android:background="@drawable/mybutton_background"
            android:textSize="10sp" /> <!-- Use SP(Scale Independent Pixel) -->

You can find the allowed attributes in the api.

Or, if you want this to apply to all buttons in your application, create a style. See the Styles and Themes development documentation.

Populating Spring @Value during Unit Test

@ExtendWith(SpringExtension.class)    // @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class)

May that could help. The key is ConfigDataApplicationContextInitializer get all props datas

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

How to put img inline with text

Images have display: inline by default.
You might want to put the image inside the paragraph.
<p><img /></p>

Apply style to only first level of td tags

how about using the CSS :first-child pseudo-class:

.MyClass td:first-child { border: solid 1px red; }

Java: How to convert String[] to List or Set

Collections.addAll provides the shortest (one-line) receipt

Having

String[] array = {"foo", "bar", "baz"}; 
Set<String> set = new HashSet<>();

You can do as below

Collections.addAll(set, array); 

Why is this HTTP request not working on AWS Lambda?

Of course, I was misunderstanding the problem. As AWS themselves put it:

For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling context.done() in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.

I was calling context.done way before any callbacks for the request fired, causing the termination of my function ahead of time.

The working code is this:

var http = require('http');

exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url);
}

Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.

function(event, context, callback)

Although you will still find the succeed, done and fail on the context parameter, AWS suggest to use the callback function instead or null is returned by default.

callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok

Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

How to create full path with node's fs.mkdirSync?

An asynchronous way to create directories recursively:

import fs from 'fs'

const mkdirRecursive = function(path, callback) {
  let controlledPaths = []
  let paths = path.split(
    '/' // Put each path in an array
  ).filter(
    p => p != '.' // Skip root path indicator (.)
  ).reduce((memo, item) => {
    // Previous item prepended to each item so we preserve realpaths
    const prevItem = memo.length > 0 ? memo.join('/').replace(/\.\//g, '')+'/' : ''
    controlledPaths.push('./'+prevItem+item)
    return [...memo, './'+prevItem+item]
  }, []).map(dir => {
    fs.mkdir(dir, err => {
      if (err && err.code != 'EEXIST') throw err
      // Delete created directory (or skipped) from controlledPath
      controlledPaths.splice(controlledPaths.indexOf(dir), 1)
      if (controlledPaths.length === 0) {
        return callback()
      }
    })
  })
}

// Usage
mkdirRecursive('./photos/recent', () => {
  console.log('Directories created succesfully!')
})

How do I create a file and write to it?

It's worth a try for Java 7+:

 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());

It looks promising...

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

Only get hash value using md5sum (without filename)

md5="$(md5sum "${my_iso_file}")"
md5="${md5%% *}" # remove the first space and everything after it
echo "${md5}"

How to generate random positive and negative numbers in Java

You random on (0, 32767+32768) then subtract by 32768

Mask for an Input to allow phone numbers?

Angular 4+

I've created a generic directive, able to receive any mask and also able to define the mask dynamically based on the value:

mask.directive.ts:

import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { NgControl } from '@angular/forms';

import { MaskGenerator } from '../interfaces/mask-generator.interface';

@Directive({
    selector: '[spMask]' 
})
export class MaskDirective {

    private static readonly ALPHA = 'A';
    private static readonly NUMERIC = '9';
    private static readonly ALPHANUMERIC = '?';
    private static readonly REGEX_MAP = new Map([
        [MaskDirective.ALPHA, /\w/],
        [MaskDirective.NUMERIC, /\d/],
        [MaskDirective.ALPHANUMERIC, /\w|\d/],
    ]);

    private value: string = null;
    private displayValue: string = null;

    @Input('spMask') 
    public maskGenerator: MaskGenerator;

    @Input('spKeepMask') 
    public keepMask: boolean;

    @Input('spMaskValue') 
    public set maskValue(value: string) {
        if (value !== this.value) {
            this.value = value;
            this.defineValue();
        }
    };

    @Output('spMaskValueChange') 
    public changeEmitter = new EventEmitter<string>();

    @HostListener('input', ['$event'])
    public onInput(event: { target: { value?: string }}): void {
        let target = event.target;
        let value = target.value;
        this.onValueChange(value);
    }

    constructor(private ngControl: NgControl) { }

    private updateValue(value: string) {
        this.value = value;
        this.changeEmitter.emit(value);
        MaskDirective.delay().then(
            () => this.ngControl.control.updateValueAndValidity()
        );
    }

    private defineValue() {
        let value: string = this.value;
        let displayValue: string = null;

        if (this.maskGenerator) {
            let mask = this.maskGenerator.generateMask(value);

            if (value != null) {
                displayValue = MaskDirective.mask(value, mask);
                value = MaskDirective.processValue(displayValue, mask, this.keepMask);
            }   
        } else {
            displayValue = this.value;
        }

        MaskDirective.delay().then(() => {
            if (this.displayValue !== displayValue) {
                this.displayValue = displayValue;
                this.ngControl.control.setValue(displayValue);
                return MaskDirective.delay();
            }
        }).then(() => {
            if (value != this.value) {
                return this.updateValue(value);
            }
        });
    }

    private onValueChange(newValue: string) {
        if (newValue !== this.displayValue) {
            let displayValue = newValue;
            let value = newValue;

            if ((newValue == null) || (newValue.trim() === '')) {
                value = null;
            } else if (this.maskGenerator) {
                let mask = this.maskGenerator.generateMask(newValue);
                displayValue = MaskDirective.mask(newValue, mask);
                value = MaskDirective.processValue(displayValue, mask, this.keepMask);
            }

            this.displayValue = displayValue;

            if (newValue !== displayValue) {
                this.ngControl.control.setValue(displayValue);
            }

            if (value !== this.value) {
                this.updateValue(value);
            }
        }
    }

    private static processValue(displayValue: string, mask: string, keepMask: boolean) {
        let value = keepMask ? displayValue : MaskDirective.unmask(displayValue, mask);
        return value
    }

    private static mask(value: string, mask: string): string {
        value = value.toString();

        let len = value.length;
        let maskLen = mask.length;
        let pos = 0;
        let newValue = '';

        for (let i = 0; i < Math.min(len, maskLen); i++) {
            let maskChar = mask.charAt(i);
            let newChar = value.charAt(pos);
            let regex: RegExp = MaskDirective.REGEX_MAP.get(maskChar);

            if (regex) {
                pos++;

                if (regex.test(newChar)) {
                    newValue += newChar;
                } else {
                    i--;
                    len--;
                }
            } else {
                if (maskChar === newChar) {
                    pos++;
                } else {
                    len++;
                }

                newValue += maskChar;
            }
        }       

        return newValue;
    }

    private static unmask(maskedValue: string, mask: string): string {
        let maskLen = (mask && mask.length) || 0;
        return maskedValue.split('').filter(
            (currChar, idx) => (idx < maskLen) && MaskDirective.REGEX_MAP.has(mask[idx])
        ).join('');
    }

    private static delay(ms: number = 0): Promise<void> {
        return new Promise(resolve => setTimeout(() => resolve(), ms)).then(() => null);
    }
}

(Remember to declare it in your NgModule)

The numeric character in the mask is 9 so your mask would be (999) 999-9999. You can change the NUMERIC static field if you want (if you change it to 0, your mask should be (000) 000-0000, for example).

The value is displayed with mask but stored in the component field without mask (this is the desirable behaviour in my case). You can make it be stored with mask using [spKeepMask]="true".

The directive receives an object that implements the MaskGenerator interface.

mask-generator.interface.ts:

export interface MaskGenerator {
    generateMask: (value: string) => string;
}

This way it's possible to define the mask dynamically based on the value (like credit cards).

I've created an utilitarian class to store the masks, but you can specify it directly in your component too.

my-mask.util.ts:

export class MyMaskUtil {

    private static PHONE_SMALL = '(999) 999-9999';
    private static PHONE_BIG = '(999) 9999-9999';
    private static CPF = '999.999.999-99';
    private static CNPJ = '99.999.999/9999-99';

    public static PHONE_MASK_GENERATOR: MaskGenerator = {
        generateMask: () =>  MyMaskUtil.PHONE_SMALL,
    }

    public static DYNAMIC_PHONE_MASK_GENERATOR: MaskGenerator = {
        generateMask: (value: string) => {
            return MyMaskUtil.hasMoreDigits(value, MyMaskUtil.PHONE_SMALL) ? 
                MyMaskUtil.PHONE_BIG : 
                MyMaskUtil.PHONE_SMALL;
        },
    }

    public static CPF_MASK_GENERATOR: MaskGenerator = {
        generateMask: () => MyMaskUtil.CPF,
    }

    public static CNPJ_MASK_GENERATOR: MaskGenerator = {
        generateMask: () => MyMaskUtil.CNPJ,
    }

    public static PERSON_MASK_GENERATOR: MaskGenerator = {
        generateMask: (value: string) => {
            return MyMaskUtil.hasMoreDigits(value, MyMaskUtil.CPF) ? 
                MyMaskUtil.CNPJ : 
                MyMaskUtil.CPF;
        },
    }

    private static hasMoreDigits(v01: string, v02: string): boolean {
        let d01 = this.onlyDigits(v01);
        let d02 = this.onlyDigits(v02);
        let len01 = (d01 && d01.length) || 0;
        let len02 = (d02 && d02.length) || 0;
        let moreDigits = (len01 > len02);
        return moreDigits;      
    }

    private static onlyDigits(value: string): string {
        let onlyDigits = (value != null) ? value.replace(/\D/g, '') : null;
        return onlyDigits;      
    }
}

Then you can use it in your component (use spMaskValue instead of ngModel, but if is not a reactive form, use ngModel with nothing, like in the example below, just so that you won't receive an error of no provider because of the injected NgControl in the directive; in reactive forms you don't need to include ngModel):

my.component.ts:

@Component({ ... })
export class MyComponent {
    public phoneValue01: string = '1231234567';
    public phoneValue02: string;
    public phoneMask01 = MyMaskUtil.PHONE_MASK_GENERATOR;
    public phoneMask02 = MyMaskUtil.DYNAMIC_PHONE_MASK_GENERATOR;
}

my.component.html:

<span>Phone 01 ({{ phoneValue01 }}):</span><br>
<input type="text" [(spMaskValue)]="phoneValue01" [spMask]="phoneMask01" ngModel>
<br><br>
<span>Phone 02 ({{ phoneValue02 }}):</span><br>
<input type="text" [(spMaskValue)]="phoneValue02" [spMask]="phoneMask02" [spKeepMask]="true" ngModel>

(Take a look at phone02 and see that when you type 1 more digit, the mask changes; also, look that the value stored of phone01 is without mask)

I've tested it with normal inputs as well as with ionic inputs (ion-input), with both reactive (with formControlName, not with formControl) and non-reactive forms.

Case insensitive comparison of strings in shell script

All of these answers ignore the easiest and quickest way to do this (as long as you have Bash 4):

if [ "${var1,,}" = "${var2,,}" ]; then
  echo ":)"
fi

All you're doing there is converting both strings to lowercase and comparing the results.

How to set HTML5 required attribute in Javascript?

What matters isn't the attribute but the property, and its value is a boolean.

You can set it using

 document.getElementById("edName").required = true;

Instantiate and Present a viewController in Swift

Swift 4.2 updated code is

let storyboard = UIStoryboard(name: "StoryboardNameHere", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerNameHere")
self.present(controller, animated: true, completion: nil)

How to Apply global font to whole HTML document

Best practice I think is to set the font to the body:

body {
    font: normal 10px Verdana, Arial, sans-serif;
}

and if you decide to change it for some element it could be easily overwrited:

h2, h3 {
    font-size: 14px;
}

When should I use curly braces for ES6 import?

For a default export we do not use { } when we import.

For example,

File player.js

export default vx;

File index.js

import vx from './player';

File index.js

Enter image description here

File player.js

Enter image description here

If we want to import everything that we export then we use *:

Enter image description here

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.

How do you set a JavaScript onclick event to a class with css

Here is my solution through CSS, It does not use any JavaScript at all

HTML:

<a href="#openModal">Open Modal</a>

<div id="openModal" class="modalDialog">
        <div>   <a href="#close" title="Close" class="close">X</a>

                <h2>Modal Box</h2>

            <p>This is a sample modal box that can be created using the powers of CSS3.</p>
            <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
        </div>
    </div>

CSS:

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}
.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}
.close {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}
.close:hover {
    background: #00d9ff;
}

CSS alert No JavaScript Just pure HTML and CSS

I believe that it will do the trick for you as it has for me

Where can I find my Facebook application id and secret key?

It is under Account -> Application Settings, click on your application's profile, then go to Edit Application.

Get elements by attribute when querySelectorAll is not available without using libraries?

Don't use in Browser

In the browser, use document.querySelect('[attribute-name]').

But if you're unit testing and your mocked dom has a flakey querySelector implementation, this will do the trick.

This is @kevinfahy's answer, just trimmed down to be a bit with ES6 fat arrow functions and by converting the HtmlCollection into an array at the cost of readability perhaps.

So it'll only work with an ES6 transpiler. Also, I'm not sure how performant it'll be with a lot of elements.

function getElementsWithAttribute(attribute) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) !== null);
}

And here's a variant that will get an attribute with a specific value

function getElementsWithAttributeValue(attribute, value) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) === value);
}

How to grep recursively, but only in files with certain extensions?

If you want to filter out extensions from the output of another command e.g. "git":

files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')

for file in $files; do
    echo "$file"
done

Python "expected an indented block"

Your for loop has no loop body:

elif option == 2:
    print "please enter a number"
    for x in range(x, 1, 1):
elif option == 0:

Actually, the whole if option == 1: block has indentation problems. elif option == 2: should be at the same level as the if statement.

How to configure nginx to enable kinda 'file browser' mode?

1. List content of all directories

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default ) should be like this

location /{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

2. List content of only some specific directory

Set autoindex option to on. It is off by default.

Your configuration file ( vi /etc/nginx/sites-available/default )
should be like this.
change path_of_your_directory to your directory path

location /path_of_your_directory{ 
   ... ( some other lines )
   autoindex on;
   ... ( some other lines )
}

Hope it helps..

What is the role of the bias in neural networks?

In a couple of experiments in my masters thesis (e.g. page 59), I found that the bias might be important for the first layer(s), but especially at the fully connected layers at the end it seems not to play a big role.

This might be highly dependent on the network architecture / dataset.

C - error: storage size of ‘a’ isn’t known

Your struct is called struct xyx but a is of type struct xyz. Once you fix that, the output is 100.

#include <stdio.h>

struct xyx {
    int x;
    int y;
    char c;
    char str[20];
    int arr[2];
};

int main(void)
{
    struct xyx a;
    a.x = 100;
    printf("%d\n", a.x);
    return 0;
}

What is the difference between jQuery: text() and html() ?

var v = "&#x5168;&#x540D;";
$("#div").html(v); //display as "??"
$("#div").text(v); //display as "&#x5168;&#x540D;"

text() – This method sets or returns the text content of elements selected. html() – This method sets or returns the content of elements selected. Refer example here : https://www.tutorialspoint.com/online_jquery_editor.php

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

font size in html code

Try this:

<html>
  <table>
    <tr>
      <td style="padding-left: 5px;
                 padding-bottom: 3px;">
        <strong style="font-size: 35px;">Datum:</strong><br />
        November 2010 
      </td>
    </tr>
  </table>
</html>

Notice that I also included the table-tag, which you seem to have forgotten. This has to be included if you want this to appear as a table.

MySQL Update Column +1?

The easiest way is to not store the count, relying on the COUNT aggregate function to reflect the value as it is in the database:

   SELECT c.category_name,
          COUNT(p.post_id) AS num_posts
     FROM CATEGORY c
LEFT JOIN POSTS p ON p.category_id = c.category_id

You can create a view to house the query mentioned above, so you can query the view just like you would a table...

But if you're set on storing the number, use:

UPDATE CATEGORY
   SET count = count + 1
 WHERE category_id = ?

..replacing "?" with the appropriate value.

How to generate gcc debug symbol outside the build target?

NOTE: Programs compiled with high-optimization levels (-O3, -O4) cannot generate many debugging symbols for optimized variables, in-lined functions and unrolled loops, regardless of the symbols being embedded (-g) or extracted (objcopy) into a '.debug' file.

Alternate approaches are

  1. Embed the versioning (VCS, git, svn) data into the program, for compiler optimized executables (-O3, -O4).
  2. Build a 2nd non-optimized version of the executable.

The first option provides a means to rebuild the production code with full debugging and symbols at a later date. Being able to re-build the original production code with no optimizations is a tremendous help for debugging. (NOTE: This assumes testing was done with the optimized version of the program).

Your build system can create a .c file loaded with the compile date, commit, and other VCS details. Here is a 'make + git' example:

program: program.o version.o 

program.o: program.cpp program.h 

build_version.o: build_version.c    

build_version.c: 
    @echo "const char *build1=\"VCS: Commit: $(shell git log -1 --pretty=%H)\";" > "$@"
    @echo "const char *build2=\"VCS: Date: $(shell git log -1 --pretty=%cd)\";" >> "$@"
    @echo "const char *build3=\"VCS: Author: $(shell git log -1 --pretty="%an %ae")\";" >> "$@"
    @echo "const char *build4=\"VCS: Branch: $(shell git symbolic-ref HEAD)\";" >> "$@"
    # TODO: Add compiler options and other build details

.TEMPORARY: build_version.c

After the program is compiled you can locate the original 'commit' for your code by using the command: strings -a my_program | grep VCS

VCS: PROGRAM_NAME=my_program
VCS: Commit=190aa9cace3b12e2b58b692f068d4f5cf22b0145
VCS: BRANCH=refs/heads/PRJ123_feature_desc
VCS: AUTHOR=Joe Developer  [email protected]
VCS: COMMIT_DATE=2013-12-19

All that is left is to check-out the original code, re-compile without optimizations, and start debugging.

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Determine when a ViewPager changes pages

ViewPager.setOnPageChangeListener is deprecated now. You now need to use ViewPager.addOnPageChangeListener instead.

for example,

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

Read/Write String from/to a File in Android

the first thing we need is the permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

so in an asyncTask Kotlin class, we treat the creation of the file

    import android.os.AsyncTask
    import android.os.Environment
    import android.util.Log
    import java.io.*
    class WriteFile: AsyncTask<String, Int, String>() {
        private val mFolder = "/MainFolder"
        lateinit var folder: File
        internal var writeThis = "string to cacheApp.txt"
        internal var cacheApptxt = "cacheApp.txt"
        override fun doInBackground(vararg writethis: String): String? {
            val received = writethis[0]
            if(received.isNotEmpty()){
                writeThis = received
            }
            folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
            if(!folder.exists()){
                folder.mkdir()
                val readME = File(folder, cacheApptxt)
                val file = File(readME.path)
                val out: BufferedWriter
                try {
                    out = BufferedWriter(FileWriter(file, true), 1024)
                    out.write(writeThis)
                    out.newLine()
                    out.close()
                    Log.d("Output_Success", folder.path)
                } catch (e: Exception) {
                    Log.d("Output_Exception", "$e")
                }
            }
            return folder.path

    }

        override fun onPostExecute(result: String) {
            super.onPostExecute(result)

            if(result.isNotEmpty()){
                //implement an interface or do something
                Log.d("onPostExecuteSuccess", result)
            }else{
                Log.d("onPostExecuteFailure", result)
            }
        }

    }

Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class ReadandWrite {
        private val mREAD = 9
        private val mWRITE = 10
        private var readAndWrite: Boolean = false
        fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
            if (Build.VERSION.SDK_INT < 23) {
                readAndWrite = true
            } else {
                val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
                val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                if (mRead != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
                } else {
                    readAndWrite = true
                }

                if (mWrite != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
                } else {
                    readAndWrite = true
                }
            }
            return readAndWrite
        }
    }

then in an activity, execute the call.

  var pathToFileCreated = ""
    val anRW = ReadandWrite().readAndwriteStorage(this,this)
    if(anRW){
        pathToFileCreated =  WriteFile().execute("onTaskComplete").get()
        Log.d("pathToFileCreated",pathToFileCreated)
    }

How to upgrade docker-compose to latest version

After a lot of looking at ways to perform this I ended up using jq, and hopefully I can expand it to handle other repos beyond Docker-Compose without too much work.

# If you have jq installed this will automatically find the latest release binary for your architecture and download it
curl --silent "https://api.github.com/repos/docker/compose/releases/latest" | jq --arg PLATFORM_ARCH "$(echo `uname -s`-`uname -m`)" -r '.assets[] | select(.name | endswith($PLATFORM_ARCH)).browser_download_url' | xargs sudo curl -L -o /usr/local/bin/docker-compose --url

How to list npm user-installed packages?

npm ls

npm list is just an alias for npm ls

For the extended info use

npm la    
npm ll

You can always set --depth=0 at the end to get the first level deep.

npm ls --depth=0

You can check development and production packages.

npm ls --only=dev
npm ls --only=prod

To show the info in json format

npm ls --json=true

The default is false

npm ls --json=false

You can insist on long format to show extended information.

npm ls --long=true

You can show parseable output instead of tree view.

npm ls --parseable=true

You can list packages in the global install prefix instead of in the current project.

npm ls --global=true
npm ls -g // shorthand

Full documentation you can find here.

Using Jquery Ajax to retrieve data from Mysql

Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?

Assuming you have correctly fetched your records from your Records.php, You can do something like this:

$(document).ready(function()
{
    $('#getRecords').click(function()
    {
        var response = '';
        $.ajax({ type: 'POST',   
                 url: "Records.php",   
                 async: false,
                 success : function(text){
                               $('#table1').html(text);
                           }
           });
    });

}

In your HTML

<table id="table1"> 
    //Let jQuery AJAX Change This Text  
</table>
<button id='getRecords'>Get Records</button>

A little note:

Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

Breaking out of a nested loop

You asked for a combination of quick, nice, no use of a boolean, no use of goto, and C#. You've ruled out all possible ways of doing what you want.

The most quick and least ugly way is to use a goto.

How do I use Join-Path to combine more than two strings into a file path?

The following approach is more concise than piping Join-Path statements:

$p = "a"; "b", "c", "d" | ForEach-Object -Process { $p = Join-Path $p $_ }

$p then holds the concatenated path 'a\b\c\d'.

(I just noticed that this is the exact same approach as Mike Fair's, sorry.)

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

Importing a function from a class in another file?

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

OAuth: how to test with local URLs?

Update October 2016: Easiest now: use lvh.me which always points to 127.0.0.1.

Previous Answer:

Since the callback request is issued by the browser, as a HTTP redirect response, you can set up your .hosts file or equivalent to point a domain that is not localhost to 127.0.0.1.

Say for example you register the following callback with Twitter: http://www.publicdomain.com/callback/. Make sure that www.publicdomain.com points to 127.0.0.1 in your hosts file, AND that twitter can do a successful DNS lookup on www.publicdomain.com, i.e the domain needs to exist and the specific callback should probably return a 200 status message if requested.

EDIT:

I just read the following article: http://www.tonyamoyal.com/2009/08/17/how-to-quickly-set-up-a-test-for-twitter-oauth-authentication-from-your-local-machine, which was linked to from this question: Twitter oAuth callbackUrl - localhost development.

To quote the article:

You can use bit.ly, a URL shortening service. Just shorten the [localhost URL such as http//localhost:8080/twitter_callback] and register the shortened URL as the callback in your Twitter app.

This should be easier than fiddling around in the .hosts file.

Note that now (Aug '14) bit.ly is not allowing link forwarding to localhost; however Google link shortener works.

PS edit: (Nov '18): Google link shortener stopped giving support for localhost or 127.0.0.1.

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

Syntax:

 sp_spaceused 'Tablename'

see in :

http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data. If so you should design your class Customer differently, like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

How can I refresh c# dataGridView after update ?

You can use the DataGridView refresh method. But... in a lot of cases you have to refresh the DataGridView from methods running on a different thread than the one where the DataGridView is running. In order to do that you should implement the following method and call it rather than directly typing DataGridView.Refresh():

    private void RefreshGridView()
    {
        if (dataGridView1.InvokeRequired)
        {
            dataGridView1.Invoke((MethodInvoker)delegate ()
            {
                RefreshGridView();
            });
        }
        else
            dataGridView1.Refresh();
    }  

Python Pandas Error tokenizing data

The dataset that I used had a lot of quote marks (") used extraneous of the formatting. I was able to fix the error by including this parameter for read_csv():

quoting=3 # 3 correlates to csv.QUOTE_NONE for pandas

How Should I Set Default Python Version In Windows?

This worked for me:

Go to

Control Panel\System and Security\System

select

Advanced system settings from the left panel
from Advanced tab click on Environment Variables

In the System variables section search for (create if doesn't exist)

PYTHONPATH

and set

C:\Python27\;C:\Python27\Scripts;

or your desired version

You need to restart CMD.

In case it still doesn't work you might want to leave in the PATH variable only your desired version.

@HostBinding and @HostListener: what do they do and what are they for?

One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...

@HostBinding('attr.something') 
get something() { 
    return this.somethingElse; 
 }

It works, because it is a get accessor. You couldn't use a function equivalent:

@HostBinding('attr.something') 
something() { 
    return this.somethingElse; 
 }

Otherwise, the benefit of using @HostBinding is it assures change detection is run when the bound value changes.

How to open VMDK File of the Google-Chrome-OS bundle 2012?

you can also use vmware-mount from VMwares VDDK (Virtual Disk Development Kit): http://communities.vmware.com/community/vmtn/developer/forums/vddk

this allows you to mount VMDK files as disk drives in windows or linux

How to add "Maven Managed Dependencies" library in build path eclipse?

If you have m2e installed and the project already is a maven project but the maven dependencies are still missing, the easiest way that worked for me was

  • right click the project,
  • Maven,
  • Update Project...

Eclipse screenshot

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

error (Cannot resolve the collation conflict between .... ) usually occurs while comparing data from multiple databases.

since you cannot change the collation of databases now, use COLLATE DATABASE_DEFAULT.

----------
AND db1.tbl1.fiel1 COLLATE DATABASE_DEFAULT =db2.tbl2.field2 COLLATE DATABASE_DEFAULT 

SHA-256 or MD5 for file integrity

It is technically approved that MD5 is faster than SHA256 so in just verifying file integrity it will be sufficient and better for performance.

You are able to checkout the following resources:

Why can't I define a default constructor for a struct in .NET?

Shorter explanation:

In C++, struct and class were just two sides of the same coin. The only real difference is that one was public by default and the other was private.

In .NET, there is a much greater difference between a struct and a class. The main thing is that struct provides value-type semantics, while class provides reference-type semantics. When you start thinking about the implications of this change, other changes start to make more sense as well, including the constructor behavior you describe.

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

I found another solution to get the data. according to the documentation Please check documentation link

In service file add following.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class MoviesService {

  constructor(private db: AngularFireDatabase) {}
  getMovies() {
    this.db.list('/movies').valueChanges();
  }
}

In Component add following.

import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  movies$;

  constructor(private moviesDb: MoviesService) { 
   this.movies$ = moviesDb.getMovies();
 }

In your html file add following.

<li  *ngFor="let m of movies$ | async">{{ m.name }} </li>

Sorting arrays in javascript by object key value

Use Array's sort() method, eg

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});

How to concatenate columns in a Postgres SELECT?

For example if there is employee table which consists of columns as:

employee_number,f_name,l_name,email_id,phone_number 

if we want to concatenate f_name + l_name as name.

SELECT employee_number,f_name ::TEXT ||','|| l_name::TEXT  AS "NAME",email_id,phone_number,designation FROM EMPLOYEE;

Difference between the System.Array.CopyTo() and System.Array.Clone()

The answers are confusing to me. When you say shallow copy, this means that they are still pointing to the same address. Which means, changing either one will change another as well.

So if I have A = [1,2,3,4] and I clone it and get B = [1,2,3,4]. Now, if I change B[0] = 9. This means that A will now be A = [9,2,3,4]. Is that correct?

Python: 'break' outside loop

This is an old question, but if you wanted to break out of an if statement, you could do:

while 1:
    if blah:
        break

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

How to send authorization header with axios

Try this :

axios.get(
    url,
    {headers: {
        "name" : "value"
      }
    }
  )
  .then((response) => {
      var response = response.data;
    },
    (error) => {
      var status = error.response.status
    }
  );

SQL Query - Using Order By in UNION

(SELECT table1.field1 FROM table1 
UNION
SELECT table2.field1 FROM table2) ORDER BY field1 

Work? Remember think sets. Get the set you want using a union and then perform your operations on it.

Closing WebSocket correctly (HTML5, Javascript)

By using close method of web socket, where you can write any function according to requirement.

var connection = new WebSocket('ws://127.0.0.1:1337');
    connection.onclose = () => {
            console.log('Web Socket Connection Closed');
        };

Importing files from different folder

Your problem is that Python is looking in the Python directory for this file and not finding it. You must specify that you are talking about the directory that you are in and not the Python one.

To do this you change this:

from application.app.folder.file import func_name

to this:

from .application.app.folder.file import func_name

By adding the dot you are saying look in this folder for the application folder instead of looking in the Python directory.

How to define custom sort function in javascript?

For Objects try this:

function sortBy(field) {
  return function(a, b) {
    if (a[field] > b[field]) {
      return -1;
    } else if (a[field] < b[field]) {
      return 1;
    }
    return 0;
  };
}

JavaScript OOP in NodeJS: how?

I suggest to use the inherits helper that comes with the standard util module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

There is an example of how to use it on the linked page.

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

 var span = TimeSpan.FromMinutes(2);
 var t = Task.Factory.StartNew(async delegate / () =>
   {
        this.SomeAsync();
        await Task.Delay(span, source.Token);
  }, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

source.Cancel(true/or not);

// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)

if u like use some loop thread inside ...

public async void RunForestRun(CancellationToken token)
{
  var t = await Task.Factory.StartNew(async delegate
   {
       while (true)
       {
           await Task.Delay(TimeSpan.FromSeconds(1), token)
                 .ContinueWith(task => { Console.WriteLine("End delay"); });
           this.PrintConsole(1);
        }
    }, token) // drop thread options to default values;
}

// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.

jQuery - Redirect with post data

"extended" the above solution with target. For some reason i needed the possibility to redirect the post to _blank or another frame:

$.extend(
   {
       redirectPost: function(location, args, target = "_self")
       {
           var form = $('<form></form>');
           form.attr("method", "post");
           form.attr("action", location);
           form.attr("target", target);
           $.each( args, function( key, value ) {
               var field = $('<input></input>');
               field.attr("type", "hidden");
               field.attr("name", key);
               field.attr("value", value);
               form.append(field);
           });
           $(form).appendTo('body').submit();
       }
   });

NuGet Packages are missing

You also get this error if you use package.config together with this build command

MSBuild.exe /t:Restore MySln.sln

In this case either switch to nuget restore command or use PackageReference.

Increase permgen space

You can use :

-XX:MaxPermSize=128m

to increase the space. But this usually only postpones the inevitable.

You can also enable the PermGen to be garbage collected

-XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled

Usually this occurs when doing lots of redeploys. I am surprised you have it using something like indexing. Use virtualvm or jconsole to monitor the Perm gen space and check it levels off after warming up the indexing.

Maybe you should consider changing to another JVM like the IBM JVM. It does not have a Permanent Generation and is immune to this issue.

How can I install a previous version of Python 3 in macOS using homebrew?

The easiest way for me was to install Anaconda: https://docs.anaconda.com/anaconda/install/

There I can create as many environments with different Python versions as I want and switch between them with a mouse click. It could not be easier.

To install different Python versions just follow these instructions https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html

A new development environment with a different Python version was done within 2 minutes. And in the future I can easily switch back and forth.

cv2.imshow command doesn't work properly in opencv-python

If you choose to use "cv2.waitKey(0)", be sure that you have written "cv2.waitKey(0)" instead of "cv2.waitkey(0)", because that lowercase "k" might freeze your program too.

error MSB6006: "cmd.exe" exited with code 1

For the sake of future readers. My problem was that I was specifying an incompatible openssl library to build my program through CMAKE. Projects were generated but build started failing with this error without any other useful information or error. Verbose cmake/compilation logs didn't help either.

My take away lesson is that cross check the incompatibilities in case your program has dependencies on the any other third party library.

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Ran into the same problem and at first defragmenting seemed to work. But it was for just a short while. Turns out the server the customer was using, was running the Express version and that has a licensing limit of about 10gb.

So even though the size was set to "unlimited", it wasn't.

Save file Javascript with file name

Use the filename property like this:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
              encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');

EDIT:

Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?

Laravel Eloquent "WHERE NOT IN"

You can do following.

DB::table('book_mast') 
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')  
->whereNotIn('book_price',[100,200]);

Windows shell command to get the full path to the current directory?

On Windows:

CHDIR Displays the name of or changes the current directory.

In Linux:

PWD Displays the name of current directory.

failed to find target with hash string android-23

The answer to this question.

Gradle gets stupid from time to time and wiping out the cache is the only solution that I've found. You'll find a hidden .gradle folder under your user home folder and another one wherever the checkout location is for osmdroid.

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Well as the stack trace says, you would need to set the protected mode settings to same for all zones in IE. Read the why here : http://jimevansmusic.blogspot.in/2012/08/youre-doing-it-wrong-protected-mode-and.html

and a quick how to from the same link : "In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone"

Writing a new line to file in PHP (line feed)

You can also use file_put_contents():

file_put_contents('ids.txt', implode("\n", $gemList) . "\n", FILE_APPEND);

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

MySQL > Table doesn't exist. But it does (or it should)

Here is another scenario (version upgrade):

I reinstalled my OS (Mac OS El Captain) and installed a new version of mysql (using homebrew). The installed version (5.7) happened to be newer than my previous one. Then I copied over the tables, including the ib* files, and restarted the server. I could see the tables in mysql workbench but when I tried to select anything, I got "Table doesn't exist".

Solution:

  1. stop the mysql server e.g. mysql.server stop or brew services stop mysql
  2. start the server using mysqld_safe --user=mysql --datadir=/usr/local/var/mysql/ (change path as needed)
  3. run mysql_upgrade -u root -p password (in another terminal window)
  4. shut down the running server mysqladmin -u root -p password shutdown
  5. restart the server in normal mode mysql.server start or brew services start mysql

Relevant docs are here.

Rails: select unique values from a column

If I am going right to way then :

Current query

Model.select(:rating)

is returning array of object and you have written query

Model.select(:rating).uniq

uniq is applied on array of object and each object have unique id. uniq is performing its job correctly because each object in array is uniq.

There are many way to select distinct rating :

Model.select('distinct rating').map(&:rating)

or

Model.select('distinct rating').collect(&:rating)

or

Model.select(:rating).map(&:rating).uniq

or

Model.select(:name).collect(&:rating).uniq

One more thing, first and second query : find distinct data by SQL query.

These queries will considered "london" and "london   " same means it will neglect to space, that's why it will select 'london' one time in your query result.

Third and forth query:

find data by SQL query and for distinct data applied ruby uniq mehtod. these queries will considered "london" and "london " different, that's why it will select 'london' and 'london ' both in your query result.

please prefer to attached image for more understanding and have a look on "Toured / Awaiting RFP".

enter image description here

Find length of 2D array Python

Like this:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

Assuming that all the sublists have the same length (that is, it's not a jagged array).

How can I create objects while adding them into a vector?

To answer the first part of your question, you must create an object of type Player before you can use it. When you say push_back(Player), it means "add the Player class to the vector", not "add an object of type Player to the vector" (which is what you meant).

You can create the object on the stack like this:

Player player;
vectorOfGamers.push_back(player);    // <-- name of variable, not type

Or you can even create a temporary object inline and push that (it gets copied when it's put in the vector):

vectorOfGamers.push_back(Player());    // <-- parentheses create a "temporary"

To answer the second part, you can create a vector of the base type, which will allow you to push back objects of any subtype; however, this won't work as expected:

vector<Gamer> gamers;
gamers.push_back(Dealer());    // Doesn't work properly!

since when the dealer object is put into the vector, it gets copied as a Gamer object -- this means only the Gamer part is copied effectively "slicing" the object. You can use pointers, however, since then only the pointer would get copied, and the object is never sliced:

vector<Gamer*> gamers;
gamers.push_back(new Dealer());    // <-- Allocate on heap with `new`, since we
                                   // want the object to persist while it's
                                   // pointed to

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

Is it possible to get element from HashMap by its position?

Use a LinkedHashMap and when you need to retrieve by position, convert the values into an ArrayList.

LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String,String>();
/* Populate */
linkedHashMap.put("key0","value0");
linkedHashMap.put("key1","value1");
linkedHashMap.put("key2","value2");
/* Get by position */
int pos = 1;
String value = (new ArrayList<String>(linkedHashMap.values())).get(pos);

How do you convert epoch time in C#?

// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

Should use ToUniversalTime() for the DateTime object.

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

How to clear APC cache entries?

Another possibility for command-line usage, not yet mentioned, is to use curl.

This doesn't solve your problem for all cache entries if you're using the stock apc.php script, but it could call an adapted script or another one you've put in place.

This clears the opcode cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=1&`date +%s`"

Change the OB parameter to 3 to clear the user cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=3&`date +%s`"

Put both lines in a script and call it with $PASSWORD in your env.

How to use a switch case 'or' in PHP

I suggest you to go through switch (manual).

switch ($your_variable)
{
    case 1:
    case 2:
        echo "the value is either 1 or 2.";
    break;
}

Explanation

Like for the value you want to execute a single statement for, you can put it without a break as as until or unless break is found. It will go on executing the code and if a break found, it will come out of the switch case.

Get last field using awk substr

It should be a comment to the basename answer but I haven't enough point.

If you do not use double quotes, basename will not work with path where there is space character:

$ basename /home/foo/bar foo/bar.png
bar

ok with quotes " "

$ basename "/home/foo/bar foo/bar.png"
bar.png

file example

$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3

$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3

How to disable auto-play for local video in iframe

Try This Code for disable auto play video.

Its Working . Please Vote if your are done with this

<div class="embed-responsive embed-responsive-16by9">
    <video controls="true" class="embed-responsive-item">
      <source src="example.mp4" type="video/mp4" />
    </video>
</div>

How to generate a core dump in Linux on a segmentation fault?

What I did at the end was attach gdb to the process before it crashed, and then when it got the segfault I executed the generate-core-file command. That forced generation of a core dump.

Install a Nuget package in Visual Studio Code

Example for .csproj file

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="7.0.7-m61" />
  </ItemGroup>

Just get package name and version number from NuGet and add to .csproj then save. You will be prompted to run restore that will import new packages.

Javascript How to define multiple variables on a single line?

Using Javascript's es6 or node, you can do the following:

var [a,b,c,d] = [0,1,2,3]

And if you want to easily print multiple variables in a single line, just do this:

console.log(a, b, c, d)

0 1 2 3

This is similar to @alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.

Note that this uses Javascript's array destructuring assignment

How to check the exit status using an if statement

Just to add to the helpful and detailed answer:

If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... )), this way:

run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }

Or, use a case statement:

run_some_command; ec=$?  # grab the exit code into a variable so that it can
                         # be reused later, without the fear of being overwritten
case $ec in
    0) ;;
    1) printf '%s\n' "Command exited with non-zero"; exit 1;;
    *) do_something_else;;
esac

Related answer about error handling in Bash:

How to [recursively] Zip a directory in PHP?

Try this link <-- MORE SOURCE CODE HERE

/** Include the Pear Library for Zip */
include ('Archive/Zip.php');

/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);

/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/

if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}

?>; // We'll be outputting a ZIP
header('Content-type: application/zip');

// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');

//read a file and send
readfile('test.zip');
?>;

Why can't I define my workbook as an object?

It's actually a sensible question. Here's the answer from Excel 2010 help:

"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."

So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:

Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")

What is Dispatcher Servlet in Spring?

DispatcherServlet is Spring MVC's implementation of the front controller pattern.

See description in the Spring docs here.

Essentially, it's a servlet that takes the incoming request, and delegates processing of that request to one of a number of handlers, the mapping of which is specific in the DispatcherServlet configuration.

How to change the font color of a disabled TextBox?

You can try this. Override the OnPaint event of the TextBox.

    protected override void OnPaint(PaintEventArgs e)
{
     SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
     // Draw string to screen.
     e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}

set the ControlStyles to "UserPaint"

public MyTextBox()//constructor
{
     // This call is required by the Windows.Forms Form Designer.
     this.SetStyle(ControlStyles.UserPaint,true);

     InitializeComponent();

     // TODO: Add any initialization after the InitForm call
}

Refrence

Or you can try this hack

In Enter event set the focus

int index=this.Controls.IndexOf(this.textBox1);

this.Controls[index-1].Focus();

So your control will not focussed and behave like disabled.

python inserting variable string as file name

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')

CSS Input with width: 100% goes outside parent's bound

I tried these solutions but never got a conclusive result. In the end I used proper semantic markup with a fieldset. It saved having to add any width calculations and any box-sizing.

It also allows you to set the form width as you require and the inputs remain within the padding you need for your edges.

In this example I have put a border on the form and fieldset and an opaque background on the legend and fieldset so you can see how they overlap and sit with each other.

<html>
  <head>
  <style>
    form {
      width: 300px;
      margin: 0 auto;
      border: 1px solid;
    }
    fieldset {
      border: 0;
      margin: 0;
      padding: 0 20px 10px;
      border: 1px solid blue;
      background: rgba(0,0,0,.2);
    }
    legend {
      background: rgba(0,0,0,.2);
      width: 100%;
      margin: 0 -20px;
      padding: 2px 20px;
      color: $col1;
      border: 0;
    }
    input[type="email"],
    input[type="password"],
    button {
      width: 100%;
      margin: 0 0 10px;
      padding: 0 10px;
    }
    input[type="email"],
    input[type="password"] {
      line-height: 22px;
      font-size: 16px;
    }
    button {
    line-height: 26px;
    font-size: 20px;
    }
  </style>
  </head>
  <body>
  <form>
      <fieldset>
          <legend>Log in</legend>
          <p>You may need some content here, a message?</p>
          <input type="email" id="email" name="email" placeholder="Email" value=""/>
          <input type="password" id="password" name="password" placeholder="password" value=""/>
          <button type="submit">Login</button>
      </fieldset>
  </form>
  </body>
</html>

Description Box using "onmouseover"

I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.

Here's a simple example.

HTML:

?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????

Basic CSS:

?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?

jQuery:

$("#testText").hover(
   function(e){
       $("#tooltip").show();
   },
   function(e){
       $("#tooltip").hide();
  });??????????

How do I Validate the File Type of a File Upload?

Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.

HTML:

<input type="file" name="FILENAME"  size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />

Javascript:

var hash = {
  'xls'  : 1,
  'xlsx' : 1,
};

function check_extension(filename,submitId) {
      var re = /\..+$/;
      var ext = filename.match(re);
      var submitEl = document.getElementById(submitId);
      if (hash[ext]) {
        submitEl.disabled = false;
        return true;
      } else {
        alert("Invalid filename, please select another file");
        submitEl.disabled = true;

        return false;
      }
}

Simplest way to throw an error/exception with a custom message in Swift 2?

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

struct RuntimeError: LocalizedError
{
    let message: String

    init(_ message: String)
    {
        self.message = message
    }

    public var errorDescription: String?
    {
        return message
    }
}

See this answer for more details.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

Creating an Instance of a Class with a variable in Python

If you just want to pass a class to a function, so that this function can create new instances of that class, just treat the class like any other value you would give as a parameter:

def printinstance(someclass):
  print someclass()

Result:

>>> printinstance(list)
[]
>>> printinstance(dict)
{}

How to bind Events on Ajax loaded Content?

use jQuery.live() instead . Documentation here

e.g

$("mylink").live("click", function(event) { alert("new link clicked!");});

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install. This should solve the problem.

Docker container will automatically stop after "docker run -d"

I have this code snippet run from the ENTRYPOINT in my docker file:

while true
do
    echo "Press [CTRL+C] to stop.."
    sleep 1
done

Run the built docker image as:

docker run -td <image name>

Log in to the container shell:

docker exec -it <container id> /bin/bash

How can I select the record with the 2nd highest salary in database Oracle?

WITH records
AS
(
    SELECT  id, user_name, salary,
            DENSE_RANK() OVER (PARTITION BY id ORDER BY salary DESC) rn
    FROM    tableName
)
SELECT  id, user_name, salary
FROM    records 
WHERE   rn = 2

"Register" an .exe so you can run it from any command line in Windows

Use a 1 line batch file in your install:

SETX PATH "C:\Windows"

run the bat file

Now place your .exe in c:\windows, and you're done.

you may type the 'exename' in command-line and it'll run it.

How do you add swap to an EC2 instance?

We can add swap space in any server

create a file using dd command

 #dd if=/dev/zero of=/swapfile bs=1M count=2048
                    or
 #dd if=/dev/zero of=/swapfile bs=1024M count=2

bs is blocksize and count refers to the size in MB or GB

we can use vice versa

After creation change the permission of file :

 #chmod 600 /swapfile 

Then makeswap the file :

 #mkswap /swapfile 

Then enable the swap file with swapon command :

 #swapon  /swapfile 

Check with free command whether swap is enabled or not :

 #free -h
 #swapon -s

Create an empty object in JavaScript with {} or new Object()?

I believe {} was recommended in one of the Javascript vids on here as a good coding convention. new is necessary for pseudoclassical inheritance. the var obj = {}; way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new is when you are using constructors functions. For example:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

Then it is used like so:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

Another advantage to using {} as oppose to new Object is you can use it to do JSON-style object literals.

Is there a way to add a gif to a Markdown file?

Upload from local:

  1. Add your .gif file to the root of Github repository and push the change.
  2. Go to README.md
  3. Add this ![Alt text](name-of-gif-file.gif) / ![](name-of-gif-file.gif)
  4. Commit and gif should be seen.

Show the gif using url:

  1. Go to README.md
  2. Add in this format ![Alt text](https://sample/url/name-of-gif-file.gif)
  3. Commit and gif should be seen.

Hope this helps.

Insert into ... values ( SELECT ... FROM ... )

You could try this if you want to insert all column using SELECT * INTO table.

SELECT  *
INTO    Table2
FROM    Table1;

How to disable EditText in Android

you can use EditText.setFocusable(false) to disable editing
EditText.setFocusableInTouchMode(true) to enable editing;

Using :after to clear floating elements

Use

.wrapper:after {
    content : '\n';
}

Much like solution provided by Roko. It allows to insert/change content using : after and :before psuedo. For details check http://www.quirksmode.org/css/content.html

Integer.toString(int i) vs String.valueOf(int i)

From the Java sources:

/**
 * Returns the string representation of the {@code int} argument.
 * <p>
 * The representation is exactly the one returned by the
 * {@code Integer.toString} method of one argument.
 *
 * @param   i   an {@code int}.
 * @return  a string representation of the {@code int} argument.
 * @see     java.lang.Integer#toString(int, int)
 */
public static String valueOf(int i) {
    return Integer.toString(i);
}

So they give exactly the same result and one in fact calls the other. String.valueOf is more flexible if you might change the type later.

With Spring can I make an optional path variable?

You can't have optional path variables, but you can have two controller methods which call the same service code:

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
        HttpServletRequest req,
        @PathVariable String type,
        @RequestParam("track") String track) {
    return getTestBean(type);
}

@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
        HttpServletRequest req,
        @RequestParam("track") String track) {
    return getTestBean();
}

How do I install cygwin components from the command line?

Old question, but still relevant. Here is what worked for me today (6/26/16).

From the bash shell:

lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg
install apt-cyg /bin

How do I force a favicon refresh?

To refresh your site's favicon you can force browsers to download a new version using the link tag and a querystring on your filename. This is especially helpful in production environments to make sure your users get the update.

<link rel="icon" href="http://www.yoursite.com/favicon.ico?v=2" />

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

Can I get all methods of a class?

package tPoint;

import java.io.File;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class ReadClasses {

public static void main(String[] args) {

    try {
        Class c = Class.forName("tPoint" + ".Sample");
        Object obj = c.newInstance();
        Document doc = 
        DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File("src/datasource.xml"));

        Method[] m = c.getDeclaredMethods();

        for (Method e : m) {
            String mName = e.getName();
            if (mName.startsWith("set")) {
                System.out.println(mName);
                e.invoke(obj, new 
          String(doc.getElementsByTagName(mName).item(0).getTextContent()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Matplotlib scatter plot legend

2D scatter plot

Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry.

In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()

enter image description here

3D scatter plot

To plot a scatter in 3D, use the plot method, as the legend does not support Patch3DCollection as is returned by the scatter method of an Axes3D instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle and marker parameters.

import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()

enter image description here

Iterate through a C++ Vector using a 'for' loop

With STL, programmers use iterators for traversing through containers, since iterator is an abstract concept, implemented in all standard containers. For example, std::list has no operator [] at all.

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

Differences between strong and weak in Objective-C

Strong: Basically Used With Properties we used to get or send data from/into another classes. Weak: Usually all outlets, connections are of Weak type from Interface.

Nonatomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Nonatomic instance make our properties to deal with one thread at a time. Hopefully it helpful for you.

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Just faced the issue of Unexpected end of JSON input while parsing near.. while adding the 'radium' package in my React App. As a matter of fact, I am facing this issue even when trying to update the NPM to the latest version.

Anyways, NPM didn't work after clearing the cache and it also won't update to the latest version right now but adding the package via Yarn did the trick for me.

So, if you are in a hurry to solve this issue but you are not able to, then give yarn a try instead of npm.

Happy Coding!

Update

After trying few things finally sudo npm cache clean --force worked for me.

This can be a temporary glitch in your network or with something else in the npm registry.

Hive Alter table change Column Name

Command works only if "use" -command has been first used to define the database where working in. Table column renaming syntax using DATABASE.TABLE throws error and does not work. Version: HIVE 0.12.

EXAMPLE:

hive> ALTER TABLE databasename.tablename CHANGE old_column_name new_column_name;

  MismatchedTokenException(49!=90)
        at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617)
        at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115)
        at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixExchangePartition(HiveParser.java:11492)
        ...

hive> use databasename;

hive> ALTER TABLE tablename CHANGE old_column_name new_column_name;

OK

How do I get a python program to do nothing?

You could use a pass statement:

if condition:
    pass

Python 2.x documentation

Python 3.x documentation

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

If you have something like this:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

How do I use StringUtils in Java?

java.lang does not contain a class called StringUtils. Several third-party libs do, such as Apache Commons Lang or the Spring framework. Make sure you have the relevant jar in your project classpath and import the correct class.

nginx 502 bad gateway

If running a linux server, make sure that your IPTABLES configuration is correct.

Execute sudo iptables -L -n , you will recieve a listing of your open ports. If there is not an Iptables Rule to open the port serving the fcgi script you will receive a 502 error. The Iptables Rule which opens the correct port must be listed before any rule which categorically rejects all packets (i.e. a rule of the form "REJECT ALL -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable or similar)

On my configuration, to properly open the port, I had to execute this command (assume my fcgi server is running at port 4567):

sudo iptables -I INPUT 1 -p tcp --dport 4567 -j ACCEPT

WARNING: This will open port 4567 to the whole world.

So it might be better to do something like this:

   sudo iptables-save >> backup.iptables
   sudo iptables -D INPUT 1 #Delete the previously entered rule
   sudo iptables -I INPUT 1 -p tcp --dport 8080 -s localhost -j ACCEPT # Add new rule

Doing this removed the 502 error for me.

Is there a portable way to get the current username in Python?

Using only standard python libs:

from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()

Works on Windows (if you are on drive C), Mac or Linux

Alternatively, you could remove one line with an immediate invocation:

from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()

How to force file download with PHP

header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");

Dynamically add event listener

I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:

ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }

If i´m adding a listener

this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
    alert('Clicking the document');
})

I´d expect my function to execute what i intended, not the total opposite which is remove the listener.

// I´d expect an alert('Clicking the document'); 
this.listenToClick();
// what you actually get is removing the listener, so nothing...

In the given scenario, It´d actually make to more sense to name it like:

// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
    console.log('Clicking the document', evt);
})

let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
    console.log('Clicking the button', evt);
});

There must be a good reason for this but in my opinion it´s very misleading and not intuitive.

get all the elements of a particular form

document.forms["form_name"].getElementsByTagName("input");

Ignoring NaNs with str.contains

df[df.col.str.contains("foo").fillna(False)]

Fatal error: Call to undefined function mb_detect_encoding()

Mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option.

In case your php version is 7.0:

sudo apt-get install php7.0-mbstring

sudo service apache2 restart

In case your php version is 5.6:

sudo apt-get install php5.6-mbstring

sudo service apache2 restart

How to read/write files in .Net Core?

For writing any Text to a file.

public static void WriteToFile(string DirectoryPath,string FileName,string Text)
    {
        //Check Whether directory exist or not if not then create it
        if(!Directory.Exists(DirectoryPath))
        {
            Directory.CreateDirectory(DirectoryPath);
        }

        string FilePath = DirectoryPath + "\\" + FileName;
        //Check Whether file exist or not if not then create it new else append on same file
        if (!File.Exists(FilePath))
        {
            File.WriteAllText(FilePath, Text);
        }
        else
        {
            Text = $"{Environment.NewLine}{Text}";
            File.AppendAllText(FilePath, Text);
        }
    }

For reading a Text from file

public static string ReadFromFile(string DirectoryPath,string FileName)
    {
        if (Directory.Exists(DirectoryPath))
        {
            string FilePath = DirectoryPath + "\\" + FileName;
            if (File.Exists(FilePath))
            {
                return File.ReadAllText(FilePath);
            }
        }
        return "";
    }

For Reference here this is the official microsoft document link.

Replacing .NET WebBrowser control with a better browser, like Chrome?

Chrome uses (a fork of) Webkit if you didn't know, which is also used by Safari. Here's a few questions that are of the same vein:

The webkit one isn't great as the other answer states, one version no longer works (the google code one) and the Mono one is experimental. It'd be nice if someone made the effort to make a decent .NET wrapper for it but it's not something anyone seems to want to do - which is surprising given it now has support for HTML5 and so many other features that the IE(8) engine lacks.

Update (2014)

There's new dual-licensed project that allows you embed Chrome into your .NET applications called Awesomium. It comes with a .NET api but requires quite a few hacks for rendering (the examples draw the browser window to a buffer, paint the buffer as an image and refresh on a timer).

I think this is the browser used by Origin in Battlefield 3.

Update (2016)

There is now DotnetBrowser, a commercial alternative to Awesomium. It's based off Chromium.