Programs & Examples On #Configure

A Configure script is an executable script designed to aid in developing a program to be run on a wide number of different computers.

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

"Logging out" of phpMyAdmin?

The presence of the logout button depends on whether you are required to login or not, in the first place. This is tweakable in PHPMyAdmin config files.

Yet, I don't think that would change anything concerning your error message. You would need to fix the configuration for the message to go away.

Edit: this is the kind of solution you should be searching for. And here are plenty of others for you to explore ^^

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

How to compare two Carbon Timestamps?

This is how I am comparing 2 dates, now() and a date from the table

@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
    .....
    .....
@endif

Should work just right. I have used the comparison functions provided by Carbon.

Add 2 hours to current time in MySQL?

SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time

Counting the number of elements with the values of x in a vector

A method that is relatively fast on long vectors and gives a convenient output is to use lengths(split(numbers, numbers)) (note the S at the end of lengths):

# Make some integer vectors of different sizes
set.seed(123)
x <- sample.int(1e3, 1e4, replace = TRUE)
xl <- sample.int(1e3, 1e6, replace = TRUE)
xxl <-sample.int(1e3, 1e7, replace = TRUE)

# Number of times each value appears in x:
a <- lengths(split(x,x))

# Number of times the value 64 appears:
a["64"]
#~ 64
#~ 15

# Occurences of the first 10 values
a[1:10]
#~ 1  2  3  4  5  6  7  8  9 10 
#~ 13 12  6 14 12  5 13 14 11 14 

The output is simply a named vector.
The speed appears comparable to rle proposed by JBecker and even a bit faster on very long vectors. Here is a microbenchmark in R 3.6.2 with some of the functions proposed:

library(microbenchmark)

f1 <- function(vec) lengths(split(vec,vec))
f2 <- function(vec) table(vec)
f3 <- function(vec) rle(sort(vec))
f4 <- function(vec) plyr::count(vec)

microbenchmark(split = f1(x),
               table = f2(x),
               rle = f3(x),
               plyr = f4(x))
#~ Unit: microseconds
#~   expr      min        lq      mean    median        uq      max neval  cld
#~  split  402.024  423.2445  492.3400  446.7695  484.3560 2970.107   100  b  
#~  table 1234.888 1290.0150 1378.8902 1333.2445 1382.2005 3203.332   100    d
#~    rle  227.685  238.3845  264.2269  245.7935  279.5435  378.514   100 a   
#~   plyr  758.866  793.0020  866.9325  843.2290  894.5620 2346.407   100   c 

microbenchmark(split = f1(xl),
               table = f2(xl),
               rle = f3(xl),
               plyr = f4(xl))
#~ Unit: milliseconds
#~   expr       min        lq      mean    median        uq       max neval cld
#~  split  21.96075  22.42355  26.39247  23.24847  24.60674  82.88853   100 ab 
#~  table 100.30543 104.05397 111.62963 105.54308 110.28732 168.27695   100   c
#~    rle  19.07365  20.64686  23.71367  21.30467  23.22815  78.67523   100 a  
#~   plyr  24.33968  25.21049  29.71205  26.50363  27.75960  92.02273   100  b 

microbenchmark(split = f1(xxl),
               table = f2(xxl),
               rle = f3(xxl),
               plyr = f4(xxl))
#~ Unit: milliseconds
#~   expr       min        lq      mean    median        uq       max neval  cld
#~  split  296.4496  310.9702  342.6766  332.5098  374.6485  421.1348   100 a   
#~  table 1151.4551 1239.9688 1283.8998 1288.0994 1323.1833 1385.3040   100    d
#~    rle  399.9442  430.8396  464.2605  471.4376  483.2439  555.9278   100   c 
#~   plyr  350.0607  373.1603  414.3596  425.1436  437.8395  506.0169   100  b  

Importantly, the only function that also counts the number of missing values NA is plyr::count. These can also be obtained separately using sum(is.na(vec))

'do...while' vs. 'while'

One of the applications I have seen it is in Oracle when we look at result sets.

Once you a have a result set, you first fetch from it (do) and from that point on.. check if the fetch returns an element or not (while element found..) .. The same might be applicable for any other "fetch-like" implementations.

Update Jenkins from a war file

We run jenkins from the .war file with the following command.

java -Xmx2500M -jar jenkins.war --httpPort=3333 --prefix=/jenkins

You can even run the command from the ~/Downloads directory

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

Can't find AVD or SDK manager in Eclipse

Unfortunately I ended up having to re-install eclipse. but first (In Linux)(not sure of folder in Windows) do:

sudo rm -R /usr/share/eclipse/

When saving, how can you check if a field has changed?

How about using David Cramer's solution:

http://cramer.io/2010/12/06/tracking-changes-to-fields-in-django/

I've had success using it like this:

@track_data('name')
class Mode(models.Model):
    name = models.CharField(max_length=5)
    mode = models.CharField(max_length=5)

    def save(self, *args, **kwargs):
        if self.has_changed('name'):
            print 'name changed'

    # OR #

    @classmethod
    def post_save(cls, sender, instance, created, **kwargs):
        if instance.has_changed('name'):
            print "Hooray!"

Why is there no ForEach extension method on IEnumerable?

One workaround is to write .ToList().ForEach(x => ...).

pros

Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.

Syntactic noise is very mild (only adds a little extranious code).

Doesn't usually cost extra memory, since a native .ForEach() would have to realize the whole collection, anyway.

cons

Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.

If realizing the list throws an exception, you never get to act on a single element.

If the enumeration is infinite (like the natural numbers), you're out of luck.

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

How do you compare two version Strings in Java?

Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.

How to use Servlets and Ajax?

Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.

Kickoff example returning String as plain text

Create a /some.jsp like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from "someservlet" to "${pageContext.request.contextPath}/someservlet"; it's merely omitted from the code snippets for brevity):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

Create a servlet with a doGet() method which look like this:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

Map this servlet on an URL pattern of /someservlet or /someservlet/* as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet URL in JS code examples over all place accordingly):

package com.example;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml the old fashioned way (see also our Servlets wiki page):

<servlet>
    <servlet-name>someservlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someservlet</servlet-name>
    <url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>

Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

Returning List<String> as JSON

With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib folder of your webapplication.

Here's an example which displays List<String> as <ul><li>. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson) as function argument when you set the response content type to application/json. If you forget to set it or rely on a default of text/plain or text/html, then the responseJson argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse() afterwards, which is thus totally unnecessary if you set the content type right in first place.

Returning Map<String, String> as JSON

Here's another example which displays Map<String, String> as <option>:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

And the JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

with

<select id="someselect"></select>

Returning List<Entity> as JSON

Here's an example which displays List<Product> in a <table> where the Product class has the properties Long id, String name and BigDecimal price. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

Returning List<Entity> as XML

Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();

    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}

The JSP code (note: if you put the <table> in a <jsp:include>, it may be reusable elsewhere in a non-ajax response):

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
    <table>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td><c:out value="${product.name}" /></td>
                <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
            </tr>
        </c:forEach>
    </table>
</data>

The JS code:

$(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
        $("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
    });
});

You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.

Ajaxifying an existing form

You can use jQuery $.serialize() to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

You can progressively enhance it with ajax as below:

$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // ...
    });

    event.preventDefault(); // Important! Prevents submitting the form.
});

You can in the servlet distinguish between normal requests and ajax requests as below:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON or XML) response.
    } else {
        // Handle regular (JSP) response.
    }
}

The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data forms as required by file uploads.

Manually sending request parameters to servlet

If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param() to easily convert a JSON object to an URL-encoded query string.

var params = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.post("someservlet", $.param(params), function(response) {
    // ...
});

The same doPost() method as shown here above can be reused. Do note that above syntax also works with $.get() in jQuery and doGet() in servlet.

Manually sending JSON object to servlet

If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify() (not part of jQuery) and instruct jQuery to set request content type to application/json instead of (default) application/x-www-form-urlencoded. This can't be done via $.post() convenience function, but needs to be done via $.ajax() as below.

var data = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.ajax({
    type: "POST",
    url: "someservlet",
    contentType: "application/json", // NOT dataType!
    data: JSON.stringify(data),
    success: function(response) {
        // ...
    }
});

Do note that a lot of starters mix contentType with dataType. The contentType represents the type of the request body. The dataType represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type header.

Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter() the usual way. Namely, servlets don't support application/json formatted requests, but only application/x-www-form-urlencoded or multipart/form-data formatted requests. Gson also supports parsing a JSON string into a JSON object.

JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...

Do note that this all is more clumsy than just using $.param(). Normally, you want to use JSON.stringify() only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.

Sending a redirect from servlet

Important to realize and understand is that any sendRedirect() and forward() call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.

document.open();
document.write(responseText);
document.close();

Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.

String redirectURL = "http://example.com";

Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
function(responseJson) {
    if (responseJson.redirect) {
        window.location = responseJson.redirect;
        return;
    }

    // ...
}

See also:

How do you change the value inside of a textfield flutter?

Here is a full example where the parent widget controls the children widget. The parent widget updates the children widgets (Text and TextField) with a counter.

To update the Text widget, all you do is pass in the String parameter. To update the TextField widget, you need to pass in a controller, and set the text in the controller.

main.dart:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Update Text and TextField demo'),
        ),
        body: ParentWidget());
  }
}

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  int _counter = 0;
  String _text = 'no taps yet';
  var _controller = TextEditingController(text: 'initial value');

  void _handleTap() {
    setState(() {
      _counter = _counter + 1;
      _text = 'number of taps: ' + _counter.toString();
      _controller.text  = 'number of taps: ' + _counter.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(children: <Widget>[
        RaisedButton(
          onPressed: _handleTap,
          child: const Text('Tap me', style: TextStyle(fontSize: 20)),
        ),
        Text('$_text'),
        TextField(controller: _controller,),
      ]),
    );
  }
}

Detecting an undefined object property

All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined':

var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
  return ((prop in obj) && (typeof obj[prop] == 'undefined'));
};

Example:

var a = { b : 1, e : null };
a.c = a.d;

hasUndefinedProperty(a, 'b'); // false: b is defined as 1
hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
hasUndefinedProperty(a, 'd'); // false: d is undefined
hasUndefinedProperty(a, 'e'); // false: e is defined as null

// And now...
delete a.c ;
hasUndefinedProperty(a, 'c'); // false: c is undefined

Too bad that this been the right answer and is buried in wrong answers >_<

So, for anyone who pass by, I will give you undefined's for free!!

var undefined ; undefined ; // undefined
({}).a ;                    // undefined
[].a ;                      // undefined
''.a ;                      // undefined
(function(){}()) ;          // undefined
void(0) ;                   // undefined
eval() ;                    // undefined
1..a ;                      // undefined
/a/.a ;                     // undefined
(true).a ;                  // undefined

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

How do I get the last character of a string?

public char LastChar(String a){
    return a.charAt(a.length() - 1);
}

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

READ_EXTERNAL_STORAGE permission for Android

Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21" to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

ieshims.dll is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.

I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

SyntaxError: unexpected EOF while parsing

Maybe this is what you mean to do:

import random

x = 0
z = input('Please Enter an integer: ')
z = int(z) # you need to capture the result of the expressioin: int(z) and assign it backk to z

def main():
    for i in range(x,z):
        n1 = random.randrange(1,3)
        n2 = random.randrange(1,3)
        t1 = n1+n2
        print('{0}+{1}={2}'.format(n1,n2,t1))

main()
  1. do z = int(z)
  2. Add the missing closing parenthesis on the last line of code in your listing.
  3. And have a for-loop that will iterate from x to z-1

Here's a link on the range() function: http://docs.python.org/release/1.5.1p1/tut/range.html

Get index of array element faster than O(n)

Is there a good reason not to use a hash? Lookups are O(1) vs. O(n) for the array.

How can I add an item to a ListBox in C# and WinForms?

You have to create an item of type ListBoxItem and add that to the Items collection:

list.Items.add( new ListBoxItem("clan", "sifOsoba"));

How do I undo 'git add' before commit?

git remove or git rm can be used for this, with the --cached flag. Try:

git help rm

INSERT VALUES WHERE NOT EXISTS

There is a great solution for this problem ,You can use the Merge Keyword of Sql

Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

You can check this before following, below is the sample

IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
    DROP TABLE dbo.TargetTable
GO

CREATE TABLE dbo.TargetTable
    (
    Id   INT NOT NULL,
    Name VARCHAR (255) NOT NULL,
    CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
    )
GO



INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO


Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Javascript window.open pass values using POST

thanks php-b-grader !

below the generic function for window.open pass values using POST:

function windowOpenInPost(actionUrl,windowName, windowFeatures, keyParams, valueParams) 
{
    var mapForm = document.createElement("form");
    var milliseconds = new Date().getTime();
    windowName = windowName+milliseconds;
    mapForm.target = windowName;
    mapForm.method = "POST";
    mapForm.action = actionUrl;
    if (keyParams && valueParams && (keyParams.length == valueParams.length)){
        for (var i = 0; i < keyParams.length; i++){
        var mapInput = document.createElement("input");
            mapInput.type = "hidden";
            mapInput.name = keyParams[i];
            mapInput.value = valueParams[i];
            mapForm.appendChild(mapInput);

        }
        document.body.appendChild(mapForm);
    }


    map = window.open('', windowName, windowFeatures);
if (map) {
    mapForm.submit();
} else {
    alert('You must allow popups for this map to work.');
}}

gitignore all files of extension in directory

It would appear that the ** syntax is supported by git as of version 1.8.2.1 according to the documentation.

Two consecutive asterisks ("**") in patterns matched against full pathname may have special meaning:

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

  • A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.

  • A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.

  • Other consecutive asterisks are considered invalid.

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

How do I compare two string variables in an 'if' statement in Bash?

This question has already great answers, but here it appears that there is a slight confusion between using single equal (=) and double equals (==) in

if [ "$s1" == "$s2" ]

The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash in the starting of the script and save your script as filename.bash. To execute, use bash filename.bash - then you have to use ==.

If you are using sh then use #!/bin/sh and save your script as filename.sh. To execute use sh filename.sh - then you have to use single =. Avoid intermixing them.

JOptionPane Input to int

String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

The requested operation cannot be performed on a file with a user-mapped section open

If it is a web application deleting files in Temporary ASP.NET Files folder could be a solution.

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

Lombok is not generating getter and setter

  • If you use STS. You must have Lombok installed in your Eclipse by running lombok-xyz.jar

  • Please Try the Following the Steps:

    1. Include pom in Maven .
    2. Exit/Shutdown STS
    3. Find lombok Jar in ~/.m2/repository/org/projectlombok/lombok/version.x
    4. From Command Prompt/Shell java -jar lombok-1.x.y.jar Project Lombok Installer

    5. Start STS

Thats all.

EDIT: I did this and was still showing errors, as mentioned in the comments. So I updated the project: right-click on project -> Maven -> Update Project and the errors disappeared.

How do the major C# DI/IoC frameworks compare?

Just read this great .Net DI container comparison blog by Philip Mat.

He does some thorough performance comparison tests on;

He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.

Delete data with foreign key in SQL Server table

If you wish the delete to be automatic, you need to change your schema so that the foreign key constraint is ON DELETE CASCADE.

For more information, see the MSDN page on Cascading Referential Integrity Constraints.

ETA (after clarification from the poster): If you can't update the schema, you have to manually DELETE the affected child records first.

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

How to change the color of a button?

Through Programming:

btn.setBackgroundColor(getResources().getColor(R.color.colorOffWhite));

and your colors.xml must contain...

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="colorOffWhite">#80ffffff</color>
</resources>

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You could just use: {in and out function callback}

$(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

For your example, better will be to use CSS pseudo class :hover: {no js/jquery needed}

.result {
    height: 72px;
    width: 100%;
    border: 1px solid #000;
  }
  .result:hover {
    background-color: #000;
  }

HTTP requests and JSON parsing in Python

requests has built-in .json() method

import requests
requests.get(url).json()

Get img thumbnails from Vimeo?

If you are looking for an alternative solution and can manage the vimeo account there is another way, you simply add every video you want to show into an album and then use the API to request the album details - it then shows all the thumbnails and links. It's not ideal but might help.

API end point (playground)

Twitter convo with @vimeoapi

How do I write out a text file in C# with a code page other than UTF-8?

Wrap your StreamWriter with FileStream, this way:

string fileName = "test.txt";
string textToAdd = "Example text in file";
Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); //Or any other Encoding

using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
    using (StreamWriter writer = new StreamWriter(fs, encoding))
    {
        writer.Write(textToAdd);
    }
}

Look at MSDN

Similarity String Comparison in Java

Yes, there are many well documented algorithms like:

  • Cosine similarity
  • Jaccard similarity
  • Dice's coefficient
  • Matching similarity
  • Overlap similarity
  • etc etc

A good summary ("Sam's String Metrics") can be found here (original link dead, so it links to Internet Archive)

Also check these projects:

How to vertically center an image inside of a div element in HTML using CSS?

The accepted answer did not work for me. vertical-align needs a partner so that they can be aligned at their centers. So I created an empty div with full height of the parent div but with no width for the image to align with. inline-block is needed for both objects to stay in one line.

<div>
    <div class="placeholder"></div>
    <img />
</div>

CSS:

.class {
    height: 100%;
    width: 0%;
    vertical-align: middle;
    display: inline-block
}
img {
    display: inline-block;
    vertical-align: middle;
}

forcing web-site to show in landscape mode only

While I myself would be waiting here for an answer, I wonder if it can be done via CSS:

@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}

@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}

HTML5 Canvas Resize (Downscale) Image High Quality?

DEMO: Resizing images with JS and HTML Canvas Demo fiddler.

You may find 3 different methods to do this resize, that will help you understand how the code is working and why.

https://jsfiddle.net/1b68eLdr/93089/

Full code of both demo, and TypeScript method that you may want to use in your code, can be found in the GitHub project.

https://github.com/eyalc4/ts-image-resizer

This is the final code:

export class ImageTools {
base64ResizedImage: string = null;

constructor() {
}

ResizeImage(base64image: string, width: number = 1080, height: number = 1080) {
    let img = new Image();
    img.src = base64image;

    img.onload = () => {

        // Check if the image require resize at all
        if(img.height <= height && img.width <= width) {
            this.base64ResizedImage = base64image;

            // TODO: Call method to do something with the resize image
        }
        else {
            // Make sure the width and height preserve the original aspect ratio and adjust if needed
            if(img.height > img.width) {
                width = Math.floor(height * (img.width / img.height));
            }
            else {
                height = Math.floor(width * (img.height / img.width));
            }

            let resizingCanvas: HTMLCanvasElement = document.createElement('canvas');
            let resizingCanvasContext = resizingCanvas.getContext("2d");

            // Start with original image size
            resizingCanvas.width = img.width;
            resizingCanvas.height = img.height;


            // Draw the original image on the (temp) resizing canvas
            resizingCanvasContext.drawImage(img, 0, 0, resizingCanvas.width, resizingCanvas.height);

            let curImageDimensions = {
                width: Math.floor(img.width),
                height: Math.floor(img.height)
            };

            let halfImageDimensions = {
                width: null,
                height: null
            };

            // Quickly reduce the size by 50% each time in few iterations until the size is less then
            // 2x time the target size - the motivation for it, is to reduce the aliasing that would have been
            // created with direct reduction of very big image to small image
            while (curImageDimensions.width * 0.5 > width) {
                // Reduce the resizing canvas by half and refresh the image
                halfImageDimensions.width = Math.floor(curImageDimensions.width * 0.5);
                halfImageDimensions.height = Math.floor(curImageDimensions.height * 0.5);

                resizingCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                    0, 0, halfImageDimensions.width, halfImageDimensions.height);

                curImageDimensions.width = halfImageDimensions.width;
                curImageDimensions.height = halfImageDimensions.height;
            }

            // Now do final resize for the resizingCanvas to meet the dimension requirments
            // directly to the output canvas, that will output the final image
            let outputCanvas: HTMLCanvasElement = document.createElement('canvas');
            let outputCanvasContext = outputCanvas.getContext("2d");

            outputCanvas.width = width;
            outputCanvas.height = height;

            outputCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                0, 0, width, height);

            // output the canvas pixels as an image. params: format, quality
            this.base64ResizedImage = outputCanvas.toDataURL('image/jpeg', 0.85);

            // TODO: Call method to do something with the resize image
        }
    };
}}

any tool for java object to object mapping?

Use Apache commons beanutils:

static void copyProperties(Object dest, Object orig) -Copy property values from the origin bean to the destination bean for all cases where the property names are the same.

http://commons.apache.org/proper/commons-beanutils/

How to read a single char from the console in Java (as the user types it)?

Use jline3:

Example:

Terminal terminal = TerminalBuilder.builder()
    .jna(true)
    .system(true)
    .build();

// raw mode means we get keypresses rather than line buffered input
terminal.enterRawMode();
reader = terminal .reader();
...
int read = reader.read();
....
reader.close();
terminal.close();

Dart SDK is not configured

The reasons for this error can be either you did not install Flutter or you are using an older version of Flutter 1.21. So it is advisable to check the above things first of all. If none of the above things are the reasons for your error you can follow the below steps and it might help you.

  1. Go to File --> Settings
  2. Then Languages and Frameworks --> Flutter

Flutter SDK path should be empty here. The problem is in here

  1. Copy the Flutter SDK path
  2. Paste it in the empty text field
  3. Apply and OK

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

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

How can I add shadow to the widget in flutter?

class ShadowContainer extends StatelessWidget {
  ShadowContainer({
    Key key,
    this.margin = const EdgeInsets.fromLTRB(0, 10, 0, 8),
    this.padding = const EdgeInsets.symmetric(horizontal: 8),
    this.circular = 4,
    this.shadowColor = const Color.fromARGB(
        128, 158, 158, 158), //Colors.grey.withOpacity(0.5),
    this.backgroundColor = Colors.white,
    this.spreadRadius = 1,
    this.blurRadius = 3,
    this.offset = const Offset(0, 1),
    @required this.child,
  }) : super(key: key);

  final Widget child;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final double circular;
  final Color shadowColor;
  final double spreadRadius;
  final double blurRadius;
  final Offset offset;
  final Color backgroundColor;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(circular),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            spreadRadius: spreadRadius,
            blurRadius: blurRadius,
            offset: offset,
          ),
        ],
      ),
      child: child,
    );
  }
}

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I run my application with Java 8 and Java 8 brought security certificate onto its trust store. Then I switched to Java 7 and added the following into VM options:

-Djavax.net.ssl.trustStore=C:\<....>\java8\jre\lib\security\cacerts

Simply I pointed to the location where a certificate is.

How to convert a string to lower case in Bash?

For a standard shell (without bashisms) using only builtins:

uppers=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lowers=abcdefghijklmnopqrstuvwxyz

lc(){ #usage: lc "SOME STRING" -> "some string"
    i=0
    while ([ $i -lt ${#1} ]) do
        CUR=${1:$i:1}
        case $uppers in
            *$CUR*)CUR=${uppers%$CUR*};OUTPUT="${OUTPUT}${lowers:${#CUR}:1}";;
            *)OUTPUT="${OUTPUT}$CUR";;
        esac
        i=$((i+1))
    done
    echo "${OUTPUT}"
}

And for upper case:

uc(){ #usage: uc "some string" -> "SOME STRING"
    i=0
    while ([ $i -lt ${#1} ]) do
        CUR=${1:$i:1}
        case $lowers in
            *$CUR*)CUR=${lowers%$CUR*};OUTPUT="${OUTPUT}${uppers:${#CUR}:1}";;
            *)OUTPUT="${OUTPUT}$CUR";;
        esac
        i=$((i+1))
    done
    echo "${OUTPUT}"
}

C++ Double Address Operator? (&&)

This is C++11 code. In C++11, the && token can be used to mean an "rvalue reference".

Outline effect to text

I got better results with 6 different shadows:

.strokeThis{
    text-shadow:
    -1px -1px 0 #ff0,
    0px -1px 0 #ff0,
    1px -1px 0 #ff0,
    -1px 1px 0 #ff0,
    0px 1px 0 #ff0,
    1px 1px 0 #ff0;
}

CSS Child vs Descendant selectors

Be aware that the child selector is not supported in Internet Explorer 6. (If you use the selector in a jQuery/Prototype/YUI etc selector rather than in a style sheet it still works though)

Java - creating a new thread

Please try this. You will understand all perfectly after you will take a look on my solution.

There are only 2 ways of creating threads in java

with implements Runnable

class One implements Runnable {
@Override
public void run() {
    System.out.println("Running thread 1 ... ");
}

with extends Thread

class Two extends Thread {
@Override
public void run() {
    System.out.println("Running thread 2 ... ");
}

Your MAIN class here

public class ExampleMain {
public static void main(String[] args) {

    One demo1 = new One();
    Thread t1 = new Thread(demo1);
    t1.start();

    Two demo2 = new Two();
    Thread t2 = new Thread(demo2);
    t2.start();
}

}

Add a properties file to IntelliJ's classpath

For those of you who migrate from Eclipse to IntelliJ or the other way around here is a tip when working with property files or other resource files.

Its maddening (cost my a whole evening to find out) but both IDE's work quite different when it comes to looking for resource/propertty files when you want to run locally from your IDE or during debugging. (Packaging to a .jar is also quite different, but thats documented better.)

Suppose you have a relative path referral like this in your code:

new FileInputStream("xxxx.properties");

(which is convenient if you work with env specific .properties files which you don't want to package along with your JAR)

INTELLIJ

(I use 13.1 , but could be valid for more versions)

The file xxxx.properties needs to be at the PARENT dir of the project ROOT in order to be picked up at runtime like this in IntelliJ. (The project ROOT is where the /src folder resides in)

ECLIPSE

Eclipse is just happy when the xxxx.properties file is at the project ROOT itself.

So IntelliJ expects .properties file to be 1 level higher then Eclipse when it is referenced like this !!

This also affects the way you have to execute your code when you have this same line of code ( new FileInputStream("xxxx.properties"); ) in your exported .jar. When you want to be agile and don't want to package the .properties file with your jar you'll have to execute the jar like below in order to reference the .properties file correctly from the command line:

INTELLIJ EXPORTED JAR

java -cp "/path/to_properties_file/:/path/to_jar/some.jar" com.bla.blabla.ClassContainingMainMethod

ECLIPSE EXPORTED JAR

java -jar some.jar

where the Eclipse exported executable jar will just expect the referenced .properties file to be on the same location as where the .jar file is

How can we run a test method with multiple parameters in MSTest?

EDIT 4: Looks like this is completed in MSTest V2 June 17, 2016: https://blogs.msdn.microsoft.com/visualstudioalm/2016/06/17/taking-the-mstest-framework-forward-with-mstest-v2/

Original Answer:

As of about a week ago in Visual Studio 2012 Update 1 something similar is now possible:

[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
[DataRow(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual( q, n / d );
}

EDIT: It appears this is only available within the unit testing project for WinRT/Metro. Bummer

EDIT 2: The following is the metadata found using "Go To Definition" within Visual Studio:

#region Assembly Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll, v11.0.0.0
// C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\MSTestFramework\11.0\References\CommonConfiguration\neutral\Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll
#endregion

using System;

namespace Microsoft.VisualStudio.TestPlatform.UnitTestFramework
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class DataTestMethodAttribute : TestMethodAttribute
    {
        public DataTestMethodAttribute();

        public override TestResult[] Execute(ITestMethod testMethod);
    }
}

EDIT 3: This issue was brought up in Visual Studio's UserVoice forums. Last Update states:

STARTED · Visual Studio Team ADMIN Visual Studio Team (Product Team, Microsoft Visual Studio) responded · April 25, 2016 Thank you for the feedback. We have started working on this.

Pratap Lakshman Visual Studio

https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/3865310-allow-use-of-datatestmethod-datarow-in-all-unit

How to programmatically modify WCF app.config endpoint address setting?

For what it's worth, I needed to update the port and scheme for SSL for my RESTFul service. This is what I did. Apologies that it is a bit more that the original question, but hopefully useful to someone.

// Don't forget to add references to System.ServiceModel and System.ServiceModel.Web

using System.ServiceModel;
using System.ServiceModel.Configuration;

var port = 1234;
var isSsl = true;
var scheme = isSsl ? "https" : "http";

var currAssembly = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
Configuration config = ConfigurationManager.OpenExeConfiguration(currAssembly);

ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);

// Get the first endpoint in services.  This is my RESTful service.
var endp = serviceModel.Services.Services[0].Endpoints[0];

// Assign new values for endpoint
UriBuilder b = new UriBuilder(endp.Address);
b.Port = port;
b.Scheme = scheme;
endp.Address = b.Uri;

// Adjust design time baseaddress endpoint
var baseAddress = serviceModel.Services.Services[0].Host.BaseAddresses[0].BaseAddress;
b = new UriBuilder(baseAddress);
b.Port = port;
b.Scheme = scheme;
serviceModel.Services.Services[0].Host.BaseAddresses[0].BaseAddress = b.Uri.ToString();

// Setup the Transport security
BindingsSection bindings = serviceModel.Bindings;
WebHttpBindingCollectionElement x =(WebHttpBindingCollectionElement)bindings["webHttpBinding"];
WebHttpBindingElement y = (WebHttpBindingElement)x.ConfiguredBindings[0];
var e = y.Security;

e.Mode = isSsl ? WebHttpSecurityMode.Transport : WebHttpSecurityMode.None;
e.Transport.ClientCredentialType = HttpClientCredentialType.None;

// Save changes
config.Save();

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case, the service failed to start because I didn't set Platform='x64' in the wix file.

I saw these errors in Event Viewer:

Service cannot be started.

System.BadImageFormatException: Could not load file or assembly 'SOME_LIBRARY_FILE, Version=5.0.0.0, Culture=neutral, PublicKeyToken=33345856ad364e35' or one of its dependencies.

I tried checking the bitness of all service related files using CorFlags.exe. When I changed my installer to be 64 bit, everything started working fine.

What exactly does the .join() method do?

To append a string, just concatenate it with the + sign.

E.g.

>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world

join connects strings together with a separator. The separator is what you place right before the join. E.g.

>>> "-".join([a,b])
'Hello, -world'

Join takes a list of strings as a parameter.

How to fix 'sudo: no tty present and no askpass program specified' error?

If by any chance you came here because you can't sudo inside the Ubuntu that comes with Windows10

  1. Edit the /etc/hosts file from Windows (with Notepad), it'll be located at: %localappdata\lxss\rootfs\etc, add 127.0.0.1 WINDOWS8, this will get rid of the first error that it can't find the host.

  2. To get rid of the no tty present error, always do sudo -S <command>

How do you add an SDK to Android Studio?

You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:

On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:

 Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
 Mac: /Applications/Android\ Studio.app/sdk/

How do I base64 encode a string efficiently using Excel VBA?

This code works very fast. It comes from here

Option Explicit

Private Const clOneMask = 16515072          '000000 111111 111111 111111
Private Const clTwoMask = 258048            '111111 000000 111111 111111
Private Const clThreeMask = 4032            '111111 111111 000000 111111
Private Const clFourMask = 63               '111111 111111 111111 000000

Private Const clHighMask = 16711680         '11111111 00000000 00000000
Private Const clMidMask = 65280             '00000000 11111111 00000000
Private Const clLowMask = 255               '00000000 00000000 11111111

Private Const cl2Exp18 = 262144             '2 to the 18th power
Private Const cl2Exp12 = 4096               '2 to the 12th
Private Const cl2Exp6 = 64                  '2 to the 6th
Private Const cl2Exp8 = 256                 '2 to the 8th
Private Const cl2Exp16 = 65536              '2 to the 16th

Public Function Encode64(sString As String) As String

    Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
    Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long

    For lTemp = 0 To 63                                 'Fill the translation table.
        Select Case lTemp
            Case 0 To 25
                bTrans(lTemp) = 65 + lTemp              'A - Z
            Case 26 To 51
                bTrans(lTemp) = 71 + lTemp              'a - z
            Case 52 To 61
                bTrans(lTemp) = lTemp - 4               '1 - 0
            Case 62
                bTrans(lTemp) = 43                      'Chr(43) = "+"
            Case 63
                bTrans(lTemp) = 47                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
        lPowers8(lTemp) = lTemp * cl2Exp8
        lPowers16(lTemp) = lTemp * cl2Exp16
    Next lTemp

    iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
    If iPad Then                                        'If not, figure out the end pad and resize the input.
        iPad = 3 - iPad
        sString = sString & String(iPad, Chr(0))
    End If

    bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
    lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
    lTemp = lLen \ 72                                   'Added space for vbCrLfs.
    lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
    ReDim bOut(lOutSize)                                'Make the output buffer.

    lLen = 0                                            'Reusing this one, so reset it.

    For lChar = LBound(bIn) To UBound(bIn) Step 3
        lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
        lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
        bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
        lTemp = lTrip And clTwoMask                     'Mask for the second set.
        bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
        lTemp = lTrip And clThreeMask                   'Mask for the third set.
        bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
        bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
        If lLen = 68 Then                               'Ready for a newline
            bOut(lPos + 4) = 13                         'Chr(13) = vbCr
            bOut(lPos + 5) = 10                         'Chr(10) = vbLf
            lLen = 0                                    'Reset the counter
            lPos = lPos + 6
        Else
            lLen = lLen + 4
            lPos = lPos + 4
        End If
    Next lChar

    If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.

    If iPad = 1 Then                                    'Add the padding chars if any.
        bOut(lOutSize) = 61                             'Chr(61) = "="
    ElseIf iPad = 2 Then
        bOut(lOutSize) = 61
        bOut(lOutSize - 1) = 61
    End If

    Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.

End Function

Public Function Decode64(sString As String) As String

    Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
    Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
    Dim lTemp As Long

    sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
    sString = Replace(sString, vbLf, vbNullString)      'either order.

    lTemp = Len(sString) Mod 4                          'Test for valid input.
    If lTemp Then
        Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
    End If

    If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
        iPad = 2                                        'Note:  These translate to 0, so you can leave them...
    ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
        iPad = 1
    End If

    For lTemp = 0 To 255                                'Fill the translation table.
        Select Case lTemp
            Case 65 To 90
                bTrans(lTemp) = lTemp - 65              'A - Z
            Case 97 To 122
                bTrans(lTemp) = lTemp - 71              'a - z
            Case 48 To 57
                bTrans(lTemp) = lTemp + 4               '1 - 0
            Case 43
                bTrans(lTemp) = 62                      'Chr(43) = "+"
            Case 47
                bTrans(lTemp) = 63                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
        lPowers6(lTemp) = lTemp * cl2Exp6
        lPowers12(lTemp) = lTemp * cl2Exp12
        lPowers18(lTemp) = lTemp * cl2Exp18
    Next lTemp

    bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
    ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.

    For lChar = 0 To UBound(bIn) Step 4
        lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
        lTemp = lQuad And clHighMask                    'Mask for the first byte
        bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
        lTemp = lQuad And clMidMask                     'Mask for the second byte
        bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
        bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
        lPos = lPos + 3
    Next lChar

    sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
    If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
    Decode64 = sOut

End Function

How to overwrite the previous print to stdout in python?

Suppress the newline and print \r.

print 1,
print '\r2'

or write to stdout:

sys.stdout.write('1')
sys.stdout.write('\r2')

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

Possible to make labels appear when hovering over a point in matplotlib?

From http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html :

from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand


if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)

    x, y, c, s = rand(4, 100)
    def onpick3(event):
        ind = event.ind
        print('onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind))

    fig = figure()
    ax1 = fig.add_subplot(111)
    col = ax1.scatter(x, y, 100*s, c, picker=True)
    #fig.savefig('pscoll.eps')
    fig.canvas.mpl_connect('pick_event', onpick3)

show()

How to get thread id of a pthread in linux c program?

I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,

POSIX thread IDs are not the same as the thread IDs returned by the Linux specific gettid() system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn’t need to know about the kernel IDs (and won’t be portable if it depends on knowing them).

Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk

IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3... to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2) function should be used.

if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");

Installing MySQL-python

yum install mysql-devel

It worked for me.

Vim 80 column layout concerns

You can try this to set the window size to allow 80 characters of actual text. This still doesn't work with vertical splits though.

let &co=80 + &foldcolumn + (&number || &relativenumber ? &numberwidth : 0)

This requires vim 7+, 7.3 for relativenumber.

Broadcast receiver for checking internet connection in android app

Try with this

public class ConnectionBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {


    if (<Check internet connection available >) { 
        Toast.makeText(context, "connect to the internet", Toast.LENGTH_LONG).show();

        /*upload background upload service*/
        Intent serviceIntent = new Intent(context,<your service class>);
        context.startService(serviceIntent);


    }else{
        Toast.makeText(context, "Connection failed", Toast.LENGTH_LONG).show();

    }
    }
}

As soon as internet connection trigger, this (BroadcastReciever) will be loaded

Reset all the items in a form

    function setToggleInputsinPnl(pnlName) {
    var domCount = pnlName.length;
    for (var i = 0; i < domCount; i++) {
        if (pnlName[i].type == 'text') {
            pnlName[i].value = '';
        } else if (pnlName[i].type == 'select-one') {
               pnlName[i].value = '';
        }
    }
}

Count length of array and return 1 if it only contains one element

Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

$cars.count should give you what you seem to be looking for.

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

Using apkanalyzer that is now part of cmdline-tools:

$ apkanalyzer manifest version-code my_app.apk
1
$ apkanalyzer manifest version-name my_app.apk
1.2.3.4

How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

As for #2, in my case it magically came to life after replacing

<body>

tag with

<h:body>

After having done several (simpler, to be honest) JSF projects, I couldn't remember of doing anything different setting it up now, and I got this kind of error for the first time. I was making a very basic login page (username, password, user Bean...) and set up everything like usual. The only difference I spotted is tags aforementioned. Maybe someone finds this useful.

How to center an iframe horizontally?

best way and more simple to center an iframe on your webpage is :

<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>

where width and height will be the size of your iframe in your html page.

Rails: Get Client IP address

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of these options worked for me, in the end it was;

Test > Test Settings > *.testrunconfig

I had to add a new line

<DeploymentItem filename="packages\Newtonsoft.Json.4.5.8\lib\net40\Newtonsoft.Json.dll" />

Make sure the path and version is correct for your setup.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Try jQuery's delegate() function, like so:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.

Using NotNull Annotation in method argument

SO @NotNull just is a tag...If you want to validate it, then you must use something like hibernate validator jsr 303

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 Set<ConstraintViolation<List<Searching>> violations = validator.validate(searchingList);

Count items in a folder with PowerShell

Only Files

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}

Only Folders

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}

Both

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}

How to push files to an emulator instance using Android Studio

One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)

enter image description here

FileSystemWatcher Changed event is raised twice

Try this, It's working fine

  private static readonly FileSystemWatcher Watcher = new FileSystemWatcher();
    static void Main(string[] args)
    {
        Console.WriteLine("Watching....");

        Watcher.Path = @"D:\Temp\Watcher";
        Watcher.Changed += OnChanged;
        Watcher.EnableRaisingEvents = true;
        Console.ReadKey();
    }

    static void OnChanged(object sender, FileSystemEventArgs e)
    {
        try
        {
            Watcher.Changed -= OnChanged;
            Watcher.EnableRaisingEvents = false;
            Console.WriteLine($"File Changed. Name: {e.Name}");
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
        }
        finally
        {
            Watcher.Changed += OnChanged;
            Watcher.EnableRaisingEvents = true;
        }
    }

How to remove all null elements from a ArrayList or String Array?

Try:

tourists.removeAll(Collections.singleton(null));

Read the Java API. The code will throw java.lang.UnsupportedOperationException for immutable lists (such as created with Arrays.asList); see this answer for more details.

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How to add Drop-Down list (<select>) programmatically?

Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:

_x000D_
_x000D_
function select(options, selected) {_x000D_
  return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);_x000D_
}_x000D_
$('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to use SVN, Branch? Tag? Trunk?

Version Control with Subversion is the guide for beginners and old hands alike.

I don't think you can use Subversion effectively without reading at least the first few chapters of this.

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Regular Expression for password validation

Pattern satisfy, these below criteria

  1. Password Length 8 and Maximum 15 character
  2. Require Unique Chars
  3. Require Digit
  4. Require Lower Case
  5. Require Upper Case
^(?!.*([A-Za-z0-9]))(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$

Two inline-block, width 50% elements wrap to second line

inline and inline-block elements are affected by whitespace in the HTML.

The simplest way to fix your problem is to remove the whitespace between </div> and <div id="col2">, see: http://jsfiddle.net/XCDsu/15/

There are other possible solutions, see: bikeshedding CSS3 property alternative?

How do I run a file on localhost?

Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system or exec for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true

In Sender

  1. Declare params to be sent. We can send String, Object,…

Sender.xhtml

<f:metadata>
      <f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
  1. We’re going send param ID, it will be included with “includeViewParams=true” in return String of click button event Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData

Sender.xhtml

<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
      <p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??" 
      ajax="false"/>
</p:dataTable>

In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID

Sender_MB.java
    public String clickBtnDetail(sender_DTO sender_dto) {
        this._strID = sender_dto.getStrID();
        return "Receiver?faces-redirect=true&includeViewParams=true";
    }

The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*

In Recever

  1. Get viewParam Receiver.xhtml In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)

Receiver.xhtml

<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>

It will get param ID from sender View and assign to receiver_MB._strID

  1. Use viewParam In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received So that we add

Receiver.xhtml

<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />

into f:metadata tag

Receiver.xhtml

<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
            type="preRenderView" />
</f:metadata>

Now we want to use this param in our read database method, it is available to use

Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
        if (FacesContext.getCurrentInstance().isPostback()) {
            return;
        }
        readFromDatabase();
    }
private void readFromDatabase() {
//use _strID to read and set property   
}

How to replace space with comma using sed?

If you want the output on terminal then,

$sed 's/ /,/g' filename.txt

But if you want to edit the file itself i.e. if you want to replace space with the comma in the file then,

$sed -i 's/ /,/g' filename.txt

How do I open phone settings when a button is clicked?

Using UIApplication.openSettingsURLString

Update for Swift 5.1

 override func viewDidAppear(_ animated: Bool) {
    let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in

        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}

Swift 4.2

override func viewDidAppear(_ animated: Bool) {
    let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in

        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}

How to combine two byte arrays

You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils class ). You need to do the following

byte[] concatBytes = ArrayUtils.addAll(one,two);

What is the difference between mocking and spying when using Mockito?

Difference between a Spy and a Mock

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

In the following example – we create a mock of the ArrayList class:

@Test
public void whenCreateMock_thenCreated() {
    List mockedList = Mockito.mock(ArrayList.class);

    mockedList.add("one");
    Mockito.verify(mockedList).add("one");

    assertEquals(0, mockedList.size());
}

As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
public void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());
    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertEquals(1, spyList.size());
}

Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.

Source: http://www.baeldung.com/mockito-spy + self notes.

How to construct a REST API that takes an array of id's for the resources

As much as I prefer this approach:-

    api.com/users?id=id1,id2,id3,id4,id5

The correct way is

    api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

or

    api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5

This is how rack does it. This is how php does it. This is how node does it as well...

How much data can a List can hold at the maximum?

The interface however defines the size() method, which returns an int.

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

So, no limit, but after you reach Integer.MAX_VALUE, the behaviour of the list changes a bit

ArrayList (which is tagged) is backed by an array, and is limited to the size of the array - i.e. Integer.MAX_VALUE

MongoDB: How to update multiple documents with a single command?

For Mongo version > 2.2, add a field multi and set it to true

db.Collection.update({query}, 
                 {$set: {field1: "f1", field2: "f2"}},
                 {multi: true })

How to add an image in Tkinter?

There is no "Syntax Error" in the code above - it either ocurred in some other line (the above is not all of your code, as there are no imports, neither the declaration of your path variable) or you got some other error type.

The example above worked fine for me, testing on the interactive interpreter.

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Hash and salt passwords in C#

In answer to this part of the original question "Is there any other C# method for hashing passwords" You can achieve this using ASP.NET Identity v3.0 https://www.nuget.org/packages/Microsoft.AspNet.Identity.EntityFramework/3.0.0-rc1-final

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Security.Principal;

namespace HashTest{


    class Program
    {
        static void Main(string[] args)
        {

            WindowsIdentity wi = WindowsIdentity.GetCurrent();

            var ph = new PasswordHasher<WindowsIdentity>();

            Console.WriteLine(ph.HashPassword(wi,"test"));

            Console.WriteLine(ph.VerifyHashedPassword(wi,"AQAAAAEAACcQAAAAEA5S5X7dmbx/NzTk6ixCX+bi8zbKqBUjBhID3Dg1teh+TRZMkAy3CZC5yIfbLqwk2A==","test"));

        }
    }


}

Running Windows batch file commands asynchronously

Use the START command:

start [programPath]

If the path to the program contains spaces remember to add quotes. In this case you also need to provide a title for the opening console window

start "[title]" "[program path]"

If you need to provide arguments append them at the end (outside the command quotes)

start "[title]" "[program path]" [list of command args]

Use the /b option to avoid opening a new console window (but in that case you cannot interrupt the application using CTRL-C

JQuery datepicker not working

try adjusting the order in which your script runs. Place the script tag below the element it is trying to affect. Or leave it up at the top and wrap it in a $(document).ready() EDIT: and include the right file.

How to reload/refresh jQuery dataTable?

        if(data.length==0){
            alert("empty");
              $('#MembershipTable > tbody').empty();
            // $('#MembershipTable').dataTable().fnDestroy();
                    $('#MembershipTable_info').empty(); 
                    $("#MembershipTable_length").empty();
                    $("#MembershipTable_paginate").empty();

             html="<tr><td colspan='20'><b>No data available in Table</b> </td></tr>";
           $("#MembershipTable").append(html);
        }

        else{
             $('#MembershipTable').dataTable().fnDestroy();
            $('#MembershipTable > tbody').empty();

         for(var i=0; i<data.length; i++){
            //

.......}

SQL query to select dates between two dates

Select 
    * 
from 
    Calculation 
where 
    EmployeeId=1 and Date between #2011/02/25# and #2011/02/27#;

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

There is no option to downgrade XAMPP. XAMPP is hardcoded with specific PHP version to make sure all the modules are compatible and working properly. However if your project needs PHP 5.6, you can just install a older version of XAMPP with PHP 5.6 packaged into it.

Source: How to downgrade php from 5.5 to 5.3

Android Design Support Library expandable Floating Action Button(FAB) menu

Another option for the same result with ConstraintSet animation:

fab animation example

1) Put all the animated views in one ConstraintLayout

2) Animate it from code like this (if you want some more effects its up to you..this is only example)

menuItem1 and menuItem2 is the first and second FABs in menu, descriptionItem1 and descriptionItem2 is the description to the left of menu, parentConstraintLayout is the root ConstraintLayout wich contains all the animated views, isMenuOpened is some function to change open/closed flag in the state

I put animation code in extension file but its not necessary.

fun FloatingActionButton.expandMenu(
    menuItem1: View,
    menuItem2: View,
    descriptionItem1: TextView,
    descriptionItem2: TextView,
    parentConstraintLayout: ConstraintLayout,
    isMenuOpened: (Boolean)-> Unit
) {
    val constraintSet = ConstraintSet()
    constraintSet.clone(parentConstraintLayout)

    constraintSet.setVisibility(descriptionItem1.id, View.VISIBLE)
    constraintSet.clear(menuItem1.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem1.id, ConstraintSet.BOTTOM, this.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem1.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    constraintSet.setVisibility(descriptionItem2.id, View.VISIBLE)
    constraintSet.clear(menuItem2.id, ConstraintSet.TOP)
    constraintSet.connect(menuItem2.id, ConstraintSet.BOTTOM, menuItem1.id, ConstraintSet.TOP, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.START, this.id, ConstraintSet.START, 0)
    constraintSet.connect(menuItem2.id, ConstraintSet.END, this.id, ConstraintSet.END, 0)

    val transition = AutoTransition()
    transition.duration = 150
    transition.interpolator = AccelerateInterpolator()

    transition.addListener(object: Transition.TransitionListener {
        override fun onTransitionEnd(p0: Transition) {
            isMenuOpened(true)
        }
        override fun onTransitionResume(p0: Transition) {}
        override fun onTransitionPause(p0: Transition) {}
        override fun onTransitionCancel(p0: Transition) {}
        override fun onTransitionStart(p0: Transition) {}
    })

    TransitionManager.beginDelayedTransition(parentConstraintLayout, transition)
    constraintSet.applyTo(parentConstraintLayout)
}

Remove warning messages in PHP

in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.

In Wordpress hide Warnings and Notices add following code in wp-config.php file

ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Command-line tool for finding out who is locking a file

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • Cannot delete file: Access is denied.
  • There has been a sharing violation.
  • The source or destination file may be in use.
  • The file is in use by another program or user.
  • Make sure the disk is not full or write-protected and that the file is not currently in use.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

My solution was simple! I was actually having this error when checked out a repo from a svn server. I took following steps to remove error

  1. Cleaned solution
  2. Went to nuget package manager and uninstalled the entity framework.
  3. Removed DataModel and its .cs components.
  4. Shutdown the VS and opened again.
  5. Installed Entity Framework and Recreated entity model.
  6. Check if there is any files needed "Include in the solution". It worked like a charm

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

In android app Toolbar.setTitle method has no effect – application name is shown as title

Please see https://code.google.com/p/android/issues/detail?id=77763. Apparently it is supposed to work like that. Once you call the setSupportActionBar() method call, it then is the responsibility of the ActionBar delegate to route the call to the correct view.

What exactly are iterator, iterable, and iteration?

Iterators are objects that implement the iter and next methods. If those methods are defined, we can use for loop or comprehensions.

class Squares:
    def __init__(self, length):
        self.length = length
        self.i = 0
        
    def __iter__(self):
        print('calling __iter__') # this will be called first and only once
        return self
    
    def __next__(self): 
        print('calling __next__') # this will be called for each iteration
        if self.i >= self.length:
            raise StopIteration
        else:
            result = self.i ** 2
            self.i += 1
            return result

Iterators get exhausted. It means after you iterate over items, you cannot reiterate, you have to create a new object. Let's say you have a class, which holds the cities properties and you want to iterate over.

class Cities:
    def __init__(self):
        self._cities = ['Brooklyn', 'Manhattan', 'Prag', 'Madrid', 'London']
        self._index = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self._index >= len(self._cities):
            raise StopIteration
        else:
            item = self._cities[self._index]
            self._index += 1
            return item

Instance of class Cities is an iterator. However if you want to reiterate over cities, you have to create a new object which is an expensive operation. You can separate the class into 2 classes: one returns cities and second returns an iterator which gets the cities as init param.

class Cities:
    def __init__(self):
        self._cities = ['New York', 'Newark', 'Istanbul', 'London']        
    def __len__(self):
        return len(self._cities)



class CityIterator:
    def __init__(self, city_obj):
        # cities is an instance of Cities
        self._city_obj = city_obj
        self._index = 0
        
    def __iter__(self):
        return self
    
    def __next__(self):
        if self._index >= len(self._city_obj):
            raise StopIteration
        else:
            item = self._city_obj._cities[self._index]
            self._index += 1
            return item

Now if we need to create a new iterator, we do not have to create the data again, which is cities. We creates cities object and pass it to the iterator. But we are still doing extra work. We could implement this by creating only one class.

Iterable is a Python object that implements the iterable protocol. It requires only __iter__() that returns a new instance of iterator object.

class Cities:
    def __init__(self):
        self._cities = ['New York', 'Newark', 'Istanbul', 'Paris']
        
    def __len__(self):
        return len(self._cities)
    
    def __iter__(self):
        return self.CityIterator(self)
    
    class CityIterator:
        def __init__(self, city_obj):
            self._city_obj = city_obj
            self._index = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self._index >= len(self._city_obj):
                raise StopIteration
            else:
                item = self._city_obj._cities[self._index]
                self._index += 1
                return item

Iterators has __iter__ and __next__, iterables have __iter__, so we can say Iterators are also iterables but they are iterables that get exhausted. Iterables on the other hand never become exhausted because they always return a new iterator that is then used to iterate

You notice that the main part of the iterable code is in the iterator, and the iterable itself is nothing more than an extra layer that allows us to create and access the iterator.

Iterating over an iterable

Python has a built function iter() which calls the __iter__(). When we iterate over an iterable, Python calls the iter() which returns an iterator, then it starts using __next__() of iterator to iterate over the data.

NOte that in the above example, Cities creates an iterable but it is not a sequence type, it means we cannot get a city by an index. To fix this we should just add __get_item__ to the Cities class.

class Cities:
    def __init__(self):
        self._cities = ['New York', 'Newark', 'Budapest', 'Newcastle']
        
    def __len__(self):
        return len(self._cities)
    
    def __getitem__(self, s): # now a sequence type
        return self._cities[s]
    
    def __iter__(self):
        return self.CityIterator(self)
    
    class CityIterator:
        def __init__(self, city_obj):
            self._city_obj = city_obj
            self._index = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self._index >= len(self._city_obj):
                raise StopIteration
            else:
                item = self._city_obj._cities[self._index]
                self._index += 1
                return item

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

How do you get a string from a MemoryStream?

You can also use

Encoding.ASCII.GetString(ms.ToArray());

I don't think this is less efficient, but I couldn't swear to it. It also lets you choose a different encoding, whereas using a StreamReader you'd have to specify that as a parameter.

Regex Named Groups in Java

What kind of problem do you get with jregex? It worked well for me under java5 and java6.

Jregex does the job well (even if the last version is from 2002), unless you want to wait for javaSE 7.

What is SuppressWarnings ("unchecked") in Java?

It could also mean that the current Java type system version isn't good enough for your case. There were several JSR propositions / hacks to fix this: Type tokens, Super Type Tokens, Class.cast().

If you really need this supression, narrow it down as much as possible (e.g. don't put it onto the class itself or onto a long method). An example:

public List<String> getALegacyListReversed() {
   @SuppressWarnings("unchecked") List<String> list =
       (List<String>)legacyLibrary.getStringList();

   Collections.reverse(list);
   return list;
}

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

for me, that's caused by the SSL certificate not enabled in the K8S ingress. hope this helps someone

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

Java GC (Allocation Failure)

When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.

 -Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps 

SQL Server convert select a column and convert it to a string

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| RESULTS |
-----------
| 1,3,5,9 |

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

How to change the color of the axis, ticks and labels for a plot in matplotlib

  • For those using pandas.DataFrame.plot(), matplotlib.axes.Axes is returned when creating a plot from a dataframe. As such, the dataframe plot can be assigned to a variable, ax, which enables the usage of the associated formatting methods.
  • The default plotting backend for pandas, is matplotlib.
import pandas as pd

# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)

# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))

# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red') 
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both')  # 'both' refers to minor and major axes

enter image description here

How can I extract all values from a dictionary in Python?

If you want all of the values, use this:

dict_name_goes_here.values()

If you want all of the keys, use this:

dict_name_goes_here.keys()

IF you want all of the items (both keys and values), I would use this:

dict_name_goes_here.items()

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

'foo' was not declared in this scope c++

In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal(), the compiler needs to see the declaration:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc or *.cpp) file. This neatly solves the problem of needing all the functions to be declared.

Does Typescript support the ?. operator? (And, what's it called?)

As answered before, it's currently still being considered but it has been dead in the water for a few years by now.

Building on the existing answers, here's the most concise manual version I can think of:

jsfiddle

function val<T>(valueSupplier: () => T): T {
  try { return valueSupplier(); } catch (err) { return undefined; }
}

let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(val(() => obj1.a.b)); // 'c'

obj1 = { a: {} };
console.log(val(() => obj1.a.b)); // undefined
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

obj1 = {};
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

obj1 = null;
console.log(val(() => obj1.a.b) || 'Nothing'); // 'Nothing'

It simply silently fails on missing property errors. It falls back to the standard syntax for determining default value, which can be omitted completely as well.


Although this works for simple cases, if you need more complex stuff such as calling a function and then access a property on the result, then any other errors are swallowed as well. Bad design.

In the above case, an optimized version of the other answer posted here is the better option:

jsfiddle

function o<T>(obj?: T, def: T = {} as T): T {
    return obj || def;
}

let obj1: { a?: { b?: string }} = { a: { b: 'c' } };
console.log(o(o(o(obj1).a)).b); // 'c'

obj1 = { a: {} };
console.log(o(o(o(obj1).a)).b); // undefined
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

obj1 = {};
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

obj1 = null;
console.log(o(o(o(obj1).a)).b || 'Nothing'); // 'Nothing'

A more complex example:

o(foo(), []).map((n) => n.id)

You can also go the other way and use something like Lodash' _.get(). It is concise, but the compiler won't be able to judge the validity of the properties used:

console.log(_.get(obj1, 'a.b.c'));

PSEXEC, access denied errors

On Windows Server 2012 R2 I had trouble to run from user account

psexec -u administrator -p password \\machinename -h -s -d -accepteula cmd.exe

But it works fine if you run without parameters -h -s. That's why I use this to solve my trouble:

psexec -accepteula -u administrator -p password \\machinename %PathToLocalUtils%\psexec.exe -h -s -d  cmd.exe

Enable 'xp_cmdshell' SQL Server

You need to enable it. Check out the Permission section of the xp_cmdshell MSDN docs:

http://msdn.microsoft.com/en-us/library/ms190693.aspx:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

What are the obj and bin folders (created by Visual Studio) used for?

The obj folder holds object, or intermediate, files, which are compiled binary files that haven't been linked yet. They're essentially fragments that will be combined to produce the final executable. The compiler generates one object file for each source file, and those files are placed into the obj folder.

The bin folder holds binary files, which are the actual executable code for your application or library.

Each of these folders are further subdivided into Debug and Release folders, which simply correspond to the project's build configurations. The two types of files discussed above are placed into the appropriate folder, depending on which type of build you perform. This makes it easy for you to determine which executables are built with debugging symbols, and which were built with optimizations enabled and ready for release.

Note that you can change where Visual Studio outputs your executable files during a compile in your project's Properties. You can also change the names and selected options for your build configurations.

Resize image in PHP

Here is an extended version of the answer @Ian Atkin' gave. I found it worked extremely well. For larger images that is :). You can actually make smaller images larger if you're not careful. Changes: - Supports jpg,jpeg,png,gif,bmp files - Preserves transparency for .png and .gif - Double checks if the the size of the original isnt already smaller - Overrides the image given directly (Its what I needed)

So here it is. The default values of the function are the "golden rule"

function resize_image($file, $w = 1200, $h = 741, $crop = false)
   {
       try {
           $ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
           list($width, $height) = getimagesize($file);
           // if the image is smaller we dont resize
           if ($w > $width && $h > $height) {
               return true;
           }
           $r = $width / $height;
           if ($crop) {
               if ($width > $height) {
                   $width = ceil($width - ($width * abs($r - $w / $h)));
               } else {
                   $height = ceil($height - ($height * abs($r - $w / $h)));
               }
               $newwidth = $w;
               $newheight = $h;
           } else {
               if ($w / $h > $r) {
                   $newwidth = $h * $r;
                   $newheight = $h;
               } else {
                   $newheight = $w / $r;
                   $newwidth = $w;
               }
           }
           $dst = imagecreatetruecolor($newwidth, $newheight);

           switch ($ext) {
               case 'jpg':
               case 'jpeg':
                   $src = imagecreatefromjpeg($file);
                   break;
               case 'png':
                   $src = imagecreatefrompng($file);
                   imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
                   imagealphablending($dst, false);
                   imagesavealpha($dst, true);
                   break;
               case 'gif':
                   $src = imagecreatefromgif($file);
                   imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
                   imagealphablending($dst, false);
                   imagesavealpha($dst, true);
                   break;
               case 'bmp':
                   $src = imagecreatefrombmp($file);
                   break;
               default:
                   throw new Exception('Unsupported image extension found: ' . $ext);
                   break;
           }
           $result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
           switch ($ext) {
               case 'bmp':
                   imagewbmp($dst, $file);
                   break;
               case 'gif':
                   imagegif($dst, $file);
                   break;
               case 'jpg':
               case 'jpeg':
                   imagejpeg($dst, $file);
                   break;
               case 'png':
                   imagepng($dst, $file);
                   break;
           }
           return true;
       } catch (Exception $err) {
           // LOG THE ERROR HERE 
           return false;
       }
   }

"Too many values to unpack" Exception

That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3

def returnATupleWithThreeValues():
    return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c

But this raises your error

def returnATupleWithThreeValues():
    return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b

raises

Traceback (most recent call last):
  File "c.py", line 3, in ?
    a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack

Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.

How to play .wav files with java

Shortest form (without having to install random libraries) ?

public static void play(String filename)
{
    try
    {
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(new File(filename)));
        clip.start();
    }
    catch (Exception exc)
    {
        exc.printStackTrace(System.out);
    }
}

The only problem is there is no good way to make this method blocking to close and dispose the data after *.wav finishes. clip.drain() says it's blocking but it's not. The clip isn't running RIGHT AFTER start(). The only working but UGLY way I found is:

// ...
clip.start();
while (!clip.isRunning())
    Thread.sleep(10);
while (clip.isRunning())
    Thread.sleep(10);
clip.close();

How to read a text file in project's root directory?

Add a Resource File to your project (Right Click Project->Properties->Resources). Where it says "strings", you can switch to be "files". Choose "Add Resource" and select your file.

You can now reference your file through the Properties.Resources collection.

MVC 4 Razor File Upload

The Upload method's HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

<input type="file" name="file" />

Also, you could find the files in Request.Files:

[HttpPost]
public ActionResult Upload()
{
     if (Request.Files.Count > 0)
     {
         var file = Request.Files[0];

         if (file != null && file.ContentLength > 0)
         {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
            file.SaveAs(path);
         }
     }

     return RedirectToAction("UploadDocument");
 }

Using an index to get an item, Python

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

Selenium Webdriver move mouse to Point

If you are using a RemoteWebDriver, you can cast WebElement into RemoteWebElement. You can then call getCoordinates() on that object to get the coordinates.

        WebElement el = driver.findElementById("elementId");
        Coordinates c = ((RemoteWebElement)el).getCoordinates();
        driver.getMouse().mouseMove(c);

How to set default value for HTML select?

you can define attribute selected="selected" in Ex a

MySQL Error 1264: out of range value for column

The value 3172978990 is greater than 2147483647 – the maximum value for INT – hence the error. MySQL integer types and their ranges are listed here.

Also note that the (10) in INT(10) does not define the "size" of an integer. It specifies the display width of the column. This information is advisory only.

To fix the error, change your datatype to VARCHAR. Phone and Fax numbers should be stored as strings. See this discussion.

Aesthetics must either be length one, or the same length as the dataProblems

The problem is that skew isn't being subsetted in colour=factor(skew), so it's the wrong length. Since subset(skew, product == 'p1') is the same as subset(skew, product == 'p3'), in this case it doesn't matter which subset is used. So you can solve your problem with:

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

Note that most R users would write this as the more concise:

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I faced the same error when displaying YouTube links. For example: https://www.youtube.com/watch?v=8WkuChVeL0s

I replaced watch?v= with embed/ so the valid link will be: https://www.youtube.com/embed/8WkuChVeL0s

It works well.

Try to apply the same rule on your case.

SQL Select between dates

Special thanks to Jeff and vapcguy your interactivity is really encouraging.

Here is a more complex statement that is useful when the length between '/' is unknown::

SELECT * FROM tableName
WHERE julianday(
    substr(substr(date, instr(date, '/')+1), instr(substr(date, instr(date, '/')+1), '/')+1)
||'-'||
    case when length(
    substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1),'/')-1)
    )=2
    then
    substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1), '/')-1)
    else
    '0'||substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1), '/')-1)
    end
||'-'||
    case when length(substr(date,1, instr(date, '/')-1 )) =2
    then substr(date,1, instr(date, '/')-1 )
    else
    '0'||substr(date,1, instr(date, '/')-1 )
    end
) BETWEEN julianday('2015-03-14') AND julianday('2015-03-16') 

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

Download a specific tag with Git

Checking out Tags

If you want to view the versions of files a tag is pointing to, you can do a git checkout, though this puts your repository in “detached HEAD” state, which has some ill side effects:

$ git checkout 2.0.0
Note: checking out '2.0.0'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 99ada87... Merge pull request #89 from schacon/appendix-final

$ git checkout 2.0-beta-0.1
Previous HEAD position was 99ada87... Merge pull request #89 from schacon/appendix-final
HEAD is now at df3f601... add atlas.json and cover image

In “detached HEAD” state, if you make changes and then create a commit, the tag will stay the same, but your new commit won’t belong to any branch and will be unreachable, except for by the exact commit hash. Thus, if you need to make changes—say you’re fixing a bug on an older version, for instance—you will generally want to create a branch:

$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'

If you do this and make a commit, your version2 branch will be slightly different than your v2.0.0 tag since it will move forward with your new changes, so do be careful.

Run parallel multiple commands at once in the same terminal

I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.

https://github.com/k-bx/par

API is as simple as:

par "script1.sh" "script2.sh" "script3.sh"

Prefixing commands can be done via:

par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"

How to solve SyntaxError on autogenerated manage.py?

For future readers, I too had the same issue. Turns out installing Python directly from website as well as having another version from Anaconda caused this issue. I had to uninstall Python2.7 and only keep anaconda as the sole distribution.

Create HTML table using Javascript

In the html file there are three input boxes with userid,username,department respectively.

These inputboxes are used to get the input from the user.

The user can add any number of inputs to the page.

When clicking the button the script will enable the debugger mode.

In javascript, to enable the debugger mode, we have to add the following tag in the javascript.

/************************************************************************\

    Tools->Internet Options-->Advanced-->uncheck
    Disable script debugging(Internet Explorer)
    Disable script debugging(Other)

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Dynamic Table</title>

    <script language="javascript" type="text/javascript">

    // <!CDATA[

    function CmdAdd_onclick() {

    var newTable,startTag,endTag;



    //Creating a new table

    startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
    <TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"

    endTag="</TBODY></TABLE>"

    newTable=startTag;

    var trContents;

    //Get the row contents

    trContents=document.body.getElementsByTagName('TR');

    if(trContents.length>1)

    {

    for(i=1;i<trContents.length;i++)

    {

    if(trContents(i).innerHTML)

    {

    // Add previous rows

    newTable+="<TR>";

    newTable+=trContents(i).innerHTML;

    newTable+="</TR>";

    } 

    }

    }

    //Add the Latest row

    newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
        document.getElementById('userid').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('username').value +"</TD>";

    newTable+="<TD style=\"WIDTH: 120px\" >" +
        document.getElementById('department').value +"</TD><TR>";

    newTable+=endTag;

    //Update the Previous Table With New Table.

    document.getElementById('tableDiv').innerHTML=newTable;

    }

    // ]]>

    </script>

    </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <br />

    <label>UserID</label> 

    <input id="userid" type="text" /><br />

    <label>UserName</label> 

    <input id="username" type="text" /><br />

    <label>Department</label> 

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

    <center>

    <input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
    </center>



    </div>

    <div id="tableDiv" style="text-align:center" >

    <table id="mainTable">

    <tr style="width:120px " >

    <td >User ID</td>

    <td>User Name</td>

    <td>Department</td>

    </tr>

    </table>

    </div>

    </form>

    </body>

    </html>

How do I declare a global variable in VBA?

This is a question about scope.

If you only want the variables to last the lifetime of the function, use Dim (short for Dimension) inside the function or sub to declare the variables:

Function AddSomeNumbers() As Integer
    Dim intA As Integer
    Dim intB As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are no longer available since the function ended

A global variable (as SLaks pointed out) is declared outside of the function using the Public keyword. This variable will be available during the life of your running application. In the case of Excel, this means the variables will be available as long as that particular Excel workbook is open.

Public intA As Integer
Private intB As Integer

Function AddSomeNumbers() As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are still both available.  However, because intA is public,  '
'it can also be referenced from code in other modules. Because intB is private,'
'it will be hidden from other modules.

You can also have variables that are only accessible within a particular module (or class) by declaring them with the Private keyword.

If you're building a big application and feel a need to use global variables, I would recommend creating a separate module just for your global variables. This should help you keep track of them in one place.

When do we need curly braces around shell variables?

The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.

Classic Example 1) - shell variable without trailing whitespace

TIME=10

# WRONG: no such variable called 'TIMEsecs'
echo "Time taken = $TIMEsecs"

# What we want is $TIME followed by "secs" with no whitespace between the two.
echo "Time taken = ${TIME}secs"

Example 2) Java classpath with versioned jars

# WRONG - no such variable LATESTVERSION_src
CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar

# RIGHT
CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar

(Fred's answer already states this but his example is a bit too abstract)

How to grant permission to users for a directory using command line in Windows?

Corrupt Permissions: Regaining access to a folder and its sub-objects

Although most of the answers posted in reply to the question have some merit, IMHO none of them give a complete solution. The following (might be) a perfect solution for Windows 7 if you are locked-out of a folder by corrupted permission settings:

icacls "c:\folder" /remove:d /grant:r Everyone:(OI)(CI)F /T  

For Windows 10 the user/SID must be specified after the /remove:d option:

icacls "c:\folder" /remove:d Everyone /grant:r Everyone:(OI)(CI)F /T  

.
Notes:

  1. The command is applied to the specified directory.

  2. Specifying the user "Everyone" sets the widest possible permission, as it includes every possible user.

  3. The option "/remove:d" deletes any explicit DENY settings that may exist, as those override explicit ALLOW settings: a necessary preliminary to creating a new ALLOW setting. This is only a precaution, as there is often no DENY setting present, but better safe than sorry.

  4. The option "/grant" creates a new ALLOW setting, an explicit permission that replaces (":r") any and all explicit ALLOW settings that may exist.

  5. The "F" parameter (i.e. the permission created) makes this a grant of FULL control.

  6. The "/T" parameter adds recursion, applying these changes to all current sub-objects in the specified directory (i.e. files and subfolders), as well as the folder itself.

  7. The "(OI)" and "(CI)" parameters also add recursion, applying these changes to sub-objects created subsequently.
    .

ADDENDUM (2019/02/10) -

The Windows 10 command line above was kindly suggested to me today, so here it is. I haven't got Windows 10 to test it, but please try it out if you have (and then will you please post a comment below).

The change only concerns removing the DENY setting as a first step. There might well not be any DENY setting present, so that option might make no difference. My understanding is, on Windows 7, that you don't need to specify a user after /remove:d but I might be wrong about that!

.

ADDENDUM (2019/11/21) -

User astark recommends replacing Everyone with the term *S-1-1-0 in order for the command to be language independent. I only have an English install of Windows, so I can't test this proposal, but it seems reasonable.

How to use a class from one C# project with another C# project

  1. In the 'Solution Explorer' tree, expand the P2 project and then right-click the project and select 'Add Reference' from the menu.
  2. On the 'Add Reference' dialog, select the 'Projects' tab and select your P1 project.
  3. If you are using namespaces then you will need to import the namespaces for your P1 types by adding 'using' statements to your files in P2.

Note that the types in P1 that you wish to access directly must have a sufficient access level: typically this means they must be made public.

How do I add one month to current date in Java?

you can use DateUtils class in org.apache.commons.lang3.time package

DateUtils.addMonths(new Date(),1);

Working with $scope.$emit and $scope.$on

To send $scope object from one controller to another, I will discuss about $rootScope.$broadcast and $rootScope.$emit here as they are used most.

Case 1:

$rootScope.$broadcast:-

$rootScope.$broadcast('myEvent',$scope.data);//Here `myEvent` is event name

$rootScope.$on('myEvent', function(event, data) {} //listener on `myEvent` event

$rootScope listener are not destroyed automatically. You need to destroy it using $destroy. It is better to use $scope.$on as listeners on $scope are destroyed automatically i.e. as soon as $scope is destroyed.

$scope.$on('myEvent', function(event, data) {}

Or,

  var customeEventListener = $rootScope.$on('myEvent', function(event, data) {

  }
  $scope.$on('$destroy', function() {
        customeEventListener();
  });

Case 2:

$rootScope.$emit:

   $rootScope.$emit('myEvent',$scope.data);

   $rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works

The major difference in $emit and $broadcast is that $rootScope.$emit event must be listened using $rootScope.$on, because the emitted event never comes down through the scope tree..
In this case also you must destroy the listener as in the case of $broadcast.

Edit:

I prefer not to use $rootScope.$broadcast + $scope.$on but use $rootScope.$emit+ $rootScope.$on. The $rootScope.$broadcast + $scope.$on combo can cause serious performance problems. That is because the event will bubble down through all scopes.

Edit 2:

The issue addressed in this answer have been resolved in angular.js version 1.2.7. $broadcast now avoids bubbling over unregistered scopes and runs just as fast as $emit.

Download and open PDF file using Ajax

_x000D_
_x000D_
var xhr;_x000D_
var beforeSend = function(){_x000D_
    $('#pleasewaitDL').modal('show');_x000D_
}_x000D_
$(function () {_x000D_
    $('#print_brochure_link').click(function(){_x000D_
        beforeSend();_x000D_
        xhr = new XMLHttpRequest();_x000D_
        xhr.open("GET",$('#preparedPrintModalForm').attr('action'), true); _x000D_
        xhr.responseType = "blob";_x000D_
        xhr.onload = function (e) {_x000D_
            if (this.status === 200) {_x000D_
                var file = window.URL.createObjectURL(this.response);_x000D_
                var a = document.createElement("a");_x000D_
                a.href = file;_x000D_
                a.download = this.response.name || "Property Brochure";_x000D_
                console.log(file);_x000D_
                document.body.appendChild(a);_x000D_
                a.click();_x000D_
                _x000D_
                window.onfocus = function () {                     _x000D_
                  document.body.removeChild(a)_x000D_
                }_x000D_
                $('#pleasewaitDL').modal('hide');_x000D_
            };_x000D_
        };_x000D_
        xhr.send($('#preparedPrintModalForm').serialize());_x000D_
    });_x000D_
    $('#pleasewaitDLCancel').click(function() {_x000D_
        xhr.abort();_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

getting error while updating Composer

A lot of good answers already for Ubuntu. I'm on Linux and had the same problem but none of the commands above worked for me.

With Linux and php70 I used the following command which worked great:

sudo yum install php70-mbstring -y

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

Open a URL in a new tab (and not a new window)

Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)

CSS3 proposed target-new, but the specification was abandoned.

The reverse is not true; by specifying certain window features for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.

Could not find the main class, program will exit

Extract the jar and compare the contents of the manifest inside the jar with your external manifest.txt. It is quite possible that you will locate the problem.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

I struggled with this, as well. My exact issue was that I had an ASMX Web Service that, when I entered a parameter into a web method and tested it, then it would give me the 404. The particular method had worked fine in the past and hadn't been changed, only re-published. Then I got here and tried all of the posted answers & nothing helped.

My ultimate solution? I know this is drastic, but I just created a new Visual Studio solution and web project. Selected MVC, then I did an "Add" > "New Item", selected "Visual C#" > "Web" and "Web Service (ASMX)" under that. I copied all of my old code-behind code, then I took note of the namespace it gave the new file in my new project, then pasted all of my old code into the new code-behind file in the new project and put the namespace back to what it had been.

Then I created my folders in my project that I had before using Visual Studio to do "Add" > "New Folder", then copied back in my files into the folders from my other project using Windows Explorer, then right-clicked each folder in Visual Studio and did "Add" > "Existing Item..." and pulled the items in those folders into my new project's Visual Studio folders. I referenced all my .NET assemblies again, having both projects open so I could compare which ones I had referenced, previously (there were several). I had to name my new project slightly different - basically I did something comparable to "GeneralWebApp" instead of "MyWebApp", for example - so I had to do a "Replace All" in my whole solution to replace that name, so it would get the right namespace for all my files.

Then I did a "Rebuild All" on the project, then started it up with the "Play" button Visual Studio gives when I got it to build correctly. It worked fine. So I published it, and everything was fine on the server where I published it, when I ran it from there. I have no explanation as to what happened, but that's how I got through it. It's not a bad test just to see if something Visual Studio is doing has mucked it up.

Color different parts of a RichTextBox string

I have expanded the method with font as a parameter:

public static void AppendText(this RichTextBox box, string text, Color color, Font font)
{
    box.SelectionStart = box.TextLength;
    box.SelectionLength = 0;

    box.SelectionColor = color;
    box.SelectionFont = font;
    box.AppendText(text);
    box.SelectionColor = box.ForeColor;
}

What is the difference between atomic / volatile / synchronized?

You are specifically asking about how they internally work, so here you are:

No synchronization

private int counter;

public int getNextUniqueIndex() {
  return counter++; 
}

It basically reads value from memory, increments it and puts back to memory. This works in single thread but nowadays, in the era of multi-core, multi-CPU, multi-level caches it won't work correctly. First of all it introduces race condition (several threads can read the value at the same time), but also visibility problems. The value might only be stored in "local" CPU memory (some cache) and not be visible for other CPUs/cores (and thus - threads). This is why many refer to local copy of a variable in a thread. It is very unsafe. Consider this popular but broken thread-stopping code:

private boolean stopped;

public void run() {
    while(!stopped) {
        //do some work
    }
}

public void pleaseStop() {
    stopped = true;
}

Add volatile to stopped variable and it works fine - if any other thread modifies stopped variable via pleaseStop() method, you are guaranteed to see that change immediately in working thread's while(!stopped) loop. BTW this is not a good way to interrupt a thread either, see: How to stop a thread that is running forever without any use and Stopping a specific java thread.

AtomicInteger

private AtomicInteger counter = new AtomicInteger();

public int getNextUniqueIndex() {
  return counter.getAndIncrement();
}

The AtomicInteger class uses CAS (compare-and-swap) low-level CPU operations (no synchronization needed!) They allow you to modify a particular variable only if the present value is equal to something else (and is returned successfully). So when you execute getAndIncrement() it actually runs in a loop (simplified real implementation):

int current;
do {
  current = get();
} while(!compareAndSet(current, current + 1));

So basically: read; try to store incremented value; if not successful (the value is no longer equal to current), read and try again. The compareAndSet() is implemented in native code (assembly).

volatile without synchronization

private volatile int counter;

public int getNextUniqueIndex() {
  return counter++; 
}

This code is not correct. It fixes the visibility issue (volatile makes sure other threads can see change made to counter) but still has a race condition. This has been explained multiple times: pre/post-incrementation is not atomic.

The only side effect of volatile is "flushing" caches so that all other parties see the freshest version of the data. This is too strict in most situations; that is why volatile is not default.

volatile without synchronization (2)

volatile int i = 0;
void incIBy5() {
  i += 5;
}

The same problem as above, but even worse because i is not private. The race condition is still present. Why is it a problem? If, say, two threads run this code simultaneously, the output might be + 5 or + 10. However, you are guaranteed to see the change.

Multiple independent synchronized

void incIBy5() {
  int temp;
  synchronized(i) { temp = i }
  synchronized(i) { i = temp + 5 }
}

Surprise, this code is incorrect as well. In fact, it is completely wrong. First of all you are synchronizing on i, which is about to be changed (moreover, i is a primitive, so I guess you are synchronizing on a temporary Integer created via autoboxing...) Completely flawed. You could also write:

synchronized(new Object()) {
  //thread-safe, SRSLy?
}

No two threads can enter the same synchronized block with the same lock. In this case (and similarly in your code) the lock object changes upon every execution, so synchronized effectively has no effect.

Even if you have used a final variable (or this) for synchronization, the code is still incorrect. Two threads can first read i to temp synchronously (having the same value locally in temp), then the first assigns a new value to i (say, from 1 to 6) and the other one does the same thing (from 1 to 6).

The synchronization must span from reading to assigning a value. Your first synchronization has no effect (reading an int is atomic) and the second as well. In my opinion, these are the correct forms:

void synchronized incIBy5() {
  i += 5 
}

void incIBy5() {
  synchronized(this) {
    i += 5 
  }
}

void incIBy5() {
  synchronized(this) {
    int temp = i;
    i = temp + 5;
  }
}

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

Convert Go map to json

It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal.

json: unsupported type: map[int]main.Foo

JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.

You have two options:

1 Use map[string]Foo and convert the index to string (using fmt.Sprint for example):

datas := make(map[string]Foo, N)

for i := 0; i < 10; i++ {
    datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)

2 Simply just use a slice (javascript array):

datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
    datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)

playground

How to force Docker for a clean build of an image

To ensure that your build is completely rebuild, including checking the base image for updates, use the following options when building:

--no-cache - This will force rebuilding of layers already available

--pull - This will trigger a pull of the base image referenced using FROM ensuring you got the latest version.

The full command will therefore look like this:

docker build --pull --no-cache --tag myimage:version .

Same options are available for docker-compose:

docker-compose build --no-cache --pull

Note that if your docker-compose file references an image, the --pull option will not actually pull the image if there is one already.

To force docker-compose to re-pull this, you can run:

docker-compose pull

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

Android Studio: Can't start Git

In Android Studio, goto File->Settings->Version Control->Git. Set the 'Path to Git Executable' to point to git.exe. Verify by clicking Test.

C# convert int to string with padding zeros?

public static string ToLeadZeros(this int strNum, int num)
{
    var str = strNum.ToString();
    return str.PadLeft(str.Length + num, '0');
}

// var i = 1;
// string num = i.ToLeadZeros(5);

How do you post to the wall on a facebook page (not profile)

Harish has the answer here - except you need to request manage_pages permission when authenticating and then using the page-id instead of me when posting....

$result = $facebook->api('page-id/feed/','post',$attachment);

JavaFX Application Icon

What do you think about creating new package i.e image.icons in your src directory and moving there you .png images? Than you just need to write:

Image image = new Image("/image/icons/nameOfImage.png");
primaryStage.getIcons().add(image);

This solution works for me perfectly, but still I'm not sure if it's correct (beginner here).

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

http://en.wikipedia.org/wiki/POSIX_Threads

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

Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:

git push origin HEAD: <My-remote-branch>

Then

git checkout <My-remote-branch>

Then

git pull

I finally got my all changes in my branch that I made in detach HEAD.

Expanding a parent <div> to the height of its children

Instead of setting height property, use min-height.

Regex to replace multiple spaces with a single space

I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.

@slightlytyler helped me in coming with the below approach.

_x000D_
_x000D_
const testStr = "I   LOVE    STACKOVERFLOW   LOL";_x000D_
_x000D_
const removeSpaces = str  => {_x000D_
  const chars = str.split('');_x000D_
  const nextChars = chars.reduce(_x000D_
    (acc, c) => {_x000D_
      if (c === ' ') {_x000D_
        const lastChar = acc[acc.length - 1];_x000D_
        if (lastChar === ' ') {_x000D_
          return acc;_x000D_
        }_x000D_
      }_x000D_
      return [...acc, c];_x000D_
    },_x000D_
    [],_x000D_
  );_x000D_
  const nextStr = nextChars.join('');_x000D_
  return nextStr_x000D_
};_x000D_
_x000D_
console.log(removeSpaces(testStr));
_x000D_
_x000D_
_x000D_

Application not picking up .css file (flask/python)

You need to have a 'static' folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it.

Your directory structure for css should be like:

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /static
        /styles
            - mainpage.css

Notice that your /styles directory should be under /static

Then, do this

<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">

Flask will now look for the css file under static/styles/mainpage.css

How do I add an "Add to Favorites" button or link on my website?

This code is the corrected version of iambriansreed's answer:

<script type="text/javascript">
    $(function() {
        $("#bookmarkme").click(function() {
            // Mozilla Firefox Bookmark
            if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                window.sidebar.addPanel(location.href,document.title,"");
            } else if( /*@cc_on!@*/false) { // IE Favorite
                window.external.AddFavorite(location.href,document.title); 
            } else { // webkit - safari/chrome
                alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
            }
        });
    });
</script>

How to calculate percentage when old value is ZERO

use below code, as this is 100% growth rate in case of 0 to any number :

IFERROR((NEW-OLD)/OLD,100%)

How do I assign a null value to a variable in PowerShell?

If the goal simply is to list all computer objects with an empty description attribute try this

import-module activedirectory  
$domain = "domain.example.com" 
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }

How to make a text box have rounded corners?

This can be done with CSS3:

<input type="text" />

input
{
  -moz-border-radius: 15px;
 border-radius: 15px;
    border:solid 1px black;
    padding:5px;
}

http://jsfiddle.net/UbSkn/1/


However, an alternative would be to put the input inside a div with a rounded background, and no border on the input

Best way to generate a random float in C#

Any reason not to use Random.NextDouble and then cast to float? That will give you a float between 0 and 1.

If you want a different form of "best" you'll need to specify your requirements. Note that Random shouldn't be used for sensitive matters such as finance or security - and you should generally reuse an existing instance throughout your application, or one per thread (as Random isn't thread-safe).

EDIT: As suggested in comments, to convert this to a range of float.MinValue, float.MaxValue:

// Perform arithmetic in double type to avoid overflowing
double range = (double) float.MaxValue - (double) float.MinValue;
double sample = rng.NextDouble();
double scaled = (sample * range) + float.MinValue;
float f = (float) scaled;

EDIT: Now you've mentioned that this is for unit testing, I'm not sure it's an ideal approach. You should probably test with concrete values instead - making sure you test with samples in each of the relevant categories - infinities, NaNs, denormal numbers, very large numbers, zero, etc.

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

Response Buffer Limit Exceeded

The reason this is happening is because buffering is turned on by default, and IIS 6 cannot handle the large response.

In Classic ASP, at the top of your page, after <%@Language="VBScript"%> add: <%Response.Buffer = False%>

In ASP.NET, you would add Buffer="False" to your Page directive. For example: <%@Page Language="C#" Buffer="False"%>

How to print all session variables currently set?

this worked for me:-

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>

thanks for sharing code...

Array
(    
    [__ci_last_regenerate] => 1490879962

    [user_id] => 3

    [designation_name] => Admin
    [region_name] => admin
    [territory_name] => admin
    [designation_id] => 2
    [region_id] => 1
    [territory_id] => 1
    [employee_user_id] => mosin11
)

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

WebDriverException: Element is not clickable at point (x, y)

This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.

The fields of this exception are :

  • BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL
  • DRIVER_INFO : public static final java.lang.String DRIVER_INFO
  • SESSION_ID : public static final java.lang.String SESSION_ID

About your individual usecase, the error tells it all :

WebDriverException: Element is not clickable at point (x, y). Other element would receive the click 

It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).

Solution

The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:

1. Element not getting clicked due to JavaScript or AJAX calls present

Try to use Actions Class:

WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

2. Element not getting clicked as it is not within Viewport

Try to use JavascriptExecutor to bring the element within the Viewport:

WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement); 

3. The page is getting refreshed before the element gets clickable.

In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.

4. Element is present in the DOM but not clickable.

In this case induce ExplicitWait with ExpectedConditions set to elementToBeClickable for the element to be clickable:

WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));

5. Element is present but having temporary Overlay.

In this case, induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));

6. Element is present but having permanent Overlay.

Use JavascriptExecutor to send the click directly on the element.

WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);

ActionBarActivity is deprecated

android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."

checkout changes for Android Support Library, revision 22.1.0 (April 2015)

AJAX reload page with POST

By using jquery ajax you can reload your page

$.ajax({
    type: "POST",
    url: "packtypeAdd.php",
    data: infoPO,
    success: function() {   
        location.reload();  
    }
});

How does Python return multiple values from a function?

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

I hope my answer could help you. Happy coding.

Why can't DateTime.Parse parse UTC date

You need to specify the format:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 
    CultureInfo.InvariantCulture);

How to create Java gradle project

To create a Java project: create a new project directory, jump into it and execute

gradle init --type java-library

Source folders and a Gradle build file (including a wrapper) will be build.