Programs & Examples On #Version control migration

Git merge develop into feature branch outputs "Already up-to-date" while it's not

You should first pull the changes from the develop branch and only then merge them to your branch:

git checkout develop 
git pull 
git checkout branch-x
git rebase develop

Or, when on branch-x:

git fetch && git rebase origin/develop

I have an alias that saves me a lot of time. Add to your ~/.gitconfig:

[alias]
    fr = "!f() { git fetch && git rebase origin/"$1"; }; f"

Now, all that you have to do is:

git fr develop

Get Element value with minidom with Python

I know this question is pretty old now, but I thought you might have an easier time with ElementTree

from xml.etree import ElementTree as ET
import datetime

f = ET.XML(data)

for element in f:
    if element.tag == "currentTime":
        # Handle time data was pulled
        currentTime = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
    if element.tag == "cachedUntil":
        # Handle time until next allowed update
        cachedUntil = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
    if element.tag == "result":
        # Process list of skills
        pass

I know that's not super specific, but I just discovered it, and so far it's a lot easier to get my head around than the minidom (since so many nodes are essentially white space).

For instance, you have the tag name and the actual text together, just as you'd probably expect:

>>> element[0]
<Element currentTime at 40984d0>
>>> element[0].tag
'currentTime'
>>> element[0].text
'2010-04-12 02:45:45'e

How do I duplicate a line or selection within Visual Studio Code?

in my last version Visual Studio Code 1.30.2 it wil be change automatically into


ctrl + D

How to submit an HTML form on loading the page?

You don't need Jquery here! The simplest solution here is (based on the answer from charles):

<html>
<body onload="document.frm1.submit()">
   <form action="http://www.google.com" name="frm1">
      <input type="hidden" name="q" value="Hello world" />
   </form>
</body>
</html>

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

Converting string to double in C#

In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?

You may also want to figure out if your last String will be empty, and account for that situation.

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

My target is a x64 Windows 10 text mode DOSBox application in C language. Using "Visual Studio 2019 Community" to compile through DOS prompt "nmake -f makefile". The error is similar but on the opposite side:

fatal error LNK1112: module machine type 'x32' conflicts with target machine type 'X64'

It's ok to compile by VC++ 2010 on another computer. But failed on this computer by "Visual Studio 2019 Community". So my settings are correct and all above answers do not work.

I'd like to share you that the solution is a make.bat like this:

call "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" 
nmake -f makefile

You will find there are many other vcvarsxxxx.bat, only this one words.

How to format a string as a telephone number in C#

You can try {0: (000) 000-####} if your target number starts with 0.

How to export all data from table to an insertable sql format?

Quick and Easy way:

  1. Right click database
  2. Point to tasks In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu Thanks to Daniel for the comment to update.
  3. Select generate scripts
  4. Click next
  5. Choose tables
  6. Click next
  7. Click advanced
  8. Scroll to Types of data to script - Called types of data to script in SMSS 2014 Thanks to Ellesedil for commenting
  9. Select data only
  10. Click on 'Ok' to close the advanced script options window
  11. Click next and generate your script

I usually in cases like this generate to a new query editor window and then just do any modifications where needed.

Set margins in a LinearLayout programmatically

I have set up margins directly using below code

LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            
params.setMargins(3, 300, 3, 3); 
layout.setLayoutParams(params);

Only thing here is to notice that LayoutParams should be imported for following package android.widget.RelativeLayout.LayoutParams, or else there will be an error.

Using lodash to compare jagged arrays (items existence without order)

There are already answers here, but here's my pure JS implementation. I'm not sure if it's optimal, but it sure is transparent, readable, and simple.

// Does array a contain elements of array b?
const contains = (a, b) => new Set([...a, ...b]).size === a.length
const isEqualSet = (a, b) => contains(a, b) && contains(b, a)

The rationale in contains() is that if a does contain all the elements of b, then putting them into the same set would not change the size.

For example, if const a = [1,2,3,4] and const b = [1,2], then new Set([...a, ...b]) === {1,2,3,4}. As you can see, the resulting set has the same elements as a.

From there, to make it more concise, we can boil it down to the following:

const isEqualSet = (a, b) => {
  const unionSize = new Set([...a, ...b])
  return unionSize === a.length && unionSize === b.length
}

IF statement: how to leave cell blank if condition is false ("" does not work)

To Validate data in column A for Blanks

Step 1: Step 1: B1=isblank(A1)

Step 2: Drag the formula for the entire column say B1:B100; This returns Ture or False from B1 to B100 depending on the data in column A

Step 3: CTRL+A (Selct all), CTRL+C (Copy All) , CRTL+V (Paste all as values)

Step4: Ctrl+F ; Find and replace function Find "False", Replace "leave this blank field" ; Find and Replace ALL

There you go Dude!

Get nth character of a string in Swift programming language

Here's an extension you can use, working with Swift 3.1. A single index will return a Character, which seems intuitive when indexing a String, and a Range will return a String.

extension String {
    subscript (i: Int) -> Character {
        return Array(self.characters)[i]
    }
    
    subscript (r: CountableClosedRange<Int>) -> String {
        return String(Array(self.characters)[r])
    }
    
    subscript (r: CountableRange<Int>) -> String {
        return self[r.lowerBound...r.upperBound-1]
    }
}

Some examples of the extension in action:

let string = "Hello"

let c1 = string[1]  // Character "e"
let c2 = string[-1] // fatal error: Index out of range

let r1 = string[1..<4] // String "ell"
let r2 = string[1...4] // String "ello"
let r3 = string[1...5] // fatal error: Array index is out of range


n.b. You could add an additional method to the above extension to return a String with a single character if wanted:

subscript (i: Int) -> String {
    return String(self[i])
}

Note that then you would have to explicitly specify the type you wanted when indexing the string:

let c: Character = string[3] // Character "l"
let s: String = string[0]    // String "H"

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command

KILL 69

I hope this helps :)

How to change column order in a table using sql query in sql server 2005?

In SQLServer Management Studio:

Tools -> Options -> Designers -> Table and Database Designers

  • Unselect 'Prevent saving changes that require table re-creation'.

Then:

  • right click the table you want to re-order the columns for.
  • click 'Design'.
  • Drag the columns to the order you want.
  • finally, click save.

SQLServer Management studio will drop the table and recreate it using the data.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I had the same error after using the hibernate code generation

https://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/

then the hibernate.cfg.xml was created in /src/main/java but without the connection parameters after removing it - my problem was solved

What are .a and .so files?

Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.

The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.

This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

Hope this helps.

How do I remove objects from a JavaScript associative array?

You are using Object, and you don't have an associative array to begin with. With an associative array, adding and removing items goes like this:

    Array.prototype.contains = function(obj)
    {
        var i = this.length;
        while (i--)
        {
            if (this[i] === obj)
            {
                return true;
            }
        }
        return false;
    }


    Array.prototype.add = function(key, value)
    {
        if(this.contains(key))
            this[key] = value;
        else
        {
            this.push(key);
            this[key] = value;
        }
    }


    Array.prototype.remove = function(key)
    {
        for(var i = 0; i < this.length; ++i)
        {
            if(this[i] == key)
            {
                this.splice(i, 1);
                return;
            }
        }
    }



    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }

        return vars;
    }


    function ForwardAndHideVariables() {
        var dictParameters = getUrlVars();

        dictParameters.add("mno", "pqr");
        dictParameters.add("mno", "stfu");

        dictParameters.remove("mno");


        for(var i = 0; i < dictParameters.length; i++)
        {
            var key = dictParameters[i];
            var value = dictParameters[key];
            alert(key + "=" + value);
        }
        // And now forward with HTTP-POST
        aa_post_to_url("Default.aspx", dictParameters);
    }


    function aa_post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        // Move the submit function to another variable
        // so that it doesn't get written over if a parameter name is 'submit'
        form._submit_function_ = form.submit;

        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var i = 0; i < params.length; i++)
        {
            var key = params[i];

            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form._submit_function_(); // Call the renamed function
    }

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

The solution that worked for me is that:- I moved my data.json file from src to public directory. Then used fetch API to fetch the file.

fetch('./data.json').then(response => {
          console.log(response);
          return response.json();
        }).then(data => {
          // Work with JSON data here
          console.log(data);
        }).catch(err => {
          // Do something for an error here
          console.log("Error Reading data " + err);
        });

The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.

Git, fatal: The remote end hung up unexpectedly

Contrary to one of the other answers - I had the problem on push using ssh - I switched to https and it was fixed.

git remote remove origin
git remote add origin https://github..com/user/repo
git push --set-upstream origin master

Python vs. Java performance (runtime speed)

Different languages do different things with different levels of efficiency.

The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.

Python: BeautifulSoup - get an attribute value based on the name attribute

The following works:

from bs4 import BeautifulSoup

soup = BeautifulSoup('<META NAME="City" content="Austin">', 'html.parser')

metas = soup.find_all("meta")

for meta in metas:
    print meta.attrs['content'], meta.attrs['name']

What is a Java String's default initial value?

Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.

Serializing an object as UTF-8 XML in .NET

I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

How to make a div with a circular shape?

HTML div elements, unlike SVG circle primitives, are always rectangular.

You could use round corners (i.e. CSS border-radius) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:

_x000D_
_x000D_
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
_x000D_
_x000D_

npm can't find package.json

For the following command

sudo npm install react browserify watchify babelify --save-dev

I got same error

saveError ENOENT: no such file or directory, open '/Users/Path/package.json'

But when I run the command

sudo npm install -gd react browserify watchify babelify --save-dev

then no missing file or directory message appeared.

How can I use interface as a C# generic type constraint?

The closest you can do (except for your base-interface approach) is "where T : class", meaning reference-type. There is no syntax to mean "any interface".

This ("where T : class") is used, for example, in WCF to limit clients to service contracts (interfaces).

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

If you want to return a format mm/dd/yyyy, then use 101 instead of 103: CONVERT(VARCHAR(10), [MyDate], 101)

What is the difference between Bootstrap .container and .container-fluid classes?

Updated 2019

The basic difference is that container is scales responsively, while container-fluid is always width:100%. Therefore in the root CSS definitions, they appear the same, but if you look further you'll see that .container is bound to media queries.

Bootstrap 4

The container has 5 widths...

.container {
  width: 100%;
}

@media (min-width: 576px) {
  .container {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .container {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .container {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .container {
    max-width: 1140px;
  }
}

Bootstrap 3

The container has 4 sizes. Full width on xs screens, and then it's width varies based on the following media queries..

    @media (min-width: 1200px) {
        .container {
            width: 1170px;
        }
    }
    @media (min-width: 992px) {
        .container {
            width: 970px;
        }
    }
    @media (min-width: 768px) {
        .container {
            width: 750px;
        }
    }

container vs. container-fluid demo

String concatenation in MySQL

Try:

select concat(first_name,last_name) as "Name" from test.student

or, better:

select concat(first_name," ",last_name) as "Name" from test.student

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.

Create role

CREATE ROLE [db_SomeExecutor] 
GO

Grant Permission to this role

GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT  TO db_SomeExecutor

to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then

OR

   EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'

Please refer this post

How to trigger click event on href element

In addition to romkyns's great answer.. here is some relevant documentation/examples.


DOM Elements have a native .click() method.

The HTMLElement.click() method simulates a mouse click on an element.

When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an <a> element to initiate navigation as if a real mouse-click had been received. (mdn reference)

Relevant W3 documentation.


A few examples..

  • You can access a specific DOM element from a jQuery object: (example)

      $('a')[0].click();
    
  • You can use the .get() method to retrieve a DOM element from a jQuery object: (example)

      $('a').get(0).click();
    
  • As expected, you can select the DOM element and call the .click() method. (example)

      document.querySelector('a').click();
    

It's worth pointing out that jQuery is not required to trigger a native .click() event.

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

What USB driver should we use for the Nexus 5?

I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.

When I plugged it, there wasn't any yellow exclamation mark within Device Manager. So for me, the drivers were OK. But the device was not listed within my Eclipse DDMS. After a little bit of searching, it was just an option to change in the device settings. By default, the Nexus 5 USB computer connection is in MTP mode (Media Device).

What you have to do is:

  • Unplug the device from the computer
  • Go to Settings -> Storage.
  • In the ActionBar, click the option menu and choose "USB computer connection".
  • Check "Camera (PTP)" connection.
  • Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.
  • Finally, you should see it now in the DDMS and voilà.

I hope this will help!

HTML 5 video or audio playlist

You should take a look at Popcorn.js - a javascript framework for interacting with Html5 : http://popcornjs.org/documentation

Full Page <iframe>

Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Test Layout</title>
        <style type="text/css">
            body, html
            {
                margin: 0; padding: 0; height: 100%; overflow: hidden;
            }

            #content
            {
                position:absolute; left: 0; right: 0; bottom: 0; top: 0px; 
            }
        </style>
    </head>
    <body>
        <div id="content">
            <iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
        </div>
    </body>
</html>

"Error: Main method not found in class MyClass, please define the main method as..."

Other answers are doing a good job of summarizing the requirements of main. I want to gather references to where those requirements are documented.

The most authoritative source is the VM spec (second edition cited). As main is not a language feature, it is not considered in the Java Language Specification.

Another good resource is the documentation for the application launcher itself:

How do I enable logging for Spring Security?

Assuming you're using Spring Boot, another option is to put the following in your application.properties:

logging.level.org.springframework.security=DEBUG

This is the same for most other Spring modules as well.

If you're not using Spring Boot, try setting the property in your logging configuration, e.g. logback.

Here is the application.yml version as well:

logging:
  level:
    org:
      springframework:
        security: DEBUG

Best practice for using assert?

An Assert is to check -
1. the valid condition,
2. the valid statement,
3. true logic;
of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.

In example 1, since variable 'str' is not null. So no any assert or exception get raised.

Example 1:

#!/usr/bin/python

str = 'hello Python!'
strNull = 'string is Null'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)


------------------------------------------------------

Output:
hello Python!
FileName ..................... hello
FilePath ..................... C:/Python\hello.py

In example 2, var 'str' is null. So we are saving the user from going ahead of faulty program by assert statement.

Example 2:

#!/usr/bin/python

str = ''
strNull = 'NULL String'

if __debug__:
    if not str: raise AssertionError(strNull)
print str

if __debug__:
    print 'FileName '.ljust(30,'.'),(__name__)
    print 'FilePath '.ljust(30,'.'),(__file__)


------------------------------------------------------

Output:
AssertionError: NULL String

The moment we don't want debug and realized the assertion issue in the source code. Disable the optimization flag

python -O assertStatement.py
nothing will get print

How to add a local repo and treat it as a remote repo

I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.

I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.

This is my first post here so please advise what should be improved.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

How do I position a div relative to the mouse pointer using jQuery?

You don not need to create a $(document).mousemove( function(e) {}) to handle mouse x,y. Get the event in the $.hover function and from there it is possible to get x and y positions of the mouse. See the code below:

$('foo').hover(function(e){
    var pos = [e.pageX-150,e.pageY];
    $('foo1').dialog( "option", "position", pos );
    $('foo1').dialog('open');
},function(){
    $('foo1').dialog('close');
});

Can an XSLT insert the current date?

format-date(current-date(), '[M01]/[D01]/[Y0001]') = 09/19/2013
format-time(current-time(), '[H01]:[m01] [z]') = 09:26 GMT+10
format-dateTime(current-dateTime(), '[h1]:[m01] [P] on [MNn] [D].') = 9:26 a.m. on September 19.

reference: Formatting Dates and Times using XSLT 2.0 and XPath

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

Please see what the update-alternatives command does (it has a nice man...).

Shortly - what happens when you have java-sun-1.4 and java-opensouce-1.0 ... which one takes "java"? It debian "/usr/bin/java" is symbolic link and "/usr/bin/java-sun-1.4" is an alternative to "/usr/bin/java"

Edit: As Richard said, update-alternatives is not enough. You actually need to use update-java-alternatives. More info at:

https://help.ubuntu.com/community/Java

How to determine whether a year is a leap year?

A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400. For example,

if( (year % 4) == 0):
    if ( (year % 100 ) == 0):

        if ( (year % 400) == 0):

            print("{0} is a leap year".format(year))
        else:

            print("{0} is not a leap year".format(year))
    else:

        print("{0} is a leap year".format(year))

else:

    print("{0} is not a leap year".format(year))

Upload failed You need to use a different version code for your APK because you already have one with version code 2

If you're using Android Studio, you could go:

Build -> Edit Flavors

And change the Version Code and Name from there.

enter image description here

What is a clearfix?

If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.

It's worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.

  • display: inline-block - Better
  • Flexbox - Best (but limited browser support)

Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.

For a detailed browser list see: https://caniuse.com/flexbox.

(Perhaps once its position is established completely, it may be the absolutely recommended way of laying out elements.)


A clearfix is a way for an element to automatically clear its child elements, so that you don't need to add additional markup. It's generally used in float layouts where elements are floated to be stacked horizontally.

The clearfix is a way to combat the zero-height container problem for floated elements

A clearfix is performed as follows:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don't require IE<8 support, the following is fine too:

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

Normally you would need to do something as follows:

<div>
    <div style="float: left;">Sidebar</div>
    <div style="clear: both;"></div> <!-- Clear the float -->
</div>

With clearfix, you only need the following:

<div class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar</div>
    <!-- No Clearing div! -->
</div>

Read about it in this article - by Chris Coyer @ CSS-Tricks

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

The final solution to your assembly redirect errors

Okay, hopefully this should help resolve any (sane) assembly reference discrepancies ...

  1. Check the error.

Surf to the website

  1. Check web.config after the assembly redirect. Create one if not exists.

Existing web.config assembly redirect

  1. Right-click the reference for the assembly and choose Properties.

Assembly in the Reference list, in the relevant project

  1. Check the Version (not Runtime version) in the Properties table. Copy that.

Properties table showing Version of assembly

  1. Paste into the newVersion attribute.

web.config assembly redirect with updated newVersion

  1. For convenience, change the last part of the oldVersion to something high, round and imaginary.

web.config assembly redirect with updated oldVersion

Rejoice.

How to remove hashbang from url?

The vue-router uses hash-mode, in simple words it is something that you would normally expect from an achor tag like this.

<a href="#some_section">link<a>

To make the hash disappear

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
] // Routes Array
const router = new VueRouter({
  mode: 'history', // Add this line
  routes
})

Warning: If you do not have a properly configured server or you are using a client-side SPA user may get a 404 Error if they try to access https://website.com/posts/3 directly from their browser. Vue Router Docs

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

If you are facing this issue with rails and you know that you already have created that user-name with password along with correct rights then you just need to put following at the end of your database.yml file.

host: localhost

overall file will look like below

development:
  adapter: postgresql
  encoding: unicode
  database: myapp_development
  pool: 5
  username: root
  password: admin
  host: localhost

You do not need to touch you pg_hba.conf file at all. Happy coding

How to repeat a string a variable number of times in C++?

You should write your own stream manipulator

cout << multi(5) << "whatever" << "lolcat";

Node.js: socket.io close client connection

Did you try:

socket.disconnect() 

on client?

Babel 6 regeneratorRuntime is not defined

Be careful of hoisted functions

I had both my 'polyfill import' and my 'async function' in the same file, however I was using the function syntax that hoists it above the polyfill which would give me the ReferenceError: regeneratorRuntime is not defined error.

Change this code

import "babel-polyfill"
async function myFunc(){ }

to this

import "babel-polyfill"
var myFunc = async function(){}

to prevent it being hoisted above the polyfill import.

Select distinct values from a table field

Say your model is 'Shop'

class Shop(models.Model):
    street = models.CharField(max_length=150)
    city = models.CharField(max_length=150)

    # some of your models may have explicit ordering
    class Meta:
        ordering = ('city')

Since you may have the Meta class ordering attribute set, you can use order_by() without parameters to clear any ordering when using distinct(). See the documentation under order_by()

If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.

and distinct() in the note where it discusses issues with using distinct() with ordering.

To query your DB, you just have to call:

models.Shop.objects.order_by().values('city').distinct()

It returns a dictionnary

or

models.Shop.objects.order_by().values_list('city').distinct()

This one returns a ValuesListQuerySet which you can cast to a list. You can also add flat=True to values_list to flatten the results.

See also: Get distinct values of Queryset by field

javascript - pass selected value from popup window to parent window input box

(parent window)

<html> 
<script language="javascript"> 
function openWindow() { 
  window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
} 
</script> 
<body> 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 
</form> 
</body> 
</html>

(child window)

<html> 
<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
  window.close();
} 
</script> 
<body> 
<form> 
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 
</form> 
</body> 
</html>

http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

How to get query params from url in Angular 2?

now it is:

this.activatedRoute.queryParams.subscribe((params: Params) => {
  console.log(params);
});

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

Where can I find a list of escape characters required for my JSON ajax return type?

The JSON reference states:

 any-Unicode-character-
     except-"-or-\\-or-
     control-character

Then lists the standard escape codes:

  \" Standard JSON quote
  \\ Backslash (Escape char)
  \/ Forward slash
  \b Backspace (ascii code 08)
  \f Form feed (ascii code 0C)
  \n Newline
  \r Carriage return
  \t Horizontal Tab
  \u four-hex-digits

From this I assumed that I needed to escape all the listed ones and all the other ones are optional. You can choose to encode all characters into \uXXXX if you so wished, or you could only do any non-printable 7-bit ASCII characters or characters with Unicode value not in \u0020 <= x <= \u007E range (32 - 126). Preferably do the standard characters first for shorter escape codes and thus better readability and performance.

Additionally you can read point 2.5 (Strings) from RFC 4627.

You may (or may not) want to (further) escape other characters depending on where you embed that JSON string, but that is outside the scope of this question.

How to get the mysql table columns data type?

ResultSet rs = Sstatement.executeQuery("SELECT * FROM Table Name");

ResultSetMetaData rsMetaData = rs.getMetaData();

int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);

for (int i = 1; i <= numberOfColumns; i++) {
 System.out.println("column number " + i);

  System.out.println(rsMetaData.getColumnTypeName(i));
}

A regex for version number parsing

^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$

Perhaps a more concise one could be :

^(?:(\d+)\.){0,2}(\*|\d+)$

This can then be enhanced to 1.2.3.4.5.* or restricted exactly to X.Y.Z using * or {2} instead of {0,2}

Hidden features of Windows batch files

Line continuation:

call C:\WINDOWS\system32\ntbackup.exe ^
    backup ^
    /V:yes ^
    /R:no ^
    /RS:no ^
    /HC:off ^
    /M normal ^
    /L:s ^
    @daily.bks ^
    /F daily.bkf

Casting LinkedHashMap to Complex Object

I had similar Issue where we have GenericResponse object containing list of values

 ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
                redisMatchedDriverUrl,
                HttpMethod.POST,
                requestEntity,
                ResponseDTO.class
        );

Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects

 ObjectMapper mapper = new ObjectMapper();

 List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

SQL Server : Arithmetic overflow error converting expression to data type int

On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.

Is nested function a good approach when required by only one function?

You can use it to avoid defining global variables. This gives you an alternative for other designs. 3 designs presenting a solution to a problem.

A) Using functions without globals

def calculate_salary(employee, list_with_all_employees):
    x = _calculate_tax(list_with_all_employees)

    # some other calculations done to x
    pass

    y = # something 

    return y

def _calculate_tax(list_with_all_employees):
    return 1.23456 # return something

B) Using functions with globals

_list_with_all_employees = None

def calculate_salary(employee, list_with_all_employees):

    global _list_with_all_employees
    _list_with_all_employees = list_with_all_employees

    x = _calculate_tax()

    # some other calculations done to x
    pass

    y = # something

    return y

def _calculate_tax():
    return 1.23456 # return something based on the _list_with_all_employees var

C) Using functions inside another function

def calculate_salary(employee, list_with_all_employees):

    def _calculate_tax():
        return 1.23456 # return something based on the list_with_a--Lemployees var

    x = _calculate_tax()

    # some other calculations done to x
    pass
    y = # something 

    return y

Solution C) allows to use variables in the scope of the outer function without having the need to declare them in the inner function. Might be useful in some situations.

Java get String CompareTo as a comparator object

Regarding Nambari's answer there was a mistake. If you compare values using double equal sign == program will never reach compare method, unless someone will use new keyword to create String object which is not the best practice. This might be a bit better solution:

public int compare(String o1, String o2) {
        if (o1 == null && o2 == null){return 0;}
        if (o1 == null) { return -1;}
        if (o2 == null) { return 1;}
        return o1.compareTo(o2);
    }

P.S. Thanks for comments ;)

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

Javascript checkbox onChange

Javascript

  // on toggle method
  // to check status of checkbox
  function onToggle() {
    // check if checkbox is checked
    if (document.querySelector('#my-checkbox').checked) {
      // if checked
      console.log('checked');
    } else {
      // if unchecked
      console.log('unchecked');
    }
  }

HTML

<input id="my-checkbox" type="checkbox" onclick="onToggle()">

Date format in dd/MM/yyyy hh:mm:ss

SELECT FORMAT(your_column_name,'dd/MM/yyyy hh:mm:ss') FROM your_table_name

Example-

SELECT FORMAT(GETDATE(),'dd/MM/yyyy hh:mm:ss')

How to sum array of numbers in Ruby?

Also allows for [1,2].sum{|x| x * 2 } == 6:

# http://madeofcode.com/posts/74-ruby-core-extension-array-sum
class Array
  def sum(method = nil, &block)
    if block_given?
      raise ArgumentError, "You cannot pass a block and a method!" if method
      inject(0) { |sum, i| sum + yield(i) }
    elsif method
      inject(0) { |sum, i| sum + i.send(method) }
    else
      inject(0) { |sum, i| sum + i }
    end
  end
end

Using floats with sprintf() in embedded C

Many embedded systems have a limited snprintf function that doesn't handle floats. I wrote this, and it does the trick fairly efficiently. I chose to use 64-bit unsigned integers to be able to handle large floats, so feel free to reduce them down to 16-bit or whatever needs you may have with limited resources.

#include <stdio.h>   // for uint64_t support.


int  snprintf_fp( char destination[], size_t available_chars, int decimal_digits,
                  char tail[], float source_number )
{
    int   chars_used  = 0;    // This will be returned.


    if ( available_chars > 0 )
    {
        // Handle a negative sign.
        if ( source_number < 0 )
        {
            // Make it positive
            source_number = 0 - source_number;
            destination[ 0 ] = '-';
            ++chars_used;
        }

        // Handle rounding
        uint64_t zeros = 1;
        for ( int i = decimal_digits; i > 0; --i )
            zeros *= 10;

        uint64_t source_num = (uint64_t)( ( source_number * (float)zeros ) + 0.5f );

        // Determine sliding divider max position.
        uint64_t  div_amount = zeros;       // Give it a head start
        while ( ( div_amount * 10 ) <= source_num )
            div_amount *= 10;

        // Process the digits
        while ( div_amount > 0 )
        {
            uint64_t whole_number = source_num / div_amount;
            if ( chars_used < (int)available_chars )
            {
                destination[ chars_used ] = '0' + (char)whole_number;
                ++chars_used;

                if ( ( div_amount == zeros ) && ( zeros > 1 ) )
                {
                    destination[ chars_used ] = '.';
                    ++chars_used;
                }
            }
            source_num -= ( whole_number * div_amount );
            div_amount /= 10;
        }


        // Store the zero.
        destination[ chars_used ] = 0;

        // See if a tail was specified.
        size_t tail_len = strlen( tail );

        if ( ( tail_len > 0 ) && ( tail_len + chars_used < available_chars ) )
        {
            for ( size_t i = 0; i <= tail_len; ++i )
                destination[ chars_used + i ] = tail[ i ];
            chars_used += tail_len;
        }
    }

    return chars_used;
}

main()
{
    #define TEMP_BUFFER_SIZE 30
    char temp_buffer[ TEMP_BUFFER_SIZE ];
    char  degrees_c[] = { (char)248, 'C', 0 };
    float  float_temperature = 26.845f;

    int len = snprintf_fp( temp_buffer, TEMP_BUFFER_SIZE, 2, degrees_c, float_temperature );
}

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

How to encrypt String in Java

You might want to consider some automated tool to do the encryption / decryption code generation eg. https://www.stringencrypt.com/java-encryption/

It can generate different encryption and decryption code each time for the string or file encryption.

It's pretty handy when it comes to fast string encryption without using RSA, AES etc.

Sample results:

// encrypted with https://www.stringencrypt.com (v1.1.0) [Java]
// szTest = "Encryption in Java!"
String szTest = "\u9E3F\uA60F\uAE07\uB61B\uBE1F\uC62B\uCE2D\uD611" +
                "\uDE03\uE5FF\uEEED\uF699\uFE3D\u071C\u0ED2\u1692" +
                "\u1E06\u26AE\u2EDC";

for (int iatwS = 0, qUJQG = 0; iatwS < 19; iatwS++)
{
        qUJQG = szTest.charAt(iatwS);
        qUJQG ++;
        qUJQG = ((qUJQG << 5) | ( (qUJQG & 0xFFFF) >> 11)) & 0xFFFF;
        qUJQG -= iatwS;
        qUJQG = (((qUJQG & 0xFFFF) >> 6) | (qUJQG << 10)) & 0xFFFF;
        qUJQG ^= iatwS;
        qUJQG -= iatwS;
        qUJQG = (((qUJQG & 0xFFFF) >> 3) | (qUJQG << 13)) & 0xFFFF;
        qUJQG ^= 0xFFFF;
        qUJQG ^= 0xB6EC;
        qUJQG = ((qUJQG << 8) | ( (qUJQG & 0xFFFF) >> 8)) & 0xFFFF;
        qUJQG --;
        qUJQG = (((qUJQG & 0xFFFF) >> 5) | (qUJQG << 11)) & 0xFFFF;
        qUJQG ++;
        qUJQG ^= 0xFFFF;
        qUJQG += iatwS;
        szTest = szTest.substring(0, iatwS) + (char)(qUJQG & 0xFFFF) + szTest.substring(iatwS + 1);
}

System.out.println(szTest);

We use it all the time in our company.

Create ul and li elements in javascript.

Use the CSS property list-style-position to position the bullet:

list-style-position:inside /* or outside */;

Batch not-equal (inequality) operator

NEQ is usually used for numbers and == is typically used for string comparison.

I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.

I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?

How to Create simple drag and Drop in angularjs

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

Code is here: http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

Select element based on multiple classes

You mean two classes? "Chain" the selectors (no spaces between them):

.class1.class2 {
    /* style here */
}

This selects all elements with class1 that also have class2.

In your case:

li.left.ui-class-selector {

}

Official documentation : CSS2 class selectors.


As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

Java SimpleDateFormat for time zone with a colon separator?

Since an example of Apache FastDateFormat(click for the documentations of versions:2.6and3.5) is missing here, I am adding one for those who may need it. The key here is the pattern ZZ(2 capital Zs).

import java.text.ParseException
import java.util.Date;
import org.apache.commons.lang3.time.FastDateFormat;
public class DateFormatTest throws ParseException {
    public static void main(String[] args) {
        String stringDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ";
        FastDateFormat fastDateFormat = FastDateFormat.getInstance(stringDateFormat);
        System.out.println("Date formatted into String:");
        System.out.println(fastDateFormat.format(new Date()));
        String stringFormattedDate = "2016-11-22T14:30:14+05:30";
        System.out.println("String parsed into Date:");
        System.out.println(fastDateFormat.parse(stringFormattedDate));
    }
}

Here is the output of the code:

Date formatted into String:
2016-11-22T14:52:17+05:30
String parsed into Date:
Tue Nov 22 14:30:14 IST 2016

Note: The above code is of Apache Commons' lang3. The class org.apache.commons.lang.time.FastDateFormat does not support parsing, and it supports only formatting. For example, the output of the following code:

import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang.time.FastDateFormat;
public class DateFormatTest {
    public static void main(String[] args) throws ParseException {
        String stringDateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ";
        FastDateFormat fastDateFormat = FastDateFormat.getInstance(stringDateFormat);
        System.out.println("Date formatted into String:");
        System.out.println(fastDateFormat.format(new Date()));
        String stringFormattedDate = "2016-11-22T14:30:14+05:30";
        System.out.println("String parsed into Date:");
        System.out.println(fastDateFormat.parseObject(stringFormattedDate));
    }
}

will be this:

Date formatted into String:
2016-11-22T14:55:56+05:30
String parsed into Date:
Exception in thread "main" java.text.ParseException: Format.parseObject(String) failed
    at java.text.Format.parseObject(Format.java:228)
    at DateFormatTest.main(DateFormatTest.java:12)

Progress during large file copy (Copy-Item & Write-Progress?)

cmd /c copy /z src dest

not pure PowerShell, but executable in PowerShell and it displays progress in percents

How do I get the RootViewController from a pushed controller?

This worked for me:

When my root view controller is embedded in a navigation controller:

UINavigationController * navigationController = (UINavigationController *)[[[[UIApplication sharedApplication] windows] firstObject] rootViewController];
RootViewController * rootVC = (RootViewController *)[[navigationController viewControllers] firstObject];

Remember that keyWindow is deprecated.

What is the difference between XML and XSD?

Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML could be used for some particular purposes. The XML is only containing data in suitable format and structure.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Send a ping to each IP on a subnet

I just came around this question, but the answers did not satisfy me. So i rolled my own:

echo $(seq 254) | xargs -P255 -I% -d" " ping -W 1 -c 1 192.168.0.% | grep -E "[0-1].*?:"
  • Advantage 1: You don't need to install any additional tool
  • Advantage 2: It's fast. It does everything in Parallel with a timout for every ping of 1s ("-W 1"). So it will finish in 1s :)
  • Advantage 3: The output is like this
64 bytes from 192.168.0.16: icmp_seq=1 ttl=64 time=0.019 ms
64 bytes from 192.168.0.12: icmp_seq=1 ttl=64 time=1.78 ms
64 bytes from 192.168.0.21: icmp_seq=1 ttl=64 time=2.43 ms
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=1.97 ms
64 bytes from 192.168.0.11: icmp_seq=1 ttl=64 time=619 ms

Edit: And here is the same as script, for when your xargs do not have the -P flag, as is the case in openwrt (i just found out)

for i in $(seq 255);
do
 ping -W 1 -c 1 10.0.0.$i | grep 'from' &
done

javascript: pause setTimeout();

You can do like below to make setTimeout pausable on server side (Node.js)

const PauseableTimeout = function(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        global.clearTimeout(timerId);
        remaining -= Date.now() - start;
    };

    this.resume = function() {
        start = Date.now();
        global.clearTimeout(timerId);
        timerId = global.setTimeout(callback, remaining);
    };

    this.resume();
};

and you can check it as below

var timer = new PauseableTimeout(function() {
    console.log("Done!");
}, 3000);
setTimeout(()=>{
    timer.pause();
    console.log("setTimeout paused");
},1000);

setTimeout(()=>{
    console.log("setTimeout time complete");
},3000)

setTimeout(()=>{
    timer.resume();
    console.log("setTimeout resume again");
},5000)

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

There's a little bit more information about the semantics of these errors in RFC 2616, which documents HTTP 1.1.

Personally, I would probably use 400 Bad Request, but this is just my personal opinion without any factual support.

API pagination best practices

I think currently your api's actually responding the way it should. The first 100 records on the page in the overall order of objects you are maintaining. Your explanation tells that you are using some kind of ordering ids to define the order of your objects for pagination.

Now, in case you want that page 2 should always start from 101 and end at 200, then you must make the number of entries on the page as variable, since they are subject to deletion.

You should do something like the below pseudocode:

page_max = 100
def get_page_results(page_no) :

    start = (page_no - 1) * page_max + 1
    end = page_no * page_max

    return fetch_results_by_id_between(start, end)

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

Can I set the height of a div based on a percentage-based width?

I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo

.container {
  position: relative;
  max-width:100vh;
  max-height:100%;
  margin:0 auto;
  overflow: hidden;
}
.container:before {
  content: "";
  display: block;
  margin-top: 100%;
}
.child {
  position: absolute;
  top: 0;
  left: 0;
}

Support table for viewport units

I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.

pass **kwargs argument to another function with **kwargs

The ** syntax tells Python to collect keyword arguments into a dictionary. The save2 is passing it down as a non-keyword argument (a dictionary object). The openX is not seeing any keyword arguments so the **args doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX function.

def openX(filename, mode, kwargs):
    pass

If statement in select (ORACLE)

SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
    --  <add any columns to outer select from inner query> 
  FROM
 (  -- your query here --
   select 'CARAT Issue Open' issue_comment, ...., ..., 
          substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
          case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
     from ....
    where UPPER(ISSUE_STATUS) like '%OPEN%'
 )
 WHERE... -- optional --

What's the difference between <b> and <strong>, <i> and <em>?

b or i means you want the text to be rendered as bold or italics. strong or em means you want the text to be rendered in a way that the user understands as "important". The default is to render strong as bold and em as italics, but some other cultures might use a different mapping.

Like strings in a program, b and i would be "hard coded" while strong and em would be "localized".

How to check if an app is installed from a web-page on an iPhone?

iOS Safari has a feature that allows you to add a "smart" banner to your webpage that will link either to your app, if it is installed, or to the App Store.

You do this by adding a meta tag to the page. You can even specify a detailed app URL if you want the app to do something special when it loads.

Details are at Apple's Promoting Apps with Smart App Banners page.

The mechanism has the advantages of being easy and presenting a standardized banner. The downside is that you don't have much control over the look or location. Also, all bets are off if the page is viewed in a browser other than Safari.

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Delete all but the most recent X files in bash

(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm

This version supports names with spaces:

(ls -t|head -n 5;ls)|sort|uniq -u|sed -e 's,.*,"&",g'|xargs rm

Check if a string contains a number

alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and 
re.search(r'[a-z]',x)]

print(alp_num)

This returns all the string that has both alphabets and numbers in it. isalpha() returns the string with all digits or all characters.

Efficient way to update all rows in a table

The usual way is to use UPDATE:

UPDATE mytable
   SET new_column = <expr containing old_column>

You should be able to do this is a single transaction.

Difference between WebStorm and PHPStorm

Essentially, PHPStorm = WebStorm + PHP, SQL and more.

BUT (and this is a very important "but") because it is capable of parsing so much more, it quite often fails to parse Node.js dependencies, as they (probably) conflict with some other syntax it is capable of parsing.

The most notable example of that would be Mongoose model definition, where WebStorm easily recognizes mongoose.model method, whereas PHPStorm marks it as unresolved as soon as you connect Node.js plugin.

Surprisingly, it manages to resolve the method if you turn the plugin off, but leave the core modules connected, but then it cannot be used for debugging. And this happens to quite a few methods out there.

All this goes for PHPStorm 8.0.1, maybe in later releases this annoying bug would be fixed.

Sort columns of a dataframe by column name

An alternative option is to use str_sort() from library stringr, with the argument numeric = TRUE. This will correctly order column that include numbers not just alphabetically:

str_sort(c("V3", "V1", "V10"), numeric = TRUE)

# [1] V1 V3 V11

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

Stripping everything but alphanumeric chars from a string in Python

If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..

s = """An... essay is, generally, a piece of writing that gives the author's own 
argument — but the definition is vague, 
overlapping with those of a paper, an article, a pamphlet, and a short story. Essays 
have traditionally been 
sub-classified as formal and informal. Formal essays are characterized by "serious 
purpose, dignity, logical 
organization, length," whereas the informal essay is characterized by "the personal 
element (self-revelation, 
individual tastes and experiences, confidential manner), humor, graceful style, 
rambling structure, unconventionality 
or novelty of theme," etc.[1]"""

d = {}      # creating empty dic      
words = s.split() # spliting string and stroing in list
for word in words:
    new_word = ''
    for c in word:
        if c.isalnum(): # checking if indiviual chr is alphanumeric or not
            new_word = new_word + c
    print(new_word, end=' ')
    # if new_word not in d:
    #     d[new_word] = 1
    # else:
    #     d[new_word] = d[new_word] +1
print(d)

please rate this if this answer is useful!

Return multiple values from a SQL Server function

Here's the Query Analyzer template for an in-line function - it returns 2 values by default:

-- =============================================  
-- Create inline function (IF)  
-- =============================================  
IF EXISTS (SELECT *   
   FROM   sysobjects   
   WHERE  name = N'<inline_function_name, sysname, test_function>')  
DROP FUNCTION <inline_function_name, sysname, test_function>  
GO  

CREATE FUNCTION <inline_function_name, sysname, test_function>   
(<@param1, sysname, @p1> <data_type_for_param1, , int>,   
 <@param2, sysname, @p2> <data_type_for_param2, , char>)  
RETURNS TABLE   
AS  
RETURN SELECT   @p1 AS c1,   
        @p2 AS c2  
GO  

-- =============================================  
-- Example to execute function  
-- =============================================  
SELECT *   
FROM <owner, , dbo>.<inline_function_name, sysname, test_function>   
    (<value_for_@param1, , 1>,   
     <value_for_@param2, , 'a'>)  
GO  

Root element is missing

Hi this is odd way but try it once

  1. Read the file content into a string
  2. print the string and check whether you are getting proper XML or not
  3. you can use XMLDocument.LoadXML(xmlstring)

I try with your code and same XML without adding any XML declaration it works for me

XmlDocument doc = new XmlDocument();
        doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");
        XmlNodeList nodes = doc.GetElementsByTagName("Product");
        XmlNode node = null;
        foreach (XmlNode n in nodes)
        {
            Console.WriteLine("HI");
        }

Its working perfectly fine

eclipse stuck when building workspace

Sometimes the problem seems to be fixed by killing other programs which have files open from the project folder.

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

Netbeans how to set command line arguments in Java

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel

How can I completely uninstall nodejs, npm and node in Ubuntu

I was crazy to delete node and npm and nodejs from my Ubuntu 14.04 but with this steps you will remove it:

sudo apt-get uninstall nodejs npm node
sudo apt-get remove nodejs npm node

If you uninstall correctly and it is still there, check these links:

You can also try using find:

find / -name "node"

Although since that is likely to take a long time and return a lot of confusing false positives, you may want to search only PATH locations:

find $(echo $PATH | sed 's/:/ /g') -name "node"

It would probably be in /usr/bin/node or /usr/local/bin. After finding it, you can delete it using the correct path, eg:

sudo rm /usr/bin/node

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

You can use the following maven dependency in your pom file. Otherwise, you can download the following two jars from net and add it to your build path.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.4</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.4</version>
</dependency>

This is copied from my working project. First make sure it is working in your project. Then you can change the versions to use any other(versions) compatible jars.

For AggCat, you can refer the POM file of the sample java application.

https://github.com/IntuitDeveloperRelations/IPP_Sample_Code/blob/master/CustomerAccountData/Java/AggCatSampleApplication/pom.xml

Thanks

Why is processing a sorted array faster than processing an unsorted array?

The above behavior is happening because of Branch prediction.

To understand branch prediction one must first understand Instruction Pipeline:

Any instruction is broken into a sequence of steps so that different steps can be executed concurrently in parallel. This technique is known as instruction pipeline and this is used to increase throughput in modern processors. To understand this better please see this example on Wikipedia.

Generally, modern processors have quite long pipelines, but for ease let's consider these 4 steps only.

  1. IF -- Fetch the instruction from memory
  2. ID -- Decode the instruction
  3. EX -- Execute the instruction
  4. WB -- Write back to CPU register

4-stage pipeline in general for 2 instructions. 4-stage pipeline in general

Moving back to the above question let's consider the following instructions:

                        A) if (data[c] >= 128)
                                /\
                               /  \
                              /    \
                        true /      \ false
                            /        \
                           /          \
                          /            \
                         /              \
              B) sum += data[c];          C) for loop or print().

Without branch prediction, the following would occur:

To execute instruction B or instruction C the processor will have to wait till the instruction A doesn't reach till EX stage in the pipeline, as the decision to go to instruction B or instruction C depends on the result of instruction A. So the pipeline will look like this.

when if condition returns true: enter image description here

When if condition returns false: enter image description here

As a result of waiting for the result of instruction A, the total CPU cycles spent in the above case (without branch prediction; for both true and false) is 7.

So what is branch prediction?

Branch predictor will try to guess which way a branch (an if-then-else structure) will go before this is known for sure. It will not wait for the instruction A to reach the EX stage of the pipeline, but it will guess the decision and go to that instruction (B or C in case of our example).

In case of a correct guess, the pipeline looks something like this: enter image description here

If it is later detected that the guess was wrong then the partially executed instructions are discarded and the pipeline starts over with the correct branch, incurring a delay. The time that is wasted in case of a branch misprediction is equal to the number of stages in the pipeline from the fetch stage to the execute stage. Modern microprocessors tend to have quite long pipelines so that the misprediction delay is between 10 and 20 clock cycles. The longer the pipeline the greater the need for a good branch predictor.

In the OP's code, the first time when the conditional, the branch predictor does not have any information to base up prediction, so the first time it will randomly choose the next instruction. Later in the for loop, it can base the prediction on the history. For an array sorted in ascending order, there are three possibilities:

  1. All the elements are less than 128
  2. All the elements are greater than 128
  3. Some starting new elements are less than 128 and later it become greater than 128

Let us assume that the predictor will always assume the true branch on the first run.

So in the first case, it will always take the true branch since historically all its predictions are correct. In the 2nd case, initially it will predict wrong, but after a few iterations, it will predict correctly. In the 3rd case, it will initially predict correctly till the elements are less than 128. After which it will fail for some time and the correct itself when it sees branch prediction failure in history.

In all these cases the failure will be too less in number and as a result, only a few times it will need to discard the partially executed instructions and start over with the correct branch, resulting in fewer CPU cycles.

But in case of a random unsorted array, the prediction will need to discard the partially executed instructions and start over with the correct branch most of the time and result in more CPU cycles compared to the sorted array.

req.query and req.param in ExpressJS

I would suggest using following

req.param('<param_name>')

req.param("") works as following

Lookup is performed in the following order:

req.params
req.body
req.query

Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

Ref:http://expressjs.com/4x/api.html#req.param

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

Unsigned keyword in C++

You can read about the keyword unsigned in the C++ Reference.

There are two different types in this matter, signed and un-signed. The default for integers is signed which means that they can have negative values.

On a 32-bit system an integer is 32 Bit which means it can contain a value of ~4 billion.

And when it is signed, this means you need to split it, leaving -2 billion to +2 billion.

When it is unsigned however the value cannot contain any negative numbers, so for integers this would mean 0 to +4 billion.

There is a bit more informationa bout this on Wikipedia.

Session state can only be used when enableSessionState is set to true either in a configuration

I have got this error only when debugging the ASP .Net Application.

I also had Session["mysession"] kind of variables added into my Watch of Visual Studio.

the issue was solved Once, I have removed the Session Variables from watch.

Using mysql concat() in WHERE clause?

There's a few things that could get in the way - is your data clean?

It could be that you have spaces at the end of the first name field, which then means you have two spaces between the firstname and lastname when you concat them? Using trim(first_name)/trim(last_name) will fix this - although the real fix is to update your data.

You could also this to match where two words both occur but not necessarily together (assuming you are in php - which the $search_term variable suggests you are)

$whereclauses=array();
$terms = explode(' ', $search_term);
foreach ($terms as $term) {
    $term = mysql_real_escape_string($term);
    $whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);

Passing html values into javascript functions

Try: if(parseInt(order)>0){....

codeigniter, result() vs. result_array()

result() is recursive in that it returns an std class object where as result_array() just returns a pure array, so result_array() would be choice regarding performance. There is very little difference in speed though.

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

dotnet ef not found in .NET Core 3

For me, The problem was solved after I close Visual Studio and Open it again

How can I trim leading and trailing white space?

To manipulate the white space, use str_trim() in the stringr package. The package has manual dated Feb 15, 2013 and is in CRAN. The function can also handle string vectors.

install.packages("stringr", dependencies=TRUE)
require(stringr)
example(str_trim)
d4$clean2<-str_trim(d4$V2)

(Credit goes to commenter: R. Cotton)

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

How to resolve Unneccessary Stubbing exception

Replace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

nginx 502 bad gateway

You can make nginx ignore client aborts using:

location / {
  proxy_ignore_client_abort on;
}

Java Interfaces/Implementation naming convention

Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:

IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations

The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.

I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

Entity Framework Migrations renaming tables and columns

For EF Core migrationBuilder.RenameColumn usually works fine but sometimes you have to handle indexes as well.

migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");

Example error message when updating database:

Microsoft.Data.SqlClient.SqlException (0x80131904): The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.

The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.

RENAME COLUMN Identifier failed because one or more objects access this column.

In this case you have to do the rename like this:

migrationBuilder.DropIndex(
    name: "IX_Questions_Identifier",
    table: "Questions");

migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");

migrationBuilder.CreateIndex(
    name: "IX_Questions_ChangedIdentifier",
    table: "Questions",
    column: "ChangedIdentifier",
    unique: true,
    filter: "[ChangedIdentifier] IS NOT NULL");

POI setting Cell Background to a Custom Color

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

How to execute a Python script from the Django shell?

As other answers indicate but don't explicitly state, what you may actually need is not necessarily to execute your script from the Django shell, but to access your apps without using the Django shell.

This differs a lot Django version to Django version. If you do not find your solution on this thread, answers here -- Django script to access model objects without using manage.py shell -- or similar searches may help you.

I had to begin my_command.py with

import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()

import project.app.models
#do things with my models, yay

and then ran python3 my_command.py

(Django 2.0.2)

"Could not load type [Namespace].Global" causing me grief

You need to set your Output path to bin\

Parameterize an SQL IN clause

You can do this in a reusable way by doing the following -

public static class SqlWhereInParamBuilder
{
    public static string BuildWhereInClause<t>(string partialClause, string paramPrefix, IEnumerable<t> parameters)
    {
        string[] parameterNames = parameters.Select(
            (paramText, paramNumber) => "@" + paramPrefix + paramNumber.ToString())
            .ToArray();

        string inClause = string.Join(",", parameterNames);
        string whereInClause = string.Format(partialClause.Trim(), inClause);

        return whereInClause;
    }

    public static void AddParamsToCommand<t>(this SqlCommand cmd, string paramPrefix, IEnumerable<t> parameters)
    {
        string[] parameterValues = parameters.Select((paramText) => paramText.ToString()).ToArray();

        string[] parameterNames = parameterValues.Select(
            (paramText, paramNumber) => "@" + paramPrefix + paramNumber.ToString()
            ).ToArray();

        for (int i = 0; i < parameterNames.Length; i++)
        {
            cmd.Parameters.AddWithValue(parameterNames[i], parameterValues[i]);
        }
    }
}

For more details have a look at this blog post - Parameterized SQL WHERE IN clause c#

Install pdo for postgres Ubuntu

If you are using PHP 5.6, the command is:

sudo apt-get install php5.6-pgsql

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

How can I remove the string "\n" from within a Ruby string?

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

See here for more info

Alter MySQL table to add comments on columns

Script for all fields on database:

SELECT 
table_name,
column_name,
CONCAT('ALTER TABLE `',
        TABLE_SCHEMA,
        '`.`',
        table_name,
        '` CHANGE `',
        column_name,
        '` `',
        column_name,
        '` ',
        column_type,
        ' ',
        IF(is_nullable = 'YES', '' , 'NOT NULL '),
        IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default IN ('CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP()', 'NULL', 'b\'0\'', 'b\'1\''), column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
        IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
        extra,
        ' COMMENT \'',
        column_comment,
        '\' ;') as script
FROM
    information_schema.columns
WHERE
    table_schema = 'my_database_name'
ORDER BY table_name , column_name
  1. Export all to a CSV
  2. Open it on your favorite csv editor

Note: You can improve to only one table if you prefer

The solution given by @Rufinus is great but if you have auto increments it will break it.

How do you extract classes' source code from a dll file?

You can use Reflector and also use Add-In FileGenerator to extract source code into a project.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Query scopes may help you to let your code more readable.

http://laravel.com/docs/eloquent#query-scopes

Updating this answer with some example:

In your model, create scopes methods like this:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

Then, you can call this scopes while building your query:

$users = User::active()->that()->get();

How to hide element using Twitter Bootstrap and show it using jQuery?

Use the following snippet for Bootstrap 4, which extends jQuery:

(function( $ ) {

    $.fn.hideShow = function( action ) {

        if ( action.toUpperCase() === "SHOW") {
            // show
            if(this.hasClass("d-none"))
            {
                this.removeClass("d-none");
            }

            this.addClass("d-block");

        }

        if ( action.toUpperCase() === "HIDE" ) {
            // hide
            if(this.hasClass("d-block"))
            {
                this.removeClass("d-block");
            }

            this.addClass("d-none");
      }

          return this;
    };

}( jQuery ));
  1. Put the above code in a file. Let's suppose "myJqExt.js"
  2. Include the file after jQuery has been included.

  3. Use it using the syntax

    $().hideShow('hide');

    $().hideShow('show');

hope you guys find it helpful. :-)

Warning: Failed propType: Invalid prop `component` supplied to `Route`

In my case i leave my .js file empty means i never write anything in my .js file after that i was using it in my route so make function component or class component and finally export it will work

Select current date by default in ASP.Net Calendar control

Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

Git commit with no commit message

Git requires a commit to have a comment, otherwise it wont accept the commit.

You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.

class Child extends React.Component {
    constructor(){}
    dismiss() {
        this.props.unmountMe();
    } 
    render(){
        // code
    }
}

class Parent ...
    constructor(){
        super(props)
        this.state = {renderChild: true};
        this.handleChildUnmount = this.handleChildUnmount.bind(this);
    }
    handleChildUnmount(){
        this.setState({renderChild: false});
    }
    render(){
        // code
        {this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
    }

}

this is a very simple example. but you can see a rough way to pass through to the parent an action

That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render

I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.

EDIT: Here is how I set up a notification system using React/Redux/Typescript

Few things to note first. this is in typescript so you would need to remove the type declarations :)

I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.

The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol(). This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.

notification-actions.ts

import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';

interface IDispatchType {
    type: string;
    payload?: any;
    remove?: Symbol;
}

export const notifySuccess = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const notifyFailure = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const clearNotification = (notifyId: Symbol) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
    };
};

notification-reducer.ts

const defaultState = {
    userNotifications: []
};

export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
    switch (action.type) {
        case USER_SYSTEM_NOTIFICATION:
            const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
            if (_.has(action, 'remove')) {
                const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
                if (key) {
                    // mutate list and remove the specified item
                    list.splice(key, 1);
                }
            } else {
                list.push(action.payload);
            }
            return _.assign({}, state, { userNotifications: list });
    }
    return state;
};

app.tsx

in the base render for your application you would render the notifications

render() {
    const { systemNotifications } = this.props;
    return (
        <div>
            <AppHeader />
            <div className="user-notify-wrap">
                { _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
                    ? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
                    : null
                }
            </div>
            <div className="content">
                {this.props.children}
            </div>
        </div>
    );
}

user-notification.tsx

user notification class

/*
    Simple notification class.

    Usage:
        <SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
        these two functions are actions and should be props when the component is connect()ed

    call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
        this.props.notifySuccess('it Works!!!', 2);
        this.props.notifySuccess(<SomeComponentHere />, 15);
        this.props.notifyFailure(<div>You dun goofed</div>);

*/

interface IUserNotifyProps {
    data: any;
    clearNotification(notifyID: symbol): any;
}

export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
    public notifyRef = null;
    private timeout = null;

    componentDidMount() {
        const duration: number = _.get(this.props, 'data.duration', '');
       
        this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';

        
        // fallback incase the animation event doesn't fire
        const timeoutDuration = (duration * 1000) + 500;
        this.timeout = setTimeout(() => {
            this.notifyRef.classList.add('hidden');
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }, timeoutDuration);

        TransitionEvents.addEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    componentWillUnmount() {
        clearTimeout(this.timeout);

        TransitionEvents.removeEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    onAmimationComplete = (e) => {
        if (_.get(e, 'animationName') === 'fadeInAndOut') {
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }
    }
    handleCloseClick = (e) => {
        e.preventDefault();
        this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
    }
    assignNotifyRef = target => this.notifyRef = target;
    render() {
        const {data, clearNotification} = this.props;
        return (
            <div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
                {!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
                <div className="close-message" onClick={this.handleCloseClick}>+</div>
            </div>
        );
    }
}

How much faster is C++ than C#?

C/C++ can perform vastly better in programs where there are either large arrays or heavy looping/iteration over arrays (of any size). This is the reason that graphics are generally much faster in C/C++, because heavy array operations underlie almost all graphics operations. .NET is notoriously slow in array indexing operations due to all the safety checks, and this is especially true for multi-dimensional arrays (and, yes, rectangular C# arrays are even slower than jagged C# arrays).

The bonuses of C/C++ are most pronounced if you stick directly with pointers and avoid Boost, std::vector and other high-level containers, as well as inline every small function possible. Use old-school arrays whenever possible. Yes, you will need more lines of code to accomplish the same thing you did in Java or C# as you avoid high-level containers. If you need a dynamically sized array, you will just need to remember to pair your new T[] with a corresponding delete[] statement (or use std::unique_ptr)—the price for the extra speed is that you must code more carefully. But in exchange, you get to rid yourself of the overhead of managed memory / garbage collector, which can easily be 20% or more of the execution time of heavily object-oriented programs in both Java and .NET, as well as those massive managed memory array indexing costs. C++ apps can also benefit from some nifty compiler switches in certain specific cases.

I am an expert programmer in C, C++, Java, and C#. I recently had the rare occasion to implement the exact same algorithmic program in the latter 3 languages. The program had a lot of math and multi-dimensional array operations. I heavily optimized this in all 3 languages. The results were typical of what I normally see in less rigorous comparisons: Java was about 1.3x faster than C# (most JVMs are more optimized than the CLR), and the C++ raw pointer version came in about 2.1x faster than C#. Note that the C# program only used safe code—it is my opinion that you might as well code it in C++ before using the unsafe keyword.

Lest anyone think I have something against C#, I will close by saying that C# is probably my favorite language. It is the most logical, intuitive and rapid development language I've encountered so far. I do all my prototyping in C#. The C# language has many small, subtle advantages over Java (yes, I know Microsoft had the chance to fix many of Java's shortcomings by entering the game late and arguably copying Java). Toast to Java's Calendar class anyone? If Microsoft ever spends real effort to optimize the CLR and the .NET JITter, C# could seriously take over. I'm honestly surprised they haven't already—they did so many things right in the C# language, why not follow it up with heavy-hitting compiler optimizations? Maybe if we all beg.

Detect when input has a 'readonly' attribute

In vanilla/pure javascript you can check as following -

var field = document.querySelector("input[name='fieldName']");
if(field.readOnly){
 alert("foo");
}

C# ListView Column Width Auto

You can use something like this, passing the ListView you want in param

    private void AutoSizeColumnList(ListView listView)
    {
        //Prevents flickering
        listView.BeginUpdate();

        Dictionary<int, int> columnSize = new Dictionary<int,int>();

        //Auto size using header
        listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

        //Grab column size based on header
        foreach(ColumnHeader colHeader in listView.Columns )
            columnSize.Add(colHeader.Index, colHeader.Width);

        //Auto size using data
        listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

        //Grab comumn size based on data and set max width
        foreach (ColumnHeader colHeader in listView.Columns)
        {
            int nColWidth;
            if (columnSize.TryGetValue(colHeader.Index, out nColWidth))
                colHeader.Width = Math.Max(nColWidth, colHeader.Width);
            else
                //Default to 50
                colHeader.Width = Math.Max(50, colHeader.Width);
        }

        listView.EndUpdate();
    }

Angular2: custom pipe could not be found

A really dumb answer (I'll vote myself down in a minute), but this worked for me:

After adding your pipe, if you're still getting the errors and are running your Angular site using "ng serve", stop it... then start it up again.

For me, none of the other suggestions worked, but simply stopping, then restarting "ng serve" was enough to make the error go away.

Strange.

How can I parse JSON with C#?

As was answered here - Deserialize JSON into C# dynamic object?

It's pretty simple using Json.NET:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Or using Newtonsoft.Json.Linq :

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

Java way to check if a string is palindrome

import java.util.Scanner;

public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;

public void allSubstrings(String s){        
    for(int i=0;i<s.length();i++){
        for(int j=1;j<=s.length()-i;j++){
            String subString=s.substring(i, i+j);  
            palindrome(subString);             
        }
    }
        }   
public void palindrome(String sub){
    System.out.println("String to b checked is "+sub);
    StringBuilder sb=new StringBuilder();
    sb.append(sub);     // append string to string builder 
    sb.reverse();        
    if(sub.equals(sb.toString())){                        // palindrome condition 
        System.out.println("the given String :"+sub+" is a palindrome");
        longestPalindrome(sub);
    }
    else{
        System.out.println("the string "+sub+"iss not a palindrome");
    }
        }
public void longestPalindrome(String s){
            if(s.length()>longest){                 
        longest=s.length();
        longestPalindrome=s;

    }
    else if (s.length()==longest){    
        oldPalindrome=longestPalindrome;
        longestPalindrome=s;

    }




}

public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();

    Scanner sc=new Scanner(System.in);    
    System.out.println("Enter the String ::");
    String s=sc.nextLine(); 
    fp.allSubstrings(s);      
    sc.close();
    if(fp.oldPalindrome.length()>0){
    System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");  
    }
    else{
        System.out.println(longestPalindrome+":is the longest palindrome`````");
    }}
}

Identifier is undefined

You may also be missing using namespace std;

Removing array item by value

to remove $rm_val from $arr

unset($arr[array_search($rm_val, $arr)]);

How to get current time in milliseconds in PHP?

As other have stated, you can use microtime() to get millisecond precision on timestamps.

From your comments, you seem to want it as a high-precision UNIX Timestamp. Something like DateTime.Now.Ticks in the .NET world.

You may use the following function to do so:

function millitime() {
  $microtime = microtime();
  $comps = explode(' ', $microtime);

  // Note: Using a string here to prevent loss of precision
  // in case of "overflow" (PHP converts it to a double)
  return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
}

Eclipse HotKey: how to switch between tabs?

  • CTRL+E (for a list of editor)
  • CTRL+F6 (for switching to the next editor through a list)
    You can assign another shortcut to the 'Next Editor' key.

are the two official shortcuts, but they both involve a list being displayed.

CTRL+Page Up / CTRL+Page Down can cycle through editors without displaying a list.

What is interesting with that last set of shortcuts is:
they are not listed in the Eclipse Keys shortcuts to be defined.
They may be inherited from the multipage editor, making them an OS specific shortcut.


Regarding shortcuts on Mac OS (OSX), Matt Ball complained in Sept. 2011 to not being able to remap CTRL+Page Up/CTRL+Page Down:

It drives me nuts to not be able to flip through open tabs as I can in pretty much every other tabbed program in OS X (?-Left and ?-Right).

Well, in March 2012, Arthur replied:

, I've just downloaded the latest version of Eclipse (3.7+). I've been able to bind "Previous/Next tab" to (?-Left and ?-Right) when in Editor, which I'm pretty sure I couldn't do before.
So I guess they heard you.
It works just as you expect, tabs going from left to right and vice-versa, not on a history basis or some nonsense like that.

Matt Ball confirms:

oh wow, selecting "Editing Java Source" actually worked!
Now, unfortunately this means that I'm SOL if I nav into a non-Java file (JSP, XML, JS, etc.).
The fix for this is to "copy command" for this pair, and select all the "whens" that I want.
So far it's at least working beautifully for Java and JSP files.
This is a major PITA to set up, but it's just a one-time thing.

His exported preferences are available here for you to try.
Once imported, you should see, for all the relevant types of document:

Mac Os key bindings

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

What is @ModelAttribute in Spring MVC?

Take any web application whether it is Gmail or Facebook or Instagram or any other web application, it's all about exchanging data or information between the end user and the application or the UI and the back end application. Even in Spring MVC world there are two ways to exchange data:

  1. from the Controller to the UI, and
  2. from the UI to the Controller.

What we are interested here is how the data is communicated from the UI to Controller. This can also be done in 2 ways:

  1. Using an HTML Form
  2. Using Query Parameters.

Using an HTML Form: Consider the below scenario,

Form Submission Representation

When we submit the form data from the web browser, we can access that data in our Controller class as an object. When we submit an HTML form, the Spring Container does four things. It will,

  1. first read all the data that is submitted that comes in the request using the request.getParameter method.
  2. once it reads them, it will convert them into the appropriate Java type using integer.parseInt, double.parseDouble and all the other parse methods that are available based on the data type of the data.
  3. once parsed, it will create a object of the model class that we created. For example, in this scenario, it is the user information that is being submitted and we create a class called User, which the Container will create an object of and it will set all the values that come in automatically into that object.
  4. it will then handover that object by setting the values to the Controller.

To get this whole thing to work, we'll have to follow certain steps.

Internal working

We first need to define a model class, like User, in which the number of fields should exactly match the number of fields in the HTML form. Also, the names that we use in the HTML form should match the names that we have in the Java class. These two are very important. Names should match, the number of fields in the form should match the number of fields in the class that we create. Once we do that, the Container will automatically read the data that comes in, creates an object of this model, sets the values and it hands it over to the Controller. To read those values inside the Controller, we use the @ModelAttribute annotation on the method parameters. When we create methods in the Controller, we are going to use the @ModelAttribute and add a parameter to it which will automatically have this object given by the Container.

Here is an example code for registering an user:

@RequestMapping(value = "registerUser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") User user, ModelMap model) {
    model.addAttribute("user", user);
    return "regResult";
}

Hope this diagrammatic explanation helped!

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

Look for any DDL operation in the script. Maybe the user does not have access rights to run changes.

In my case it was SET IDENTITY_INSERT tblTableName ON

You can either add db_ddladmin for the whole database or for just the table to solve this issue (or change the script)

-- give the non-ddladmin user INSERT/SELECT as well as ALTER:
GRANT ALTER, INSERT, SELECT ON dbo.tblTableName TO user_name;

How can I convert a Timestamp into either Date or DateTime object?

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

How do I get the fragment identifier (value after hash #) from a URL?

Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...

// Helper Method Defined Here.
(function (helper, $) {
    // This is now a utility function to "Get the Document Hash"
    helper.getDocumentHash = function (urlString) {
        var hashValue = "";

        if (urlString.indexOf('#') != -1) {
            hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
        }
        return hashValue;
    };
})(this.helper = this.helper || {}, jQuery);

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

You are not getting value of $id=$_GET['id'];

And you are using it (before it gets initialised).

Use php's in built isset() function to check whether the variable is defied or not.

So, please update the line to:

$id = isset($_GET['id']) ? $_GET['id'] : '';

Change IPython/Jupyter notebook working directory

OS Windows 10 Python Anaconda 2018 ver

CHANGE WORKING DIRECTORY OF JUPYTER NOTEBOOK BY CONFIGURATION FILE:

  1. Open cmd prompt (or Anaconda Prompt), then type 'jupyter notebook --generate-config' and press enter

  2. This auto create a file 'jupyter_notebook_config' in the 'C:\Users\username.jupyter\' folder

  3. Look for the created file 'jupyter_notebook_config'and edit it.

  4. Find for #c.NotebookApp.notebook_dir = ''

  5. Put you're desired path inside double quote, it becomes ---> c.NotebookApp.notebook_dir = 'D:/my_folder/jupiter'

    • Note the forward slash (/) is used, and the comment (#) was remove.

Hence,

#c.NotebookApp.notebook_dir = '' 

Edit to becomes

c.NotebookApp.notebook_dir = 'D:/your/desired/path'
  1. Let's modify the path of the Jupyter Notebook shortcut icon 6.0 On start menu, right-click on the shortcut, open folder location. 6.1 Once inside the folder, recommended to create a copy of Jupyter shortcut, 6.2 right click on the new shortcut icon to open properties,

Finally,

6.3 on Target text box, remove %USERPROFILE% at the end of path, The very long path should end with jupyter-notebook-script.py

searcch my vid Jupyter Notebook - Change working folder path from default to desired path

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

How to split CSV files as per number of rows specified?

I have a one-liner answer (this example gives you 999 lines of data and one header row per file)

cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'

https://stackoverflow.com/a/53062251/401226

how to replace an entire column on Pandas.DataFrame

For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.

Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4

columns_to_overwrite = ["column_1", "column_3"]

First delete the columns that you intend to replace...

original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)

... then re-insert the columns, but using the values that you intended to overwrite

original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]

Get all variables sent with POST?

So, something like the $_POST array?

You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.

Codeigniter - multiple database connections

The best way is to use different database groups. If you want to keep using the master database as usual ($this->db) just turn off persistent connexion configuration option to your secondary database(s). Only master database should work with persistent connexion :

Master database

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Secondary database (notice pconnect is set to false)

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = FALSE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

Then you can use secondary databases as database objects while using master database as usual :

// use master dataabse
$users = $this->db->get('users');

// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
$stuff = $otherdb->get('struff');
$otherdb->insert_batch('users', $users->result_array());

// keep using master database as usual, for example insert stuff from other database
$this->db->insert_batch('stuff', $stuff->result_array());

Make browser window blink in task Bar

These users do want to be distracted when a new message arrives.

It sounds like you're writing an app for an internal company project.

You might want to investigate writing a small windows app in .net which adds a notify icon and can then do fancy popups or balloon popups or whatever, when they get new messages.

This isn't overly hard and I'm sure if you ask SO 'how do I show a tray icon' and 'how do I do pop up notifications' you'll get some great answers :-)

For the record, I'm pretty sure that (other than using an alert/prompt dialog box) you can't flash the taskbar in JS, as this is heavily windows specific, and JS really doesn't work like that. You may be able to use some IE-specific windows activex controls, but then you inflict IE upon your poor users. Don't do that :-(

Eloquent ORM laravel 5 Get Array of ids

From a Collection, another way you could do it would be:

$collection->pluck('id')->toArray()

This will return an indexed array, perfectly usable by laravel in a whereIn() query, for instance.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

 <android.support.design.widget.TabLayout
                    android:id="@+id/tabList"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    app:tabMode="scrollable"/>

How to generate an MD5 file hash in JavaScript?

You can use crypto-js.

To use crypto-js, you need to load core.js then md5.js .

A list of URLs are here https://cdnjs.com/libraries/crypto-js

cryptojs is also available in zip form here https://code.google.com/archive/p/crypto-js/downloads

There is an answer from answerer 'amal' in 2013, that is similar to this but a)his link to md5.js no longer works b)he didn't load core.js beforehand, which is necessary.

<html>    
  <head> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>

  <script>
     var hash = CryptoJS.MD5("Message");
     console.log(hash);
  </script>

  </head>
  <body>

  </body>
</html>

Invalid character in identifier

Carefully see your quotation, is this correct or incorrect! Sometime double quotation doesn’t work properly, it's depend on your keyboard layout.

Getting Google+ profile picture url with user_id

UPDATE: The method below DOES NOT WORK since 2015

It is possible to get the profile picture, and you can even set the size of it:

https://plus.google.com/s2/photos/profile/<user_id>?sz=<your_desired_size>

Example: My profile picture, with size set to 100 pixels:

https://plus.google.com/s2/photos/profile/116018066779980863044?sz=100

Usage with an image tag:

<img src="https://plus.google.com/s2/photos/profile/116018066779980863044?sz=100" width="100" height="100">

Hope you get it working!

How can I move HEAD back to a previous location? (Detached head) & Undo commits

This may not be a technical solution, but it works. (if anyone of your teammate has the same branch in local)

Let's assume your branch name as branch-xxx.

Steps to Solve:

  • Don't do update or pull - nothing
  • Just create a new branch (branch-yyy) from branch-xxx on his machine
  • That's all, all your existing changes will be in this new branch (branch-yyy). You can continue your work with this branch.

Note: Again, this is not a technical solution, but it will help for sure.

how to avoid extra blank page at end while printing?

I just encountered a case where changing from

    </div>
    <script src="addressofjavascriptfile.js"></script>
</body>
</html>

to

        <script src="addressofjavascriptfile.js"></script>
    </div>
</body>
</html>

fixed this problem.

What is the difference between active and passive FTP?

Active Mode—The client issues a PORT command to the server signaling that it will “actively” provide an IP and port number to open the Data Connection back to the client.

Passive Mode—The client issues a PASV command to indicate that it will wait “passively” for the server to supply an IP and port number, after which the client will create a Data Connection to the server.

There are lots of good answers above, but this blog post includes some helpful graphics and gives a pretty solid explanation: https://titanftp.com/2018/08/23/what-is-the-difference-between-active-and-passive-ftp/

How do you run a Python script as a service in Windows?

The simplest way is to use the: NSSM - the Non-Sucking Service Manager. Just download and unzip to a location of your choosing. It's a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no "installation" is needed. The zip contains a 64-bit and a 32-bit version of the utility. Either should work well on current systems (you can use the 32-bit version to manage services on 64-bit systems).

GUI approach

1 - install the python program as a service. Open a Win prompt as admin

c:\>nssm.exe install WinService

2 - On NSSM´s GUI console:

path: C:\Python27\Python27.exe

Startup directory: C:\Python27

Arguments: c:\WinService.py

3 - check the created services on services.msc

Scripting approach (no GUI)

This is handy if your service should be part of an automated, non-interactive procedure, that may be beyond your control, such as a batch or installer script. It is assumed that the commands are executed with administrative privileges.

For convenience the commands are described here by simply referring to the utility as nssm.exe. It is advisable, however, to refer to it more explicitly in scripting with its full path c:\path\to\nssm.exe, since it's a self-contained executable that may be located in a private path that the system is not aware of.

1. Install the service

You must specify a name for the service, the path to the proper Python executable, and the path to the script:

nssm.exe install ProjectService "c:\path\to\python.exe" "c:\path\to\project\app\main.py"

More explicitly:

nssm.exe install ProjectService 
nssm.exe set ProjectService Application "c:\path\to\python.exe"
nssm.exe set ProjectService AppParameters "c:\path\to\project\app\main.py"

Alternatively you may want your Python app to be started as a Python module. One easy approach is to tell nssm that it needs to change to the proper starting directory, as you would do yourself when launching from a command shell:

nssm.exe install ProjectService "c:\path\to\python.exe" "-m app.main"
nssm.exe set ProjectService AppDirectory "c:\path\to\project"

This approach works well with virtual environments and self-contained (embedded) Python installs. Just make sure to have properly resolved any path issues in those environments with the usual methods. nssm has a way to set environment variables (e.g. PYTHONPATH) if needed, and can also launch batch scripts.

2. To start the service

nssm.exe start ProjectService 

3. To stop the service

nssm.exe stop ProjectService

4. To remove the service, specify the confirm parameter to skip the interactive confirmation.

nssm.exe remove ProjectService confirm

How to connect Android app to MySQL database?

Android does not support MySQL out of the box. The "normal" way to access your database would be to put a Restful server in front of it and use the HTTPS protocol to connect to the Restful front end.

Have a look at ContentProvider. It is normally used to access a local database (SQLite) but it can be used to get data from any data store.

I do recommend that you look at having a local copy of all/some of your websites data locally, that way your app will still work when the Android device hasn't got a connection. If you go down this route then a service can be used to keep the two databases in sync.

How to do a batch insert in MySQL

Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys

Run Function After Delay

You can simply use jQuery’s delay() method to set the delay time interval.

HTML code:

  <div class="box"></div>

JQuery code:

  $(document).ready(function(){ 
    $(".show-box").click(function(){
      $(this).text('loading...').delay(1000).queue(function() {
        $(this).hide();
        showBox(); 
        $(this).dequeue();
      });        
    });
  });

You can see an example here: How to Call a Function After Some Time in jQuery

Telnet is not recognized as internal or external command

If your Windows 7 machine is a member of an AD, or if you have UAC enabled, or if security policies are in effect, telnet more often than not must be run as an admin. The easiest way to do this is as follows

  1. Create a shortcut that calls cmd.exe

  2. Go to the shortcut's properties

  3. Click on the Advanced button

  4. Check the "Run as an administrator" checkbox

    After these steps you're all set and telnet should work now.

Tkinter module not found on Ubuntu

this works for me:

from tkinter import *
root = Tk()
l = Label(root, text="Does it work")
l.pack()

How do I append to a table in Lua

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

Wait until flag=true

Solution using Promise, async\await and EventEmitter which allows to react immediate on flag change without any kind of loops at all

const EventEmitter = require('events');

const bus = new EventEmitter();
let lock = false;

async function lockable() {
    if (lock) await new Promise(resolve => bus.once('unlocked', resolve));
    ....
    lock = true;
    ...some logic....
    lock = false;
    bus.emit('unlocked');
}

EventEmitter is builtin in node. In browser you shall need to include it by your own, for example using this package: https://www.npmjs.com/package/eventemitter3

round() doesn't seem to be rounding properly

Floating point math is vulnerable to slight, but annoying, precision inaccuracies. If you can work with integer or fixed point, you will be guaranteed precision.

Passing std::string by Value or Reference

There are multiple answers based on what you are doing with the string.

1) Using the string as an id (will not be modified). Passing it in by const reference is probably the best idea here: (std::string const&)

2) Modifying the string but not wanting the caller to see that change. Passing it in by value is preferable: (std::string)

3) Modifying the string but wanting the caller to see that change. Passing it in by reference is preferable: (std::string &)

4) Sending the string into the function and the caller of the function will never use the string again. Using move semantics might be an option (std::string &&)

PHP import Excel into database (xls & xlsx)

I wrote an inherited class:

_x000D_
_x000D_
<?php_x000D_
class ExcelReader extends Spreadsheet_Excel_Reader { _x000D_
 _x000D_
 function GetInArray($sheet=0) {_x000D_
_x000D_
  $result = array();_x000D_
_x000D_
   for($row=1; $row<=$this->rowcount($sheet); $row++) {_x000D_
    for($col=1;$col<=$this->colcount($sheet);$col++) {_x000D_
     if(!$this->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint']) {_x000D_
      $val = $this->val($row,$col,$sheet);_x000D_
      $result[$row][$col] = $val;_x000D_
     }_x000D_
    }_x000D_
   }_x000D_
  return $result;_x000D_
 }_x000D_
_x000D_
}_x000D_
?>
_x000D_
_x000D_
_x000D_

So I can do this:

_x000D_
_x000D_
<?php_x000D_
_x000D_
 $data = new ExcelReader("any_excel_file.xls");_x000D_
 print_r($data->GetInArray());_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

Illegal character in path at index 16

If this error occurs with the jdk use this :

progra~1 instead of program files in the path example :

 c:/progra~1/java instead of c:/program files/java

It will be ok always avoid space in java code.....

it can be used for every thing in program files, otherwise put quotes at the beginning and the en of path

"c:/..../"

How to export a MySQL database to JSON?

I know this is old, but for the sake of somebody looking for an answer...

There's a JSON library for MYSQL that can be found here You need to have root access to your server and be comfortable installing plugins (it's simple).

1) upload the lib_mysqludf_json.so into the plugins directory of your mysql installation

2) run the lib_mysqludf_json.sql file (it pretty much does all of the work for you. If you run into trouble just delete anything that starts with 'DROP FUNCTION...')

3) encode your query in something like this:

SELECT json_array(
         group_concat(json_object( name, email))
FROM ....
WHERE ...

and it will return something like

[ 
   { 
     "name": "something",
     "email": "[email protected]"
    }, 
   { 
     "name": "someone",
     "email": "[email protected]"
    }

]

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Since you're dealing with values that are just supposed to be boolean anyway, just use == and convert the logical response to as.integer:

df <- data.frame(col = c("true", "true", "false"))
df
#     col
# 1  true
# 2  true
# 3 false
df$col <- as.integer(df$col == "true")
df
#   col
# 1   1
# 2   1
# 3   0

How do I use Spring Boot to serve static content located in Dropbox folder?

@Mark Schäfer

Never too late, but add a slash (/) after static:

spring.resources.static-locations=file:/opt/x/y/z/static/

So http://<host>/index.html is now reachable.

Laravel 5 Class 'form' not found

Use Form, not form. The capitalization counts.