Programs & Examples On #Exceptionhub

How can I convert an HTML table to CSV?

Read HTML File and Use Ruby's CSV and nokogiri to Output to .csv.

Based on @audiodude's answer but modified in the following ways:

  • Reads from a file to get the HTML. This is handy for long HTML tables, but easily modified to just use a static String if your HTML table is small.
  • Uses CSV's built-in library for converting an Array into a CSV row.
  • Outputs to a .csv file instead of just printing to STDOUT.
  • Gets both the table headers (th) and the table body (td).
# Convert HTML table to CSV format.

require "nokogiri"

html_file_path = ""

html_string = File.read( html_file_path )

doc = Nokogiri::HTML( html_string )

CSV.open( Rails.root.join( Time.zone.now.to_s( :file ) + ".csv" ), "wb" ) do |csv|
  doc.xpath( "//table//tr" ).each do |row|
    csv << row.xpath( "th|td" ).collect( &:text ).collect( &:strip )
  end
end

Can an AWS Lambda function call another

In java, we can do as follows :

AWSLambdaAsync awsLambdaAsync = AWSLambdaAsyncClientBuilder.standard().withRegion("us-east-1").build();

InvokeRequest invokeRequest = new InvokeRequest();
invokeRequest.withFunctionName("youLambdaFunctionNameToCall").withPayload(payload);

InvokeResult invokeResult = awsLambdaAsync.invoke(invokeRequest); 

Here, payload is your stringified java object which needs to be passed as Json object to another lambda in case you need to pass some information from calling lambda to called lambda.

Getting the thread ID from a thread

You can use the deprecated AppDomain.GetCurrentThreadId to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID, and will return the Windows thread ID.

This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.

See configurator's answer for more reasons why this is the case.

How do I generate a stream from a string?

We use the extension methods listed below. I think you should make the developer make a decision about the encoding, so there is less magic involved.

public static class StringExtensions {

    public static Stream ToStream(this string s) {
        return s.ToStream(Encoding.UTF8);
    }

    public static Stream ToStream(this string s, Encoding encoding) {
        return new MemoryStream(encoding.GetBytes(s ?? ""));
    }
}

Writelines writes lines without newline, Just fills the file

writelines() does not add line separators. You can alter the list of strings by using map() to add a new \n (line break) at the end of each string.

items = ['abc', '123', '!@#']
items = map(lambda x: x + '\n', items)
w.writelines(items)

How to get rid of underline for Link component of React Router?

<Link to="/page">
    <Box sx={{ display: 'inline-block' }}>
        <PLink variant="primary">Page</PLink>
    </Box>
</Link>

In some cases when using another component inside the Gatsby <Link> component, adding a div with display: 'inline-block' around the inner component, prevents underlining (of 'Page' in the example).

python: urllib2 how to send cookie with urlopen request

You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookies section of quickstart guide:

To send your own cookies to the server, you can use the cookies parameter:

>>> cookies = dict(cookies_are='working')

>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Is it possible to use argsort in descending order?

You could create a copy of the array and then multiply each element with -1.
As an effect the before largest elements would become the smallest.
The indeces of the n smallest elements in the copy are the n greatest elements in the original.

Why doesn't "System.out.println" work in Android?

Of course, to see the result in logcat, you should set the Log level at least to "Info" (Log level in logcat); otherwise, as it happened to me, you won't see your output.

How do getters and setters work?

In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':

class Dummy
{
    private String name;

    public Dummy() {}

    public Dummy(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

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

The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

Getting list of Facebook friends with latest API

friends.get

Is function to get a list of friend's

And yes this is best

    $friends = $facebook->api('/me/friends');

    echo '<ul>';
    foreach ($friends["data"] as $value) {
        echo '<li>';
        echo '<div class="pic">';
        echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
        echo '</div>';
        echo '<div class="picName">'.$value["name"].'</div>'; 
        echo '</li>';
    }
    echo '</ul>';

What is the difference between Promises and Observables?

Promise emits a single value while Observable emits multiple values. So, while handling a HTTP request, Promise can manage a single response for the same request, but what if there are multiple responses to the same request, then we have to use Observable. Yes, Observable can handle multiple responses for the same request.

Promise

const promise = new Promise((data) =>
{ data(1);
  data(2);
  data(3); })
.then(element => console.log(‘Promise ‘ + element));

Output

Promise 1

Observable

const observable = new Observable((data) => {
data.next(1);
data.next(2);
data.next(3);
}).subscribe(element => console.log('Observable ' + element));

Output

Observable 1
Observable 2
Observable 3

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

JDK on OSX 10.7 Lion

For Mountain Lion, Apple's java is up to 1.6.0_35-b10-428.jdk as of today.
It is indeed located under /Library/Java/JavaVirtualMachines .

You just download
"Java for OS X 2012-005 Developer Package" (Sept 6, 2012)
from
http://connect.apple.com/

In my view, Apple's naming is at least a bit confusing; why "-005" - is this the fifth version, or the fifth of five installers one needs?

And then run the installer; then follow the above steps inside Eclipse.

Git says local branch is behind remote branch, but it's not

You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:

gitk HEAD @{u}

I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:

git push -f

The -f makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.

Disabled UIButton not faded or grey

This question has a lot of answers but all they looks not very useful in case if you really want to use backgroundColor to style your buttons. UIButton has nice option to set different images for different control states but there is not same feature for background colors. So one of solutions is to add extension which will generate images from color and apply them to button.

extension UIButton {
  private func image(withColor color: UIColor) -> UIImage? {
    let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()

    context?.setFillColor(color.cgColor)
    context?.fill(rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
  }

  func setBackgroundColor(_ color: UIColor, for state: UIControlState) {
    self.setBackgroundImage(image(withColor: color), for: state)
  }
}

Only one issue with this solution -- this change won't be applied to buttons created in storyboard. As for me it's not an issue because I prefer to style UI from code. If you want to use storyboards then some additional magic with @IBInspectable needed.

Second option is subclassing but I prefer to avoid this.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

[] extracts a list, [[]] extracts elements within the list

alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7))

str(alist[[1]])
 chr [1:3] "a" "b" "c"

str(alist[1])
List of 1
 $ : chr [1:3] "a" "b" "c"

str(alist[[1]][1])
 chr "a"

How to enumerate a range of numbers starting at 1

Python 3

Official Python documentation: enumerate(iterable, start=0)

You don't need to write your own generator as other answers here suggest. The built-in Python standard library already contains a function that does exactly what you want:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

The built-in function is equivalent to this:

def enumerate(sequence, start=0):
  n = start
  for elem in sequence:
    yield n, elem
    n += 1

UITableView example for Swift

In Swift 4.1 and Xcode 9.4.1

  1. Add UITableViewDataSource, UITableViewDelegate delegated to your class.

  2. Create table view variable and array.

  3. In viewDidLoad create table view.

  4. Call table view delegates

  5. Call table view delegate functions based on your requirement.

import UIKit
// 1
class yourViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { 

// 2
var yourTableView:UITableView = UITableView()
let myArray = ["row 1", "row 2", "row 3", "row 4"]

override func viewDidLoad() {
    super.viewDidLoad()

    // 3
    yourTableView.frame = CGRect(x: 10, y: 10, width: view.frame.width-20, height: view.frame.height-200)
    self.view.addSubview(yourTableView)

    // 4
    yourTableView.dataSource = self
    yourTableView.delegate = self

}

// 5
// MARK - UITableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell : UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }
    if self. myArray.count > 0 {
        cell?.textLabel!.text = self. myArray[indexPath.row]
    }
    cell?.textLabel?.numberOfLines = 0

    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return 50.0
}

If you are using storyboard, no need for Step 3.

But you need to create IBOutlet for your table view before Step 4.

Sending emails with Javascript

The way I'm doing it now is basically like this:

The HTML:

<textarea id="myText">
    Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>

The Javascript:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    ;
    
    window.location.href = link;
}

This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.

In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.

System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());

TypeError: $ is not a function when calling jQuery function

What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>

Parsing JSON array with PHP foreach

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

Android - running a method periodically using postDelayed() call

Please check the below its working on my side in below code your handler will run after every 1 Second when you are on same activity

 HandlerThread handlerThread = new HandlerThread("HandlerThread");
                handlerThread.start();
                handler = new Handler(handlerThread.getLooper());
                runnable = new Runnable()
                {
                    @Override
                    public void run()
                    {

                            handler.postDelayed(this, 1000);
                        }
                };
                handler.postDelayed(runnable, 1000);

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

Chrome:The website uses HSTS. Network errors...this page will probably work later

Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en

How to make rectangular image appear circular with CSS

Following worked for me:

CSS

.round {
  border-radius: 50%;
  overflow: hidden;
  width: 30px;
  height: 30px;
  background: no-repeat 50%;
  object-fit: cover;
}
.round img {
   display: block;
   height: 100%;
   width: 100%;
}

HTML

<div class="round">
   <img src="test.png" />
</div>

How do I copy to the clipboard in JavaScript?

This is a standalone class and ensures no flashing could occur from the temporary textarea by placing it off-screen.

This works in Safari (desktop), Firefox, and Chrome.

// ================================================================================
// ClipboardClass
// ================================================================================
var ClipboardClass = (function() {

    function copyText(text) {
        // Create a temporary element off-screen to hold text.
        var tempElem = $('<textarea style="position: absolute; top: -8888px; left: -8888px">');
        $("body").append(tempElem);

        tempElem.val(text).select();
        document.execCommand("copy");
        tempElem.remove();
    }


    // ============================================================================
    // Class API
    // ============================================================================
    return {
        copyText: copyText
    };

})();

How to clear/delete the contents of a Tkinter Text widget?

I checked on my side by just adding '1.0' and it start working

tex.delete('1.0', END)

you can also try this

http://localhost:50070 does not work HADOOP

For recent hadoop versions (I'm using 2.7.1)

The start\stop scripts are located in the sbin folder. The scripts are:

  • ./sbin/start-dfs.sh
  • ./sbin/stop-dfs.sh
  • ./sbin/start-yarn.sh
  • ./sbin/stop-yarn.sh

I didn't have to do anything with yarn though to get the NameNodeServer instance running.

Now my mistake was that I didn't format the NameNodeServer HDFS.

bin/hdfs namenode -format

I'm not quite sure what that does at the moment but it obviously prepares the space on which the NameNodeServer will use to operate.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS for Visual Studio Community 2015.

Then run the following (substituting the variable on the right-hand side if yours has a different name):

set VS100COMNTOOLS=%VS140COMNTOOLS%

This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.

For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.

Markdown to create pages and table of contents?

There are 2 way to create your TOC (summary) in your markdown document.

1. Manually

# My Table of content
- [Section 1](#id-section1)
- [Section 2](#id-section2)

<div id='id-section1'/>
## Section 1
<div id='id-section2'/>
## Section 2

2. Programmatically

You can use for example a script that generate summary for you, take a look to my project on github - summarizeMD -

I've tried also other script/npm module (for example doctoc) but no one reproduce a TOC with working anchors.

Class JavaLaunchHelper is implemented in two places

I have found the other workaround: to exclude libinstrument.dylib from project path. To do so, go to the Preferences -> Build, Execution and Deployment -> Compiler -> Excludes -> + and here add file by the path in error message.

How to make a function wait until a callback has been called using node.js

Using async and await it is lot more easy.

router.post('/login',async (req, res, next) => {
i = await queries.checkUser(req.body);
console.log('i: '+JSON.stringify(i));
});

//User Available Check
async function checkUser(request) {
try {
    let response = await sql.query('select * from login where email = ?', 
    [request.email]);
    return response[0];

    } catch (err) {
    console.log(err);

  }

}

How to test web service using command line curl

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

How to write character & in android strings.xml

This is a my issues, my solution is as following: Use &gt; for <, &lt;for > , &amp; for & ,"'" for ' , &quot for \"\"

Upload file to FTP using C#

publish date: 06/26/2018

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
    public static void Main ()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = 
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("anonymous", 
"[email protected]");

        // Copy the contents of the file to the request stream.
        byte[] fileContents;
        using (StreamReader sourceStream = new StreamReader("testfile.txt"))
        {
            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        }

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status 
{response.StatusDescription}");
        }
    }
}
}

Java HTTP Client Request with defined timeout

I found that setting the time out settings in HttpConnectionParams and HttpConnectionManager did not solve our case. We're limited to using org.apache.commons.httpclient version 3.0.1.

I ended up using an java.util.concurrent.ExecutorService to monitor the HttpClient.executeMethod() call.

Here's a small, self-contained example

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author Jeff Kirby
 * @since <pre>Jun 17, 2011</pre>
 */
public class Example {

   private static final String SITE = "http://some.website.com/upload";
   private static final int TIME_OUT_SECS = 5;

   // upload a file and return the response as a string
   public String post(File file) throws IOException, InterruptedException {
      final Part[] multiPart = { new FilePart("file", file.getName(), file) };
      final EntityEnclosingMethod post = new PostMethod(SITE);
      post.setRequestEntity(new MultipartRequestEntity(multiPart, post.getParams()));
      final ExecutorService executor = Executors.newSingleThreadExecutor();
      final List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(new KillableHttpClient(post)), TIME_OUT_SECS, TimeUnit.SECONDS);
      executor.shutdown();
      if(futures.get(0).isCancelled()) {
         throw new IOException(SITE + " has timed out. It has taken more than " + TIME_OUT_SECS + " seconds to respond");
      }
      return post.getResponseBodyAsString();
   }

   private static class KillableHttpClient implements Callable<Integer> {

      private final EntityEnclosingMethod post;

      private KillableHttpClient(EntityEnclosingMethod post) {
         this.post = post;
      }

      public Integer call() throws Exception {
         return new HttpClient().executeMethod(post);
      }
   }
}

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

How to read XML response from a URL in java?

do it with the following code:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document doc = builder.parse("/home/codefelix/IdeaProjects/Gradle/src/main/resources/static/Employees.xml");
        NodeList namelist = (NodeList) doc.getElementById("1");

        for (int i = 0; i < namelist.getLength(); i++) {
            Node p = namelist.item(i);

            if (p.getNodeType() == Node.ELEMENT_NODE) {
                Element person = (Element) p;
                NodeList id = (NodeList) person.getElementsByTagName("Employee");
                NodeList nodeList = person.getChildNodes();
                List<EmployeeDto> employeeDtoList=new ArrayList();

                for (int j = 0; j < nodeList.getLength(); j++) {
                    Node n = nodeList.item(j);

                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element naame = (Element) n;
                        System.out.println("Employee" + id + ":" + naame.getTagName() + "=" +naame.getTextContent());
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

SQL multiple column ordering

The other answers lack a concrete example, so here it goes:

Given the following People table:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826

If you execute the query below:

SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC

The result set will look like this:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706

How to store a dataframe using Pandas

The easiest way is to pickle it using to_pickle:

df.to_pickle(file_name)  # where to save it, usually as a .pkl

Then you can load it back using:

df = pd.read_pickle(file_name)

Note: before 0.11.1 save and load were the only way to do this (they are now deprecated in favor of to_pickle and read_pickle respectively).


Another popular choice is to use HDF5 (pytables) which offers very fast access times for large datasets:

import pandas as pd
store = pd.HDFStore('store.h5')

store['df'] = df  # save it
store['df']  # load it

More advanced strategies are discussed in the cookbook.


Since 0.13 there's also msgpack which may be be better for interoperability, as a faster alternative to JSON, or if you have python object/text-heavy data (see this question).

SQL: ... WHERE X IN (SELECT Y FROM ...)

Maybe try this

Select cust.*

From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null

Registering for Push Notifications in Xcode 8/Swift 3.0?

Heads up, you should be using the main thread for this action.

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }

Setting Java heap space under Maven 2 on Windows

It should be the same command, except SET instead of EXPORT

  • set MAVEN_OPTS=-Xmx512m would give it 512Mb of heap
  • set MAVEN_OPTS=-Xmx2048m would give it 2Gb of heap

Print DIV content by JQuery

Here is a JQuery&JavaScript solutions to print div as it styles(with internal and external css)

$(document).ready(function() {
            $("#btnPrint").live("click", function () {//$btnPrint is button which will trigger print
                var divContents = $(".order_summery").html();//div which have to print
                var printWindow = window.open('', '', 'height=700,width=900');
                printWindow.document.write('<html><head><title></title>');
                printWindow.document.write('<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" >');//external styles
                printWindow.document.write('<link rel="stylesheet" href="/css/custom.css" type="text/css"/>');
                printWindow.document.write('</head><body>');
                printWindow.document.write(divContents);
                printWindow.document.write('</body></html>');
                printWindow.document.close();

                printWindow.onload=function(){
                printWindow.focus();                                         
                printWindow.print();
                printWindow.close();
                }
            });
});

This will print your div in new window.

Button to trigger event

<input type="button" id="btnPrint" value="Print This">

DataColumn Name from DataRow (not DataTable)

You need something like this:

foreach(DataColumn c in dr.Table.Columns)
{
  MessageBox.Show(c.ColumnName);
}

How do I make a simple makefile for gcc on Linux?

The simplest make file can be

all : test

test : test.o
        gcc -o test test.o 

test.o : test.c
        gcc -c test.c

clean :
        rm test *.o

Calculate execution time of a SQL query?

Please use

-- turn on statistics IO for IO related 
SET STATISTICS IO ON 
GO

and for time calculation use

SET STATISTICS TIME ON
GO

then It will give result for every query . In messages window near query input window.

How can I disable inherited css styles?

Cascading Style Sheet are designed for inheritance. Inheritance is intrinsic to their existence. If it wasn't built to be cascading, they would only be called "Style Sheets".

That said, if an inherited style doesn't fit your needs, you'll have to override it with another style closer to the object. Forget about the notion of "blocking inheritance".

You can also choose the more granular solution by giving styles to every individual objects, and not giving styles to the general tags like div, p, pre, etc.

For example, you can use styles that start with # for objects with a specific ID:

<style>
#dividstyle{
    font-family:MS Trebuchet;
}
</style>
<div id="dividstyle">Hello world</div>

You can define classes for objects:

<style>
.divclassstyle{
    font-family: Calibri;
}
</style>
<div class="divclassstyle">Hello world</div>

Hope it helps.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case i forgot to add the () after the function name inside the render function of a react component

public render() {
       let ctrl = (
           <>
                <div className="aaa">
                    {this.renderView}
                </div>
            </>
       ); 

       return ctrl;
    };


    private renderView() : JSX.Element {
        // some html
    };

Changing the render method, as it states in the error message to

        <div className="aaa">
            {this.renderView()}
        </div>

fixed the problem

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

There may be different reason for reported issue, few days back also face this issue 'duplicate jar', after upgrading studio. From all stackoverflow I tried all the suggestion but nothing worked for me.

But this is for sure some duplicate jar is there, For me it was present in one library libs folder as well as project libs folder. So I removed from project libs folder as it was not required here. So be careful while updating the studio, and try to understand all the gradle error.

How to use the pass statement?

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):

`Example:

#!/usr/bin/python

for letter in 'Python': 
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current Letter :', letter

print "Good bye!"

This will produce following result:

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block but it is no longer required.

You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

Cmake doesn't find Boost

One more bit of advice for anyone trying to build CGAL in particular, with statically linked Boost. It is not enough to define Boost_USE_STATIC_LIBS; it gets overridden by the time Boost_DEBUG outputs its value. The thing to do here is to check the "Advanced" checkbox and to enable CGAL_Boost_USE_STATIC_LIBS.

How to find if an array contains a specific string in JavaScript/jQuery?

jQuery offers $.inArray:

Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Edit 3.5 years later

$.inArray is effectively a wrapper for Array.prototype.indexOf in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_


Edit another 3 years later

Gosh, 6.5 years?!

The best option for this in modern Javascript is Array.prototype.includes:

var found = categories.includes('specialword');

No comparisons and no confusing -1 results. It does what we want: it returns true or false. For older browsers it's polyfillable using the code at MDN.

_x000D_
_x000D_
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
_x000D_
_x000D_

JavaScript string encryption and decryption?

Use SimpleCrypto

Using encrypt() and decrypt()

To use SimpleCrypto, first create a SimpleCrypto instance with a secret key (password). Secret key parameter MUST be defined when creating a SimpleCrypto instance.

To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance. This will use AES-CBC encryption algorithm.

var _secretKey = "some-unique-key";

var simpleCrypto = new SimpleCrypto(_secretKey);

var plainText = "Hello World!";
var chiperText = simpleCrypto.encrypt(plainText);
console.log("Encryption process...");
console.log("Plain Text    : " + plainText);
console.log("Cipher Text   : " + cipherText);
var decipherText = simpleCrypto.decrypt(cipherText);
console.log("... and then decryption...");
console.log("Decipher Text : " + decipherText);
console.log("... done.");

How to install the current version of Go in Ubuntu Precise

i installed from source. there is a step-by-step tutorial here: http://golang.org/doc/install/source

Calculate number of hours between 2 dates in PHP

To provide another method for DatePeriod when using the UTC or GMT timezone.

Count Hours https://3v4l.org/Mu3HD

$start = new \DateTime('2006-04-12T12:30:00');
$end = new \DateTime('2006-04-14T11:30:00');

//determine what interval should be used - can change to weeks, months, etc
$interval = new \DateInterval('PT1H');

//create periods every hour between the two dates
$periods = new \DatePeriod($start, $interval, $end);

//count the number of objects within the periods
$hours = iterator_count($periods);
echo $hours . ' hours'; 

//difference between Unix Epoch
$diff = $end->getTimestamp() - $start->getTimestamp();
$hours = $diff / ( 60 * 60 );
echo $hours . ' hours (60 * 60)';

//difference between days
$diff = $end->diff($start);
$hours = $diff->h + ($diff->days * 24);
echo $hours . ' hours (days * 24)';

Result

47 hours (iterator_count)
47 hours (60 * 60)
47 hours (days * 24)

Count Hours with Daylight Savings https://3v4l.org/QBQUB

Please be advised that DatePeriod excludes an hour for DST but does not add another hour when DST ends. So its usage is subjective to your desired outcome and date range.

See the current bug report

//set timezone to UTC to disregard daylight savings
date_default_timezone_set('America/New_York');

$interval = new \DateInterval('PT1H');

//DST starts Apr. 2nd 02:00 and moves to 03:00
$start = new \DateTime('2006-04-01T12:00:00');  
$end = new \DateTime('2006-04-02T12:00:00');

$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';

//DST ends Oct. 29th 02:00 and moves to 01:00
$start = new \DateTime('2006-10-28T12:00:00');
$end = new \DateTime('2006-10-29T12:00:00'); 

$periods = new \DatePeriod($start, $interval, $end);
$hours = iterator_count($periods);
echo $hours . ' hours';

Result

#2006-04-01 12:00 EST to 2006-04-02 12:00 EDT
23 hours (iterator_count)
//23 hours (60 * 60)
//24 hours (days * 24)

#2006-10-28 12:00 EDT to 2006-10-29 12:00 EST
24 hours (iterator_count)
//25 hours (60 * 60)
//24 hours (days * 24)

#2006-01-01 12:00 EST to 2007-01-01 12:00 EST
8759 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)

//------

#2006-04-01 12:00 UTC to 2006-04-02 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)

#2006-10-28 12:00 UTC to 2006-10-29 12:00 UTC
24 hours (iterator_count)
//24 hours (60 * 60)
//24 hours (days * 24)

#2006-01-01 12:00 UTC to 2007-01-01 12:00 UTC
8760 hours (iterator_count)
//8760 hours (60 * 60)
//8760 hours (days * 24)

T-SQL: Deleting all duplicate rows but keeping one

Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM 
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Updates were rejected because the tip of your current branch is behind its remote counterpart

the tip of your current branch is behind its remote counterpart means that there have been changes on the remote branch that you don’t have locally. and git tells you import new changes from REMOTE and merge it with your code and then push it to remote.

You can use this command to force changes to server with local repo ().

git push -f origin master

with -f tag you will override Remote Brach code with your code.

Outlets cannot be connected to repeating content iOS

With me I have a UIViewcontroller, and into it I have a tableview with a custom cell on it. I map my outlet of UILabel into UItableviewcell to the UIViewController then got the error.

Select all text inside EditText when it gets focus

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

How to split a string into a list?

If you want all the chars of a word/sentence in a list, do this:

print(list("word"))
#  ['w', 'o', 'r', 'd']


print(list("some sentence"))
#  ['s', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

Best way to check if a Data Table has a null value in it

DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
    if (dr["Column_Name"] == DBNull.Value)
    {
        //Do something
    }
    else
    {
        //Do something
    }
}

1030 Got error 28 from storage engine

Drop the problem database, then reboot mysql service (sudo service mysql restart, for example).

How to perform a fade animation on Activity transition?

you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...

View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);

Iterate through Nested JavaScript Objects

In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys(), recursively:

const iterate = (obj) => {
    Object.keys(obj).forEach(key => {

    console.log(`key: ${key}, value: ${obj[key]}`)

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
        }
    })
}

REPL example.

How to remove and clear all localStorage data

It only worked for me in Firefox when accessing it from the window object.

Example...

window.onload = function()
{
 window.localStorage.clear();
}

How to Automatically Close Alerts using Twitter Bootstrap

Calling window.setTimeout(function, delay) will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

If you want to wrap it in a nifty function you could do this.

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

Then you could use it like so...

createAutoClosingAlert(".alert-message", 2000);

I am certain there are more elegant ways to accomplish this.

CSS Image size, how to fill, but not stretch?

You can use the css property object-fit.

_x000D_
_x000D_
.cover {_x000D_
  object-fit: cover;_x000D_
  width: 50px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />
_x000D_
_x000D_
_x000D_

See example here

There's a polyfill for IE: https://github.com/anselmh/object-fit

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

How to convert / cast long to String?

String logStringVal= date+"";

Can convert the long into string object, cool shortcut for converting into string...but use of String.valueOf(date); is advisable

make a phone call click on a button

For those using AppCompact...Try this

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri;

public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startBtn = (Button) findViewById(R.id.db);
        startBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                makeCall();
            }
        });

    }

    protected void makeCall() {
        EditText num = (EditText)findViewById(R.id.Dail);
        String phone = num.getText().toString();
        String d = "tel:" + phone ;
        Log.i("Make call", "");
        Intent phoneIntent = new Intent(Intent.ACTION_CALL);
        phoneIntent.setData(Uri.parse(d));
        try {
            startActivity(phoneIntent);
            finish();
            Log.i("Finished making a call", "");
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Call faild, please try again later.", Toast.LENGTH_SHORT).show();
        }
    }

}

Then add this to your manifest,,,

 <uses-permission android:name="android.permission.CALL_PHONE" />

Which to use <div class="name"> or <div id="name">?

ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...

How to use lodash to find and return an object from Array?

You don't need Lodash or Ramda or any other extra dependency.

Just use the ES6 find() function in a functional way:

savedViews.find(el => el.description === view)

Sometimes you need to use 3rd-party libraries to get all the goodies that come with them. However, generally speaking, try avoiding dependencies when you don't need them. Dependencies can:

  • bloat your bundled code size,
  • you will have to keep them up to date,
  • and they can introduce bugs or security risks

centos: Another MySQL daemon already running with the same unix socket

It may sometime arises when MySQL service does not shut down properly during the OS reboot. The /var/lib/mysql/mysql.sock has been left. This prevents 'mysqld' from starting up.

These steps may help:

1: service mysqld start killall -9 mysqld_safe mysqld service mysqld start

2: rm /var/lib/mysql/mysql.sock service mysqld start

Random String Generator Returning Same String

As long as you are using Asp.Net 2.0 or greater, you can also use the library call- System.Web.Security.Membership.GeneratePassword, however it will include special characters.

To get 4 random characters with minimum of 0 special characters-

Membership.GeneratePassword(4, 0)

Can I install/update WordPress plugins without providing FTP access?

I also recommend the SSH SFTP Updater Support plugin. Just solved all my problems too...especially in regards to getting plugins to delete through the admin. Just install it in the usual way, and the next time you're prompted by WordPress for FTP details, there'll be extra fields for you to copy/paste your private SSH key or upload your PEM file.

Only problem I have is in getting it to remember the key (tried both methods). Don't like the idea of having to find and enter it every time I need to delete a plugin. But at least it's a solid fix for now.

How can I check if a View exists in a Database?

To expand on Kevin's answer.

    private bool CustomViewExists(string viewName)
    {
        using (SalesPad.Data.DataConnection dc = yourconnection)
        {
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                Select 1
            else
                Select 0", viewName));
            cmd.CommandType = CommandType.Text;
            return Convert.ToBoolean(dc.ExecuteScalar(cmd));
        }
    }

Batch file to delete files older than N days

Enjoy:

forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"

See forfiles documentation for more details.

For more goodies, refer to An A-Z Index of the Windows XP command line.

If you don't have forfiles installed on your machine, copy it from any Windows Server 2003 to your Windows XP machine at %WinDir%\system32\. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP.

Later versions of Windows and Windows Server have it installed by default.

For Windows 7 and newer (including Windows 10):

The syntax has changed a little. Therefore the updated command is:

forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path"

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

For OSX

  • into ~/.bash_profile add:

    export ANDROID_HOME="/path/to/android-sdk-macosx"
    export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"
    

    and then execute it in terminal to take effect immediately;

  • into /etc/sudoers add: (you can use console: sudo visudo)

    Defaults        env_keep += "ANDROID_HOME"
    

    since the building process has to start with sudo and Node's process.env get the respective variables.

How to send data in request body with a GET when using jQuery $.ajax()

Just in case somebody ist still coming along this question:

There is a body query object in any request. You do not need to parse it yourself.

E.g. if you want to send an accessToken from a client with GET, you could do it like this:

_x000D_
_x000D_
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
  if (err) throw new Error(err);_x000D_
  console.log(res);_x000D_
});
_x000D_
_x000D_
_x000D_

The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }

json Uncaught SyntaxError: Unexpected token :

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

_x000D_
_x000D_
  $.ajax({_x000D_
      crossOrigin: true,_x000D_
      url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
      type : "GET",_x000D_
      success:function(data){_x000D_
         console.log(data);_x000D_
      }_x000D_
    })
_x000D_
_x000D_
_x000D_

Is log(n!) = T(n·log(n))?

enter image description here

Sorry, I don't know how to use LaTeX syntax on stackoverflow..

Is there possibility of sum of ArrayList without looping

The only alternative to using a loop is to use recursion.

You can define a method like

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

An alternative which avoid a stack overflow is to use.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

This is just as inefficient, but will avoid a stack overflow.


The shortest way to write the same thing is

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

prints

sum(a) = 20

How to create JSON Object using String?

JSONArray may be what you want.

String message;
JSONObject json = new JSONObject();
json.put("name", "student");

JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);

json.put("course", array);

message = json.toString();

// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}

Proper way to set response status and JSON content in a REST API made with nodejs and express

FOR IIS

If you are using iisnode to run nodejs through IIS, keep in mind that IIS by default replaces any error message you send.

This means that if you send res.status(401).json({message: "Incorrect authorization token"}) You would get back You do not have permission to view this directory or page.

This behavior can be turned off by using adding the following code to your web.config file under <system.webServer> (source):

<httpErrors existingResponse="PassThrough" />

Populate data table from data reader

If you're trying to load a DataTable, then leverage the SqlDataAdapter instead:

DataTable dt = new DataTable();

using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
{
    sda.SelectCommand.CommandType = CommandType.StoredProcedure;
    sda.SelectCommand.Parameters.AddWithValue("@parm1", val1);
    ...

    sda.Fill(dt);
}

You don't even need to define the columns. Just create the DataTable and Fill it.

Here, cString is your connection string and sql is the stored procedure command.

How do I print colored output to the terminal in Python?

What about the ansicolors library? You can simple do:

from colors import color, red, blue

# common colors
print(red('This is red'))
print(blue('This is blue'))

# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))

JAVA_HOME should point to a JDK not a JRE

My JAVA_HOME was set correctly but I solved this issue by Command Prompt as Administrator

How to git clone a specific tag

git clone --depth 1 --branch <tag_name> <repo_url>

--depth 1 is optional but if you only need the state at that one revision, you probably want to skip downloading all the history up to that revision.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

Setting a max height on a table

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

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

td div{
    max-height:20px;
}

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

Android check null or empty string in Android

This worked for me

EditText   etname = (EditText) findViewById(R.id.etname);
 if(etname.length() == 0){
                    etname.setError("Required field");
                }else{
                    Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
                }

or Use this for strings

String DEP_DATE;
if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
}

SSIS Convert Between Unicode and Non-Unicode Error

  1. First, add a data conversion block into your data flow diagram.

  2. Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.

  3. Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.

  4. Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).

Inserting a blank table row with a smaller height

This one works for me:

<tr style="height: 15px;"/>

Convert Python ElementTree to string

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
      
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

Passing string parameter in JavaScript function

Use this:

document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')

Detect Browser Language in PHP

The official way to handle this is using the PECL HTTP library. Unlike some answers here, this correctly handles the language priorities (q-values), partial language matches and will return the closest match, or when there are no matches it falls back to the first language in your array.

PECL HTTP:
http://pecl.php.net/package/pecl_http

How to use:
http://php.net/manual/fa/function.http-negotiate-language.php

$supportedLanguages = [
    'en-US', // first one is the default/fallback
    'fr',
    'fr-FR',
    'de',
    'de-DE',
    'de-AT',
    'de-CH',
];

// Returns the negotiated language 
// or the default language (i.e. first array entry) if none match.
$language = http_negotiate_language($supportedLanguages, $result);

Jenkins: Is there any way to cleanup Jenkins workspace?

There is an option to do it. Configure -> Post-build Actions
The option comes by default at least in Jenkins version 2.236

Converting Date and Time To Unix Timestamp

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

Best way to create a temp table with same columns and type as a permanent table

I realize this question is extremely old, but for anyone looking for a solution specific to PostgreSQL, it's:

CREATE TEMP TABLE tmp_table AS SELECT * FROM original_table LIMIT 0;

Note, the temp table will be put into a schema like pg_temp_3.

This will create a temporary table that will have all of the columns (without indexes) and without the data, however depending on your needs, you may want to then delete the primary key:

ALTER TABLE pg_temp_3.tmp_table DROP COLUMN primary_key;

If the original table doesn't have any data in it to begin with, you can leave off the "LIMIT 0".

Python Finding Prime Factors

The code is wrong with 100. It should check case i * i = n:

I think it should be:

while i * i <= n:
    if i * i = n:
        n = i
        break

    while n%i == 0:
        n = n / i
    i = i + 1

print (n)

How do I get a value of a <span> using jQuery?

$('#item1 span').html(); Its working with my code

How do I make calls to a REST API using C#?

The first step is to create the helper class for the HTTP client.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace callApi.Helpers
{
    public class CallApi
    {
        private readonly Uri BaseUrlUri;
        private HttpClient client = new HttpClient();

        public CallApi(string baseUrl)
        {
            BaseUrlUri = new Uri(baseUrl);
            client.BaseAddress = BaseUrlUri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public HttpClient getClient()
        {
            return client;
        }

        public HttpClient getClientWithBearer(string token)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            return client;
        }
    }
}

Then you can use this class in your code.

This is an example of how you call the REST API without bearer using the above class.

// GET API/values
[HttpGet]
public async Task<ActionResult<string>> postNoBearerAsync(string email, string password,string baseUrl, string action)
{
    var request = new LoginRequest
    {
        email = email,
        password = password
    };

    var callApi = new CallApi(baseUrl);
    var client = callApi.getClient();
    HttpResponseMessage response = await client.PostAsJsonAsync(action, request);
    if (response.IsSuccessStatusCode)
        return Ok(await response.Content.ReadAsAsync<string>());
    else
        return NotFound();
}

This is an example of how you can call the REST API that require bearer.

// GET API/values
[HttpGet]
public async Task<ActionResult<string>> getUseBearerAsync(string token, string baseUrl, string action)
{
    var callApi = new CallApi(baseUrl);
    var client = callApi.getClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage response = await client.GetAsync(action);
    if (response.IsSuccessStatusCode)
    {
        return Ok(await response.Content.ReadAsStringAsync());
    }
    else
        return NotFound();
}

You can also refer to the below repository if you want to see the working example of how it works.

https://github.com/mokh223/callApi

How to compare 2 dataTables

There is nothing out there that is going to do this for you; the only way you're going to accomplish this is to iterate all the rows/columns and compare them to each other.

PHP check if url parameter exists

Use isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

How can I change the Bootstrap default font family using font from Google?

If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.

Count number of rows within each group

Current best practice (tidyverse) is:

require(dplyr)
df1 %>% count(Year, Month)

How to get a variable name as a string in PHP?

I really fail to see the use case... If you will type print_var_name($foobar) what's so hard (and different) about typing print("foobar") instead?

Because even if you were to use this in a function, you'd get the local name of the variable...

In any case, here's the reflection manual in case there's something you need in there.

'pip' is not recognized as an internal or external command

As per Python 3.6 Documentation

It is possible that pip does not get installed by default. One potential fix is:

python -m ensurepip --default-pip

HTML iframe - disable scroll

You can use the following CSS code:

margin-top: -145px; 
margin-left: -80px;
margin-bottom: -650px;

In order to limit the view of the iframe.

Webview load html from assets directory

You are getting the WebView before setting the Content view so the wv is probably null.

public class ViewWeb extends Activity {  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);  
            WebView wv;  
            wv = (WebView) findViewById(R.id.webView1);  
            wv.loadUrl("file:///android_asset/aboutcertified.html");   // now it will not fail here
        }  
    }

How do I read an attribute on a class at runtime?

System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);

for (int i = 0; i < attributes.Length; i++)
{
    if (attributes[i] is DomainNameAttribute)
    {
        System.Console.WriteLine(((DomainNameAttribute) attributes[i]).Name);
    }   
}

how to get current month and year

If you have following two labels:

<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />

Than you can use following code just need to set the Text Property for these labels like:

MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();

Watching variables contents in Eclipse IDE

You can do so by these ways.

Add watchpoint and while debugging you can see variable in debugger window perspective under variable tab. OR Add System.out.println("variable = " + variable); and see in console.

push_back vs emplace_back

One more example for lists:

// constructs the elements in place.                                                
emplace_back("element");

// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

How to run composer from anywhere?

Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer" to .bashrc or .bash_aliases didn't work at first because of two reasons:

The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0. If the what is returned is -csh you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.

To change it, first check if bash is available on your server by running cat /etc/shells. If, in the list returned, you see bin/bash, you can change the default to bash by running chsh -s /bin/csh.

Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc or source ~/.bash_profile. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile as the default script.

To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

To test, close your session and reload. If it's working properly, running composer -v or which composer should behave as expected.

How to tell if string starts with a number with Python?

Surprising that after such a long time there is still the best answer missing.

The downside of the other answers is using [0] to select the first character, but as noted, this breaks on the empty string.

Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

PHP isset() with multiple parameters

The parameters of isset() should be separated by a comma sign (,) and not a dot sign (.). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.

So the original code evaluates the variables as a unified string value:

isset($_POST['search_term'] . $_POST['postcode']) // Incorrect

While the correct form evaluates them separately as variables:

isset($_POST['search_term'], $_POST['postcode']) // Correct

What does "implements" do on a class?

Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:

public interface ISpeak
{
   public String talk();
}

public class Dog implements ISpeak
{
   public String talk()
   {
        return "bark!";
   }
}

public class Cat implements ISpeak
{
    public String talk()
    {
        return "meow!";
    }
}

Both the Cat and Dog class implement the ISpeak interface.

What's great about interfaces is that we can now refer to instances of this class through the ISpeak interface. Consider the following example:

  Dog dog = new Dog();
  Cat cat = new Cat();

  List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();

  animalsThatTalk.add(dog);
  animalsThatTalk.add(cat);

  for (ISpeak ispeak : animalsThatTalk)
  {
      System.out.println(ispeak.talk());
  }

The output for this loop would be:

bark!
meow!

Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.

One of the most common interfaces used in Java, for example, is Comparable. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.

For example:

public class Person implements Comparable<Person>
{
  private String firstName;
  private String lastName;

  // Getters/Setters

  public int compareTo(Person p)
  {
    return this.lastName.compareTo(p.getLastName());  
  }
}

Now consider this code:

//  Some code in other class

List<Person> people = getPeopleList();

Collections.sort(people);

What this code did was provide a natural ordering to the Person class. Because we implemented the Comparable interface, we were able to leverage the Collections.sort() method to sort our List of Person objects by its natural ordering, in this case, by last name.

Write HTML to string

I know you asked about C#, but if you're willing to use any .Net language then I highly recommend Visual Basic for this exact problem. Visual Basic has a feature called XML Literals that will allow you to write code like this.

Module Module1

    Sub Main()

        Dim myTitle = "Hello HTML"
        Dim myHTML = <html>
                         <head>
                             <title><%= myTitle %></title>
                         </head>
                         <body>
                             <h1>Welcome</h1>
                             <table>
                                 <tr><th>ID</th><th>Name</th></tr>
                                 <tr><td>1</td><td>CouldBeAVariable</td></tr>
                             </table>
                         </body>
                     </html>

        Console.WriteLine(myHTML)
    End Sub

End Module

This allows you to write straight HTML with expression holes in the old ASP style and makes your code super readable. Unfortunately this feature is not in C#, but you could write a single module in VB and add it as a reference to your C# project.

Writing in Visual Studio also allows proper indentation for most XML Literals and expression wholes. Indentation for the expression holes is better in VS2010.

Difference between DOMContentLoaded and load events

Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff() function whether DomContentLoaded triggers before or after your external JS files.

// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);

function doStuff(){
    //
}
if(isIE){
    // play it safe, very few users, exec ur JS when all resources are loaded
    window.onload=function(){doStuff();}
} else {
    // add event listener to trigger your function when DOMContentLoaded
    if(document.readyState==='loading'){
        document.addEventListener('DOMContentLoaded',doStuff);
    } else {
        // DOMContentLoaded already loaded, so better trigger your function
        doStuff();
    }
}

Is there an onSelect event or equivalent for HTML <select>?

Try this (event triggered exactly when you select option, without option changing):

$("select").mouseup(function() {
    var open = $(this).data("isopen");
    if(open) {
        alert('selected');
    }
    $(this).data("isopen", !open);
});

http://jsbin.com/dowoloka/4

How to remove leading whitespace from each line in a file

sed "s/^[ \t]*//" -i youfile

Warning: this will overwrite the original file.

Set and Get Methods in java?

just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.

How can I commit a single file using SVN over a network?

cd myapp/trunk
svn commit -m "commit message" page1.html

For more information, see:

svn commit --help

I also recommend this free book, if you're just getting started with Subversion.

Any way to exit bash script, but not quitting the terminal

I think that this happens because you are running it on source mode with the dot

. myscript.sh

You should run that in a subshell:

/full/path/to/script/myscript.sh

'source' http://ss64.com/bash/source.html

incompatible character encodings: ASCII-8BIT and UTF-8

I installed gem package mysql2.

gem install mysql2

and then I changed the adapter in mysql2 in database.yml.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Rename file with Git

You can rename a file using git's mv command:

$ git mv file_from file_to

Example:

$ git mv helo.txt hello.txt

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    helo.txt -> hello.txt
#

$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename helo.txt => hello.txt (100%)

postgresql: INSERT INTO ... (SELECT * ...)

insert into TABLENAMEA (A,B,C,D) 
select A::integer,B,C,D from TABLENAMEB

Print a list of space-separated elements in Python 3

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

Notepad++ add to every line

If you have thousands of lines, I guess the easiest way is like this:

-select the line that is the start point for your cursor

-while you are holding alt + shift select the line that is endpoint for your cursor

That's it. Now you have a giant cursor. You can write anything to all of these lines.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You can also check the local changelog to verify whether or not OpenSSL is patched against the vulnerability with the following command:

rpm -q --changelog openssl | grep CVE-2014-0224

If a result is not returned, then you must patch OpenSSL.

http://www.liquidweb.com/kb/update-and-patch-openssl-for-the-ccs-injection-vulnerability/

Android: How can I validate EditText input?

I find InputFilter to be more appropriate to validate text inputs on android.

Here's a simple example: How do I use InputFilter to limit characters in an EditText in Android?

You could add a Toast to feedback the user about your restrictions. Also check the android:inputType tag out.

HTML5 placeholder css padding

I noticed the issue the moment I updated Chrome on os x to the latest stable release (9.0.597.94) so this is a Chrome bug and hopefully will be fixed.

I'm tempted not to even attempt to work around this and just wait for the fix. It'll just mean more work taking it out.

How to read a file into vector in C++?

1. In the loop you are assigning value rather than comparing value so

i=((Main.size())-1) -> i=(-1) since Main.size()

Main[i] will yield "Vector Subscript out of Range" coz i = -1.

2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

Uppercase first letter of variable

just wanted to add a pure javascript solution ( no JQuery )

_x000D_
_x000D_
function capitalize(str) {_x000D_
  strVal = '';_x000D_
  str = str.split(' ');_x000D_
  for (var chr = 0; chr < str.length; chr++) {_x000D_
    strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '_x000D_
  }_x000D_
  return strVal_x000D_
}_x000D_
_x000D_
console.log(capitalize('hello world'));
_x000D_
_x000D_
_x000D_

How to get Domain name from URL using jquery..?

While pure JavaScript is sufficient here, I still prefer the jQuery approach. After all, the ask was to get the hostname using jQuery.

var hostName = $(location).attr('hostname');      // www.example.com

Recording video feed from an IP camera over a network

I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.

Andrew

How to use if statements in LESS

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    }
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;
    }
}

/* guard for class */
article when (@debug = true) {
    background-color: red;
}

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;
}

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
}
header #title {
    background-color: orange;
}
article {
    background-color: red;
}

@Transactional(propagation=Propagation.REQUIRED)

When the propagation setting is PROPAGATION_REQUIRED, a logical transaction scope is created for each method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard PROPAGATION_REQUIRED behavior, all these scopes will be mapped to the same physical transaction. So a rollback-only marker set in the inner transaction scope does affect the outer transaction's chance to actually commit (as you would expect it to).

enter image description here

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html

importing pyspark in python shell

For a Spark execution in pyspark two components are required to work together:

  • pyspark python package
  • Spark instance in a JVM

When launching things with spark-submit or pyspark, these scripts will take care of both, i.e. they set up your PYTHONPATH, PATH, etc, so that your script can find pyspark, and they also start the spark instance, configuring according to your params, e.g. --master X

Alternatively, it is possible to bypass these scripts and run your spark application directly in the python interpreter likepython myscript.py. This is especially interesting when spark scripts start to become more complex and eventually receive their own args.

  1. Ensure the pyspark package can be found by the Python interpreter. As already discussed either add the spark/python dir to PYTHONPATH or directly install pyspark using pip install.
  2. Set the parameters of spark instance from your script (those that used to be passed to pyspark).
    • For spark configurations as you'd normally set with --conf they are defined with a config object (or string configs) in SparkSession.builder.config
    • For main options (like --master, or --driver-mem) for the moment you can set them by writing to the PYSPARK_SUBMIT_ARGS environment variable. To make things cleaner and safer you can set it from within Python itself, and spark will read it when starting.
  3. Start the instance, which just requires you to call getOrCreate() from the builder object.

Your script can therefore have something like this:

from pyspark.sql import SparkSession

if __name__ == "__main__":
    if spark_main_opts:
        # Set main options, e.g. "--master local[4]"
        os.environ['PYSPARK_SUBMIT_ARGS'] = spark_main_opts + " pyspark-shell"

    # Set spark config
    spark = (SparkSession.builder
             .config("spark.checkpoint.compress", True)
             .config("spark.jars.packages", "graphframes:graphframes:0.5.0-spark2.1-s_2.11")
             .getOrCreate())

How to force two figures to stay on the same page in LaTeX?

Try using the float package and then the [H] option for your figure.

\usepackage{float}

...

\begin{figure}[H]
\centering
\includegraphics{fig1}
\caption{Write some caption here}\label{fig1}
\end{figure}

as already suggested by this insightful answer!

https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text

How to create a .NET DateTime from ISO 8601 format

This solution makes use of the DateTimeStyles enumeration, and it also works with Z.

DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

This prints the solution perfectly.

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

How to thoroughly purge and reinstall postgresql on ubuntu?

Option A

If your install isn't already damaged, you can drop unwanted PostgreSQL servers ("clusters") using pg_dropcluster. Use that in preference to a full purge and reinstall if you just want to restart with a fresh PostgreSQL instance.

$ pg_lsclusters
Ver Cluster Port Status Owner    Data directory              Log file
11  main    5432 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
$ sudo systemctl stop postgresql@11-main
$ sudo pg_dropcluster --stop 11 main
$ sudo pg_createcluster --start 11 main

Option B

If you really need to do a full purge and reinstall, first make sure PostgreSQL isn't running. ps -C postgres should show no results.

Now run:

apt-get --purge remove postgresql\*

to remove everything PostgreSQL from your system. Just purging the postgres package isn't enough since it's just an empty meta-package.

Once all PostgreSQL packages have been removed, run:

rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

You should now be able to:

apt-get install postgresql

or for a complete install:

apt-get install postgresql-8.4 postgresql-contrib-8.4 postgresql-doc-8.4

Output to the same line overwriting previous output?

Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.

import re, sys

class Reprinter:
    def __init__(self):
        self.text = ''

    def moveup(self, lines):
        for _ in range(lines):
            sys.stdout.write("\x1b[A")

    def reprint(self, text):
        # Clear previous text by overwritig non-spaces with spaces
        self.moveup(self.text.count("\n"))
        sys.stdout.write(re.sub(r"[^\s]", " ", self.text))

        # Print new text
        lines = min(self.text.count("\n"), text.count("\n"))
        self.moveup(lines)
        sys.stdout.write(text)
        self.text = text

reprinter = Reprinter()

reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")

Equivalent of .bat in mac os

May be you can find answer here? Equivalent of double-clickable .sh and .bat on Mac?

Usually you can create bash script for Mac OS, where you put similar commands as in batch file. For your case create bash file and put same command, but change back-slashes with regular ones.

Your file will look something like:

#! /bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;./supportlibraries/Framework_DataTable.jar;./supportlibraries/Framework_Reporting.jar;./supportlibraries/Framework_Utilities.jar;./supportlibraries/poi-3.8-20120326.jar;PATH_TO_YOUR_SELENIUM_SERVER_FOLDER/selenium-server-standalone-2.19.0.jar" allocator.testTrack

Change folders in path above to relevant one.

Then make this script executable: open terminal and navigate to folder with your script. Then change read-write-execute rights for this file running command:

chmod 755 scriptname.sh

Then you can run it like any other regular script: ./scriptname.sh

or you can run it passing file to bash:

bash scriptname.sh

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

In my case, I fixed this error by change export default class yourComponent extends React.Component() {} to export default class yourComponent extends React.Component {}. Yes delete the parenthesis () fixed the error.

Eloquent: find() and where() usage laravel

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

Vue template or render function not defined yet I am using neither?

Something like this should resolve the issue..

Vue.component(
'example-component', 
require('./components/ExampleComponent.vue').default);

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

This problem mysteriously appeared for me today. I hadn't done any Windows updates, so I don't know the cause.

This fixed it (in elevated command prompt):

regtlibv12.exe msdatsrc.tlb

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Populate unique values into a VBA array from Excel

Sub GetUniqueAndCount()

    Dim d As Object, c As Range, k, tmp As String

    Set d = CreateObject("scripting.dictionary")
    For Each c In Selection
        tmp = Trim(c.Value)
        If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
    Next c

    For Each k In d.keys
        Debug.Print k, d(k)
    Next k

End Sub

How to cast int to enum in C++?

Test castEnum = static_cast<Test>(a-1); will cast a to A. If you don't want to substruct 1, you can redefine the enum:

enum Test
{
    A:1, B
};

In this case Test castEnum = static_cast<Test>(a); could be used to cast a to A.

Get value of a string after last slash in JavaScript

var str = "foo/bar/test.html";
var lastSlash = str.lastIndexOf("/");
alert(str.substring(lastSlash+1));

Hibernate SessionFactory vs. JPA EntityManagerFactory

By using EntityManager, code is no longer tightly coupled with hibernate. But for this, in usage we should use :

javax.persistence.EntityManager

instead of

org.hibernate.ejb.HibernateEntityManager

Similarly, for EntityManagerFactory, use javax interface. That way, the code is loosely coupled. If there is a better JPA 2 implementation than hibernate, switching would be easy. In extreme case, we could type cast to HibernateEntityManager.

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

Save image from url with curl PHP

This is easiest implement.

function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen($url, 'rb');
    if ($file) {
        $newf = fopen($newfname, 'wb');
        if ($newf) {
            while (!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}

Where and why do I have to put the "template" and "typename" keywords?

typedef typename Tail::inUnion<U> dummy;

However, I'm not sure you're implementation of inUnion is correct. If I understand correctly, this class is not supposed to be instantiated, therefore the "fail" tab will never avtually fails. Maybe it would be better to indicates whether the type is in the union or not with a simple boolean value.

template <typename T, typename TypeList> struct Contains;

template <typename T, typename Head, typename Tail>
struct Contains<T, UnionNode<Head, Tail> >
{
    enum { result = Contains<T, Tail>::result };
};

template <typename T, typename Tail>
struct Contains<T, UnionNode<T, Tail> >
{
    enum { result = true };
};

template <typename T>
struct Contains<T, void>
{
    enum { result = false };
};

PS: Have a look at Boost::Variant

PS2: Have a look at typelists, notably in Andrei Alexandrescu's book: Modern C++ Design

Month name as a string

I keep this answer which is useful for other cases, but @trutheality answer seems to be the most simple and direct way.

You can use DateFormatSymbols

DateFormatSymbols(Locale.FRENCH).getMonths()[month]; // FRENCH as an example

How to set data attributes in HTML elements

[jQuery] .data() vs .attr() vs .extend()

The jQuery method .data() updates an internal object managed by jQuery through the use of the method, if I'm correct.

If you'd like to update your data-attributes with some spread, use --

$('body').attr({ 'data-test': 'text' });

-- otherwise, $('body').attr('data-test', 'text'); will work just fine.

Another way you could accomplish this is using --

$.extend( $('body')[0].dataset, { datum: true } );

-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.

How to refresh a page with jQuery by passing a parameter to URL

You can use Javascript URLSearchParams.

var url = new URL(window.location.href);
url.searchParams.set('single','');
window.location.href = url.href;

[UPDATE]: If IE support is a need, check this thread:

SCRIPT5009: 'URLSearchParams' is undefined in IE 11

Thanks @john-m to talk about the IE support

Stick button to right side of div

Another solution: change margins. Depending on the siblings of the button, display should be modified.

button {
    display:      block;
    margin-left:  auto;
    margin-right: 0;
}

Group by & count function in sqlalchemy

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

How to get http headers in flask?

Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.

enter image description here

The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

After params, let's now see how to get the headers:

enter image description here

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

Now let's see how to get the body

enter image description here

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

psql: FATAL: Ident authentication failed for user "postgres"

You're getting this error because you're failing client authentication. Based on the error message, you probably have the default postgres configuration, which sets client authentication method to "IDENT" for all PostgreSQL connections.

You should definitely read section 19.1 Client Authentication in the PostgreSQL manual to better understand the authentication settings available (for each record in pg_hba.conf), but here is the relevant snippet to help with the problem you're having (from the version 9.5 manual):

trust

Allow the connection unconditionally. This method allows anyone that can connect to the PostgreSQL database server to login as any PostgreSQL user they wish, without the need for a password or any other authentication. See Section 19.3.1 for details.

reject

Reject the connection unconditionally. This is useful for "filtering out" certain hosts from a group, for example a reject line could block a specific host from connecting, while a later line allows the remaining hosts in a specific network to connect.

md5

Require the client to supply a double-MD5-hashed password for authentication. See Section 19.3.2 for details.

password

Require the client to supply an unencrypted password for authentication. Since the password is sent in clear text over the network, this should not be used on untrusted networks. See Section 19.3.2 for details.

gss

Use GSSAPI to authenticate the user. This is only available for TCP/IP connections. See Section 19.3.3 for details.

sspi

Use SSPI to authenticate the user. This is only available on Windows. See Section 19.3.4 for details.

ident

Obtain the operating system user name of the client by contacting the ident server on the client and check if it matches the requested database user name. Ident authentication can only be used on TCP/IP connections. When specified for local connections, peer authentication will be used instead. See Section 19.3.5 for details.

peer

Obtain the client's operating system user name from the operating system and check if it matches the requested database user name. This is only available for local connections. See Section 19.3.6 for details.

ldap

Authenticate using an LDAP server. See Section 19.3.7 for details.

radius

Authenticate using a RADIUS server. See Section 19.3.8 for details.

cert

Authenticate using SSL client certificates. See Section 19.3.9 for details.

pam

Authenticate using the Pluggable Authentication Modules (PAM) service provided by the operating system. See Section 19.3.10 for details.

So ... to solve the problem you're experiencing, you could do one of the following:

  1. Change the authentication method(s) defined in your pg_hba.conf file to trust, md5, or password (depending on your security and simplicity needs) for the local connection records you have defined in there.

  2. Update pg_ident.conf to map your operating system users to PostgreSQL users and grant them the corresponding access privileges, depending on your needs.

  3. Leave the IDENT settings alone and create users in your database for each operating system user that you want to grant access to. If a user is already authenticated by the OS and logged in, PostgreSQL won't require further authentication and will grant access to that user based on whatever privileges (roles) are assigned to it in the database. This is the default configuration.

Note: The location of pg_hba.conf and pg_ident.conf is OS dependent.

How do I add a new class to an element dynamically?

Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

Can I configure a subdomain to point to a specific port on my server

If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)

Is there an opposite to display:none?

I use display:block; It works for me

Ng-model does not update controller value

"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.

Controller

$scope.formData = {};
$scope.check = function () {
  console.log($scope.formData.searchText.$modelValue); //works
}

Template

<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>

This happens when child scopes are in play - like child routes or ng-repeats. The child-scope creates it's own value and a name conflict is born as illustrated here:

See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s

Comparing two collections for equality irrespective of the order of items in them

A simple and fairly efficient solution is to sort both collections and then compare them for equality:

bool equal = collection1.OrderBy(i => i).SequenceEqual(
                 collection2.OrderBy(i => i));

This algorithm is O(N*logN), while your solution above is O(N^2).

If the collections have certain properties, you may be able to implement a faster solution. For example, if both of your collections are hash sets, they cannot contain duplicates. Also, checking whether a hash set contains some element is very fast. In that case an algorithm similar to yours would likely be fastest.

RuntimeError on windows trying python multiprocessing

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."

... by using if __name__ == '__main__'

Setting table row height

try this:

.topics tr { line-height: 14px; }

Get SSID when WIFI is connected

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID(). Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION.

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.

Source: "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()."

Get property value from C# dynamic object by string (reflection?)

you can use "dynamicObject.PropertyName.Value" to get value of dynamic property directly.

Example :

d.property11.Value

How to use border with Bootstrap

What others have mentioned about border vs border box is definitely correct. You can still get this to work without having to create any custom classes though: http://jsfiddle.net/panchroma/yfzdD/

HTML

<div class="container">
<div class="row" >
    <div class="span12">
       <div class="row">
        <div class="span4"> 1 </div>
        <div class="span4"> 2 </div>
        <div class="span4"> 3 </div>
        </div><!-- end nested row -->
    </div><!-- end span 12 -->

</div> <!-- end row -->
</div><!-- end container -->

CSS

.span12{
border:solid 2px black;
background-color:grey;  
}  

Good luck!

Why does the 260 character path length limit exist in Windows?

This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\" prefix the path to use greater than 260 characters.

A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths

Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the \\?\ prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.

Sending data back to the Main Activity in Android

In first activity u can send intent using startActivityForResult() and then get result from second activity after it finished using setResult.

MainActivity.class

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_RESULT_CODE = 0;

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

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        // send intent for result 
        startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
            if (resultCode == RESULT_OK) {

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.class

public class SecondActivity extends AppCompatActivity {

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

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

How to access the local Django webserver from outside world

Pick one or more from:

  • Your application isn't successfully listening on the intended IP:PORT
    • Because you haven't configured it successfully
    • Because the user doesn't have permission to
  • Your application is listening successfully on the intended IP:PORT, but clients can't reach it because
    • The server local iptables prevents it.
    • A firewall prevents it.

So, you can check that your application is listening successfully by running lsof -i as root on the machine and look for a python entry with the corresponding port you've specified.

Non-root users generally cannot bind to ports < 1024.

You'll need to look at iptables -nvL to see if there's a rule that would prevent access to the ip:port that you are trying to bind your application to.

If there is an upstream firewall and you don't know much about it, you'll need to talk to your network administrators.

href="tel:" and mobile numbers

I know the OP is asking about international country codes but for North America, you could use the following:

_x000D_
_x000D_
<a href="tel:+1-847-555-5555">1-847-555-5555</a>

<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

This might help you.

Cache busting via params

In general this should be fine, but it's possible for this to not work if there is an intermediate cache (a proxy) that is configured to ignore the request parameters.

For example, if you are serving static content through Akamai CDN, it can be configured to ignore request parameters to prevent cache busting using this method.

What does jQuery.fn mean?

jQuery.fn is defined shorthand for jQuery.prototype. From the source code:

jQuery.fn = jQuery.prototype = {
    // ...
}

That means jQuery.fn.jquery is an alias for jQuery.prototype.jquery, which returns the current jQuery version. Again from the source code:

// The current version of jQuery being used
jquery: "@VERSION",

How do I handle the window close event in Tkinter?

Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager.

You can use the protocol method to install a handler for this protocol (the widget must be a Tk or Toplevel widget):

Here you have a concrete example:

import tkinter as tk
from tkinter import messagebox

root = tk.Tk()

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

Retain precision with double in Java

When you input a double number, for example, 33.33333333333333, the value you get is actually the closest representable double-precision value, which is exactly:

33.3333333333333285963817615993320941925048828125

Dividing that by 100 gives:

0.333333333333333285963817615993320941925048828125

which also isn't representable as a double-precision number, so again it is rounded to the nearest representable value, which is exactly:

0.3333333333333332593184650249895639717578887939453125

When you print this value out, it gets rounded yet again to 17 decimal digits, giving:

0.33333333333333326

PHP ini file_get_contents external url

The answers provided above solve the problem but don't explain the strange behaviour the OP described. This explanation should help anyone testing communication between sites in a development environment where these sites all reside on the same host (and the same virtualhost; I'm working with apache 2.4 and php7.0).

There's a subtlety with file_get_contents() I came across that is absolutely relevant here but unaddressed (probably because it's either barely documented or not documented from what I can tell or is documented in an obscure php security model whitepaper I can't find).

With allow_url_fopen set to Off in all relevant contexts (e.g. /etc/php/7.0/apache2/php.ini, /etc/php/7.0/fpm/php.ini, etc...) and allow_url_fopen set to On in the command line context (i.e. /etc/php/7.0/cli/php.ini), calls to file_get_contents() for a local resource will be allowed and no warning will be logged such as:

file_get_contents('php://input');

or

// Path outside document root that webserver user agent has permission to read. e.g. for an apache2 webserver this user agent might be www-data so a file at /etc/php/7.0/filetoaccess would be successfully read if www-data had permission to read this file
file_get_contents('<file path to file on local machine user agent can access>');

or

// Relative path in same document root
file_get_contents('data/filename.dat')

To conclude, the restriction allow_url_fopen = Off is analogous to an iptables rule in the OUTPUT chain, where the restriction is only applied when an attempt to "exit the system" or "change contexts" is made.

N.B. allow_url_fopen set to On in the command line context (i.e. /etc/php/7.0/cli/php.ini) is what I had on my system but I suspect it would have no bearing on the explanation I provided even if it were set to Off unless of course you're testing by running your scripts from the command line itself. I did not test the behaviour with allow_url_fopen set to Off in the command line context.

Full width layout with twitter bootstrap

As of the latest Bootstrap (3.1.x), the way to achieve a fluid layout it to use .container-fluid class.

See Bootstrap grid for reference

Does Python have a ternary conditional operator?

a if condition else b

Just memorize this pyramid if you have trouble remembering:

     condition
  if           else
a                   b