Programs & Examples On #Minimize

To minimize is to replace one object with another object that can restore the original when selected.

Disabling Minimize & Maximize On WinForm?

Bind a handler to the FormClosing event, then set e.Cancel = true, and set the form this.WindowState = FormWindowState.Minimized.

If you want to ever actually close the form, make a class-wide boolean _close and, in your handler, set e.Cancel to !_close, so that whenever the user clicks the X on the window, it doesn't close, but you can still close it (without just killing it) with close = true; this.Close();

(And just to make my answer complete) set MaximizeBox and MinimizeBox form properties to False.

querySelector, wildcard element match?

Set the tagName as an explicit attribute:

for(var i=0,els=document.querySelectorAll('*'); i<els.length;
          els[i].setAttribute('tagName',els[i++].tagName) );

I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.

document.querySelectorAll('[tagName$="_Sequence"]')

I didn't say it would be pretty :) PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

How to access component methods from “outside” in ReactJS?

Since React 0.12 the API is slightly changed. The valid code to initialize myChild would be the following:

var Child = React.createClass({…});
var myChild = React.render(React.createElement(Child, {}), mountNode);
myChild.someMethod();

Installed SSL certificate in certificate store, but it's not in IIS certificate list

I had a key file & a crt file but it wouldn't show in IIS because I couldn't attach the key to the certificate during the import. Ended up creating a pfx file containing the certificate & the key, and after that it worked (When importing to the computer and not local user)

Created the file with OpenSSL (Download first).

openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt

Ways to save enums in database

For a large database, I am reluctant to lose the size and speed advantages of the numeric representation. I often end up with a database table representing the Enum.

You can enforce database consistency by declaring a foreign key -- although in some cases it might be better to not declare that as a foreign key constraint, which imposes a cost on every transaction. You can ensure consistency by periodically doing a check, at times of your choosing, with:

SELECT reftable.* FROM reftable
  LEFT JOIN enumtable ON reftable.enum_ref_id = enumtable.enum_id
WHERE enumtable.enum_id IS NULL;

The other half of this solution is to write some test code that checks that the Java enum and the database enum table have the same contents. That's left as an exercise for the reader.

How to pass the button value into my onclick event function?

Maybe you can take a look at closure in JavaScript. Here is a working solution:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8" />_x000D_
        <title>Test</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <p class="button">Button 0</p>_x000D_
        <p class="button">Button 1</p>_x000D_
        <p class="button">Button 2</p>_x000D_
        <script>_x000D_
            var buttons = document.getElementsByClassName('button');_x000D_
            for (var i=0 ; i < buttons.length ; i++){_x000D_
              (function(index){_x000D_
                buttons[index].onclick = function(){_x000D_
                  alert("I am button " + index);_x000D_
                };_x000D_
              })(i)_x000D_
            }_x000D_
        </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

stale element reference: element is not attached to the page document

To handle it, I use the following click method. This will attempt to find and click the element. If the DOM changes between the find and click, it will try again. The idea is that if it failed and I try again immediately the second attempt will succeed. If the DOM changes are very rapid then this will not work.

public boolean retryingFindClick(By by) {
    boolean result = false;
    int attempts = 0;
    while(attempts < 2) {
        try {
            driver.findElement(by).click();
            result = true;
            break;
        } catch(StaleElementException e) {
        }
        attempts++;
    }
    return result;
}

HTML/Javascript: how to access JSON data loaded in a script tag with src set

I agree with Ben. You cannot load/import the simple JSON file.

But if you absolutely want to do that and have flexibility to update json file, you can

my-json.js

   var myJSON = {
      id: "12ws",
      name: "smith"
    }

index.html

<head>
  <script src="my-json.js"></script>
</head>
<body onload="document.getElementById('json-holder').innerHTML = JSON.stringify(myJSON);">
  <div id="json-holder"></div>
</body>

Disabling and enabling a html input button

 <!--Button Disable Script-->
    <script type="text/javascript">
        function DisableButton() {
            document.getElementById("<%=btnSave.ClientID %>").disabled = true;
        }
        window.onbeforeunload = DisableButton;
    </script>
    <!--Button Disable Script-->

SQL to generate a list of numbers from 1 to 100

Using GROUP BY CUBE:

SELECT ROWNUM
FROM (SELECT 1 AS c FROM dual GROUP BY CUBE(1,1,1,1,1,1,1) ) sub
WHERE ROWNUM <=100;

Rextester Demo

Codeigniter displays a blank page instead of error messages

i was also facing the same problem and tried almost all the things but finally i restarted my server and i found everything started working fine..i don't know how.....i think it was some server side problem that's why my PHP CODE was not giving any error.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Yes, there is a maximum, but it's system dependent. Try it and see, doubling until you hit a limit then searching down. At least with Sun JRE 1.6 on linux you get interesting if not always informative error messages (peregrino is netbook running 32 bit ubuntu with 2G RAM and no swap):

peregrino:$ java -Xmx4096M -cp bin WheelPrimes 
Invalid maximum heap size: -Xmx4096M
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.

peregrino:$ java -Xmx4095M -cp bin WheelPrimes 
Error occurred during initialization of VM
Incompatible minimum and maximum heap sizes specified

peregrino:$ java -Xmx4092M -cp bin WheelPrimes 
Error occurred during initialization of VM
The size of the object heap + VM data exceeds the maximum representable size

peregrino:$ java -Xmx4000M -cp bin WheelPrimes 
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

(experiment reducing from 4000M until)

peregrino:$ java -Xmx2686M -cp bin WheelPrimes 
(normal execution)

Most are self explanatory, except -Xmx4095M which is rather odd (maybe a signed/unsigned comparison?), and that it claims to reserve 2686M on a 2GB machine with no swap. But it does hint that the maximum size is 4G not 2G for a 32 bit VM, if the OS allows you to address that much.

How to calculate time difference in java?

import java.sql.*;

class Time3 {

    public static void main(String args[]){ 
        String time1 = "01:03:23";
        String time2 = "02:32:00";
        long difference ;
        Time t1 = Time.valueOf(time1);
        Time t2 = Time.valueOf(time2);
        if(t2.getTime() >= t1.getTime()){
            difference = t2.getTime() - t1.getTime() -19800000;
        }
        else{
            difference = t1.getTime() - t2.getTime() -19800000;
        }

        java.sql.Time time = new java.sql.Time(difference); 
        System.out.println(time);
    } 

} 

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

How to run eclipse in clean mode? what happens if we do so?

This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.

  1. Open command prompt (cmd)
  2. Go to eclipse application location (D:\eclipse)
  3. Run command eclipse -clean

How do you dynamically add elements to a ListView on Android?

Code for MainActivity.java file.

public class MainActivity extends Activity {

    ListView listview;
    Button Addbutton;
    EditText GetValue;
    String[] ListElements = new String[] {
        "Android",
        "PHP"
    };

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

        listview = (ListView) findViewById(R.id.listView1);
        Addbutton = (Button) findViewById(R.id.button1);
        GetValue = (EditText) findViewById(R.id.editText1);

        final List < String > ListElementsArrayList = new ArrayList < String >
            (Arrays.asList(ListElements));


        final ArrayAdapter < String > adapter = new ArrayAdapter < String >
            (MainActivity.this, android.R.layout.simple_list_item_1,
                ListElementsArrayList);

        listview.setAdapter(adapter);

        Addbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                ListElementsArrayList.add(GetValue.getText().toString());
                adapter.notifyDataSetChanged();
            }
        });
    }
}

Code for activity_main.xml layout file.

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.listviewaddelementsdynamically_android_examples
    .com.MainActivity" >

  <Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:text="ADD Values to listview" />

  <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="26dp"
    android:ems="10"
    android:hint="Add elements listView" />

  <ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    android:layout_centerHorizontal="true" >
  </ListView>

</RelativeLayout>

ScreenShot

enter image description here

ORDER BY date and time BEFORE GROUP BY name in mysql

This is not the exact answer, but this might be helpful for the people looking to solve some problem with the approach of ordering row before group by in mysql.

I came to this thread, when I wanted to find the latest row(which is order by date desc but get the only one result for a particular column type, which is group by column name).

One other approach to solve such problem is to make use of aggregation.

So, we can let the query run as usual, which sorted asc and introduce new field as max(doc) as latest_doc, which will give the latest date, with grouped by the same column.

Suppose, you want to find the data of a particular column now and max aggregation cannot be done. In general, to finding the data of a particular column, you can make use of GROUP_CONCAT aggregator, with some unique separator which can't be present in that column, like GROUP_CONCAT(string SEPARATOR ' ') as new_column, and while you're accessing it, you can split/explode the new_column field.

Again, this might not sound to everyone. I did it, and liked it as well because I had written few functions and I couldn't run subqueries. I am working on codeigniter framework for php.

Not sure of the complexity as well, may be someone can put some light on that.

Regards :)

How to get char from string by index?

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

For Negative index, index ranges from -1 to -45

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,

In [8]: x[-44]
Out[8]: 'n'

Other, index's examples,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

How to find the highest value of a column in a data frame in R?

Another way would be to use ?pmax

do.call('pmax', c(as.data.frame(t(ozone)),na.rm=TRUE))
#[1]  41.0 313.0  20.1  74.0   5.0   9.0

Using Python to execute a command on every file in a folder

To find all the filenames use os.listdir().

Then you loop over the filenames. Like so:

import os
for filename in os.listdir('dirname'):
     callthecommandhere(blablahbla, filename, foo)

If you prefer subprocess, use subprocess. :-)

Changing the browser zoom level

Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.

    var currFFZoom = 1;
    var currIEZoom = 100;

    $('#plusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom += step; 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');
        } else {
            var step = 2;
            currIEZoom += step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

    $('#minusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom -= step;                 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');

        } else {
            var step = 2;
            currIEZoom -= step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

How to square all the values in a vector in R?

This is another simple way:

sq_data <- data**2

What's the simplest way to extend a numpy array in 2 dimensions?

I find it much easier to "extend" via assigning in a bigger matrix. E.g.

import numpy as np
p = np.array([[1,2], [3,4]])
g = np.array(range(20))
g.shape = (4,5)
g[0:2, 0:2] = p

Here are the arrays:

p

   array([[1, 2],
       [3, 4]])

g:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

and the resulting g after assignment:

   array([[ 1,  2,  2,  3,  4],
       [ 3,  4,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

Get the first key name of a JavaScript object

With Underscore.js, you could do

_.find( {"one": [1,2,3], "two": [4,5,6]} )

It will return [1,2,3]

Return first N key:value pairs from dict

Were d is your dictionary and n is the printing number:

for idx, (k, v) in enumerate(d):
  if idx == n: break
  print((k, v))

Casting your dictionary to list can be slow. Your dictionary may be too large and you don't need to cast all of it just for printing a few of the first.

Test a weekly cron job

The solution I am using is as follows:

  1. Edit crontab(use command :crontab -e) to run the job as frequently as needed (every 1 minute or 5 minutes)
  2. Modify the shell script which should be executed using cron to prints the output into some file (e.g: echo "Working fine" >>
    output.txt)
  3. Check the output.txt file using the command : tail -f output.txt, which will print the latest additions into this file, and thus you can track the execution of the script

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Calculate the number of business days between two dates?

I'll just share my solution. It worked for me, maybe I just don't notice/know that theres a bug. I started by getting the first incomplete week if there's any. a complete week was from sunday for saturday, so if the (int)_now.DayOfWeek was not 0(Sunday), the first week was incomplete.

I just subtract 1 to first weeks count for the first week's saturday then add it to new count;

Then I get the last incomplete week, then subtract 1 for it's sunday then add to new count.

Then finally, the number of complete weeks multiply by 5(weekdays) was added to new count.

public int RemoveNonWorkingDays(int numberOfDays){

            int workingDays = 0;

            int firstWeek = 7 - (int)_now.DayOfWeek;

            if(firstWeek < 7){

                if(firstWeek > numberOfDays)
                    return numberOfDays;

                workingDays += firstWeek-1;
                numberOfDays -= firstWeek;
            }


            int lastWeek = numberOfDays % 7;

            if(lastWeek > 0){

                numberOfDays -= lastWeek;
                workingDays += lastWeek - 1;

            }

            workingDays += (numberOfDays/7)*5;

            return workingDays;
        }

How to localise a string inside the iOS info.plist file?

In my case everything was set up correctly but still the InfoPlist.strings file was not found.

The only thing that really worked was, to remove and add the InfoPlist.strings files again to the project.

How to pass all arguments passed to my bash script to a function of mine?

abc "$@"

$@ represents all the parameters given to your bash script.

How do I create a random alpha-numeric string in C++?

Rather than manually looping, prefer using the appropriate C++ algorithm, in this case std::generate_n, with a proper random number generator:

auto generate_random_alphanumeric_string(std::size_t len) -> std::string {
    static constexpr auto chars =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    thread_local auto rng = random_generator<>();
    auto dist = std::uniform_int_distribution{{}, std::strlen(chars) - 1};
    auto result = std::string(len, '\0');
    std::generate_n(begin(result), len, [&]() { return chars[dist(rng)]; });
    return result;
}

This is close to something I would call the “canonical” solution for this problem.

Unfortunately, correctly seeding a generic C++ random number generator (e.g. MT19937) is really hard. The above code therefore uses a helper function template, random_generator:

template <typename T = std::mt19937>
auto random_generator() -> T {
    auto constexpr seed_bytes = sizeof(typename T::result_type) * T::state_size;
    auto constexpr seed_len = seed_bytes / sizeof(std::seed_seq::result_type);
    auto seed = std::array<std::seed_seq::result_type, seed_len>();
    auto dev = std::random_device();
    std::generate_n(begin(seed), seed_len, std::ref(dev));
    auto seed_seq = std::seed_seq(begin(seed), end(seed));
    return T{seed_seq};
}

This is complex and relatively inefficient. Luckily it’s used to initialise a thread_local variable and is therefore only invoked once per thread.

Finally, the necessary includes for the above are:

#include <algorithm>
#include <array>
#include <cstring>
#include <functional>
#include <random>
#include <string>

The above code uses class template argument deduction and thus requires C++17. It can be trivially adapted for earlier versions by adding the required template arguments.

How to send push notification to web browser?

So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.

Update (May 2018): Here is a comprehensive and a very well written doc on web push notification from Google.

Answer to the original questions asked 3 years ago:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?

Answer: Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging (FCM). This supports all platforms including web browsers.

  1. If not via GCM can we have our own back-end to do the same?

Answer: Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.

Check this codelab from Google to better understand the implementation.

Some Tutorials:

  • Implementing push notification in Django Here.
  • Using flask to send push notification Here & Here.
  • Sending push notifcaiton from Nodejs Here
  • Sending push notification using php Here & Here
  • Sending push notification from Wordpress. Here & Here
  • Sending push notification from Drupal. Here

Implementing own backend in various programming languages.:

Further Readings: - - Documentation from Firefox website can be read here. - A very good overview of Web Push by Google can be found here. - An FAQ answering most common confusions and questions.

Are there any free services to do the same? There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:

  1. https://onesignal.com/ (Free | Support all platforms)
  2. https://firebase.google.com/products/cloud-messaging/ (Free)
  3. https://clevertap.com/ (Has free plan)
  4. https://goroost.com/

Note: When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.

Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org

Spring @Value is not resolving to value from property file

I also found the reason @value was not working is, @value requires PropertySourcesPlaceholderConfigurer instead of a PropertyPlaceholderConfigurer. i did the same changes and it worked for me, i am using spring 4.0.3 release. I configured this using below code in my configuration file -

@Bean 
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}

Play/pause HTML 5 video using JQuery

You could use the basic HTML player or you can make your own custom one. Just saying. If you want you can refer to ... https://codepen.io/search/pens?q=video+player and have a scroll through or not. It is to to you.

Oracle SQL: Update a table with data from another table

This is called a correlated update

UPDATE table1 t1
   SET (name, desc) = (SELECT t2.name, t2.desc
                         FROM table2 t2
                        WHERE t1.id = t2.id)
 WHERE EXISTS (
    SELECT 1
      FROM table2 t2
     WHERE t1.id = t2.id )

Assuming the join results in a key-preserved view, you could also

UPDATE (SELECT t1.id, 
               t1.name name1,
               t1.desc desc1,
               t2.name name2,
               t2.desc desc2
          FROM table1 t1,
               table2 t2
         WHERE t1.id = t2.id)
   SET name1 = name2,
       desc1 = desc2

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

Is it possible to display inline images from html in an Android TextView?

You could also write your own parser to pull the URL of all the images and then dynamically create new imageviews and pass in the urls.

C++ -- expected primary-expression before ' '

You don't need "string" in your call to wordLengthFunction().

int wordLength = wordLengthFunction(string word);

should be

int wordLength = wordLengthFunction(word);

How to set width of a div in percent in JavaScript?

The question is what do you want the div's height/width to be a percent of?

By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.

So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:

obj.style.width = '50%';

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

Is there 'byte' data type in C++?

There's also byte_lite, compatible with C++98, C++11 and later.

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

You can do the folllwoing: import the jar file inside you class:

import javax.servlet.http.HttpServletResponse

add the Apache Tomcat library as follow:

Project > Properties > Java Build Path > Libraries > Add library from library tab > Choose server runtime > Next > choose Apache Tomcat v 6.0 > Finish > Ok

Also First of all, make sure that Servlet jar is included in your class path in eclipse as PermGenError said.

I think this will solve your error

ERROR Android emulator gets killed

If your username is not in English then this may help, as I tried all of the solutions here and couldn't fix this problem:

Note: I found this solution on this video, suggested by a user called "tatachka", this is her comment (she kindly let me share it here).

For example, I had this path c:\Users\????.android\avd\Nexus_One_API_24.avd My name in Windows is ????, written in Cyrillic in windows encoding (cp1251). I changed the path to e:\Distribu\AVD.android\avd\Nexus_One_API_24.avd I moved files from disk C there and edited Nexus_One_API_24.ini changing the path in it and everything worked.

How to change the folder path: My computer -> properties -> advanced system parameters -> environment variables - > lower 'New...' button: variable name: ANDROID_SDK_HOME variable value: e:\Distribu\AVD (in my case)

After the reboot, a new folder(.android) appears in the folder e:\Distribu\AVD containing the 'avd' folder

EDIT: For clarification, the idea here is that you don't want the path to have non-ascii characters. I moved it to C:\programs_that_cant_read_hebrew (and preformed the other steps) and it worked just fine.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

When to use reinterpret_cast?

Quick answer: use static_cast if it compiles, otherwise resort to reinterpret_cast.

How do I get the function name inside a function in PHP?

<?php

  class Test {
     function MethodA(){
         echo __FUNCTION__ ;
     }
 }
 $test = new Test;
 echo $test->MethodA();
?>

Result: "MethodA";

How to set a binding in Code?

Replace:

myBinding.Source = ViewModel.SomeString;

with:

myBinding.Source = ViewModel;

Example:

Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);

Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property).

How to convert Nonetype to int or string?

I was having the same problem using the python email functions. Below is the code I was trying to retrieve email subject into a variable. This works fine for most emails and the variable populates. If you receive an email from Yahoo or the like and the sender did no fill out the subject line Yahoo does not create a subject line in the email and you get a NoneType returned from the function. Martineau provided a correct answer as well as Soviut. IMO Soviut's answer is more concise from a programming stand point; not necessarily from a Python one. Here is some code to show the technique:

import sys, email, email.Utils 

afile = open(sys.argv[1], 'r')    
m = email.message_from_file(afile)    
subject = m["subject"]

# Soviut's Concise test for unset variable.

if subject is None:    
     subject = "[NO SUBJECT]"

# Alternative way to test for No Subject created in email (Thanks for NoneThing Yahoo!)

try:    
    if len(subject) == 0:    
        subject = "[NO SUBJECT]"

except TypeError:    
    subject = "[NO SUBJECT]"

print subject

afile.close()

Raise an error manually in T-SQL to jump to BEGIN CATCH block

THROW (Transact-SQL)

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2017.

Please refer the below link

T-SQL Throw Exception

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

Ubuntu, how do you remove all Python 3 but not 2

So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.

All I did was simply remove Jupyter and then alias python=python2.7 and install all packages on Python 2.7 again.

Arguably, I can install virtualenv but me and my colleagues are only using 2.7. I am just going to be lazy in this case :)

BATCH file asks for file or folder

The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.

Example:

xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"

How to add an image to the emulator gallery in android studio?

Try using Device File Explorer:

  1. Start the Device

  2. Navigate to View->Tool Windows->Device File Explorer to open the Device File Explorer

  3. Click on sdcard and select the folder in which you want to save the file to.

  4. Right-click on the folder and select upload to select the file from your computer.

  5. Select the file and click ok to upload

Invisible characters - ASCII

An invisible Character is ?, or U+200b

?

Javascript objects: get parent

You will need the child to store the parents this variable. As the Parent is the only object that has access to it's this variable it will also need a function that places the this variable into the child's that variable, something like this.

var Parent = {
  Child : {
    that : {},
  },
  init : function(){
    this.Child.that = this;
  }
}

To test this out try to run this in Firefox's Scratchpad, it worked for me.

var Parent = {
  data : "Parent Data",

  Child : {
    that : {},
    data : "Child Data",
    display : function(){
      console.log(this.data);
      console.log(this.that.data);
    }
  },
  init : function(){
    this.Child.that = this;
  }
}

Parent.init();
Parent.Child.display();

change background image in body

If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

<script>
  const meta = document.querySelector('[property="og:image"]');
  const body = document.querySelector("body");
  body.style.background = `url(${meta.content})`;
</script>

The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

If you want the image to cover the entire viewport and stay fixed set background-size like so:

body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';

Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

How can I do DNS lookups in Python, including referring to /etc/hosts?

I'm not really sure if you want to do DNS lookups yourself or if you just want a host's ip. In case you want the latter,

/!\ socket.gethostbyname is depricated, prefer socket.getaddrinfo

from man gethostbyname:

The gethostbyname*(), gethostbyaddr*(), [...] functions are obsolete. Applications should use getaddrinfo(3), getnameinfo(3),

import socket
print(socket.gethostbyname('localhost')) # result from hosts file
print(socket.gethostbyname('google.com')) # your os sends out a dns query

Transfer files to/from session I'm logged in with PuTTY

Look here:

http://web.archive.org/web/20170106202838/https://it.cornell.edu/services/managed_servers/howto/file_transfer/fileputty.cfm#puttytrans

It recommends using pscp.exe from PuTTY, which can be found here: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

A direct transfer like FTP is not possible, because all commands during your session are send to the server.

Can I bind an array to an IN() condition?

It's not possible to use an array like that in PDO.

You need to build a string with a parameter (or use ?) for each value, for instance:

:an_array_0, :an_array_1, :an_array_2, :an_array_3, :an_array_4, :an_array_5

Here's an example:

<?php
$ids = array(1,2,3,7,8,9);
$sqlAnArray = join(
    ', ',
    array_map(
        function($index) {
            return ":an_array_$index";
        },
        array_keys($ids)
    )
);
$db = new PDO(
    'mysql:dbname=mydb;host=localhost',
    'user',
    'passwd'
);
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN('.$sqlAnArray.')'
);
foreach ($ids as $index => $id) {
    $stmt->bindValue("an_array_$index", $id);
}

If you want to keep using bindParam, you may do this instead:

foreach ($ids as $index => $id) {
    $stmt->bindParam("an_array_$index", $ids[$id]);
}

If you want to use ? placeholders, you may do it like this:

<?php
$ids = array(1,2,3,7,8,9);
$sqlAnArray = '?' . str_repeat(', ?', count($ids)-1);
$db = new PDO(
    'mysql:dbname=dbname;host=localhost',
    'user',
    'passwd'
);
$stmt = $db->prepare(
    'SELECT *
     FROM phone_number_lookup
     WHERE country_code IN('.$sqlAnArray.')'
);
$stmt->execute($ids);

If you don't know if $ids is empty, you should test it and handle that case accordingly (return an empty array, or return a Null Object, or throw an exception, ...).

How to change the background color of the options menu?

Just ran into this issue too, on an App that had to be compatible with Gingerbread and still retain as much of the styling from Holo-enabled devices as possible.

I found a relatively clean solution, that worked OK for me.

In the theme I use a 9-patch drawable background to get a custom background color:

<style name="Theme.Styled" parent="Theme.Sherlock">
   ...
   <item name="android:panelFullBackground">@drawable/menu_hardkey_panel</item>
</style>

I gave up trying to style the text color, and just used a Spannable to set the text color for my item in code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getSupportMenuInflater();
   inflater.inflate(R.menu.actions_main, menu);

   if (android.os.Build.VERSION.SDK_INT < 
        android.os.Build.VERSION_CODES.HONEYCOMB) {

        SpannableStringBuilder text = new SpannableStringBuilder();
        text.append(getString(R.string.action_text));
        text.setSpan(new ForegroundColorSpan(Color.WHITE), 
                0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        MenuItem item1 = menu.findItem(R.id.action_item1);
        item1.setTitle(text);
   }

   return true;
}

Newline in markdown table?

Use an HTML line break (<br />) to force a line break within a table cell:

|Something|Something else<br />that's rather long|Something else|

Skip the headers when editing a csv file using Python

Inspired by Martijn Pieters' response.

In case you only need to delete the header from the csv file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers
   outfile.write(infile.read())

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

_DEBUG vs NDEBUG

Is NDEBUG standard?

Yes it is a standard macro with the semantic "Not Debug" for C89, C99, C++98, C++2003, C++2011, C++2014 standards. There are no _DEBUG macros in the standards.

C++2003 standard send the reader at "page 326" at "17.4.2.1 Headers" to standard C.

That NDEBUG is similar as This is the same as the Standard C library.

In C89 (C programmers called this standard as standard C) in "4.2 DIAGNOSTICS" section it was said

http://port70.net/~nsz/c/c89/c89-draft.html

If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as

     #define assert(ignore) ((void)0)

If look at the meaning of _DEBUG macros in Visual Studio https://msdn.microsoft.com/en-us/library/b0084kay.aspx then it will be seen, that this macro is automatically defined by your ?hoice of language runtime library version.

What difference is there between WebClient and HTTPWebRequest classes in .NET?

I know its too longtime to reply but just as an information purpose for future readers:

WebRequest

System.Object
    System.MarshalByRefObject
        System.Net.WebRequest

The WebRequest is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest and FileWebRequest.

You use Create method of WebRequest to create an instance of WebRequest. GetResponseStream returns data stream.

There are also FileWebRequest and FtpWebRequest classes that inherit from WebRequest. Normally, you would use WebRequest to, well, make a request and convert the return to either HttpWebRequest, FileWebRequest or FtpWebRequest, depend on your request. Below is an example:

Example:

var _request = (HttpWebRequest)WebRequest.Create("http://stackverflow.com");
var _response = (HttpWebResponse)_request.GetResponse();

WebClient

System.Object
        System.MarshalByRefObject
            System.ComponentModel.Component
                System.Net.WebClient

WebClient provides common operations to sending and receiving data from a resource identified by a URI. Simply, it’s a higher-level abstraction of HttpWebRequest. This ‘common operations’ is what differentiate WebClient from HttpWebRequest, as also shown in the sample below:

Example:

var _client = new WebClient();
var _stackContent = _client.DownloadString("http://stackverflow.com");

There are also DownloadData and DownloadFile operations under WebClient instance. These common operations also simplify code of what we would normally do with HttpWebRequest. Using HttpWebRequest, we have to get the response of our request, instantiate StreamReader to read the response and finally, convert the result to whatever type we expect. With WebClient, we just simply call DownloadData, DownloadFile or DownloadString.

However, keep in mind that WebClient.DownloadString doesn’t consider the encoding of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify and encoding.

NOTE: Basically "WebClient takes few lines of code as compared to Webrequest"

Running AngularJS initialization code when view is loaded

I use the following template in my projects:

angular.module("AppName.moduleName", [])

/**
 * @ngdoc controller
 * @name  AppName.moduleName:ControllerNameController
 * @description Describe what the controller is responsible for.
 **/
    .controller("ControllerNameController", function (dependencies) {

        /* type */ $scope.modelName = null;
        /* type */ $scope.modelName.modelProperty1 = null;
        /* type */ $scope.modelName.modelPropertyX = null;

        /* type */ var privateVariable1 = null;
        /* type */ var privateVariableX = null;

        (function init() {
            // load data, init scope, etc.
        })();

        $scope.modelName.publicFunction1 = function () /* -> type  */ {
            // ...
        };

        $scope.modelName.publicFunctionX = function () /* -> type  */ {
            // ...
        };

        function privateFunction1() /* -> type  */ {
            // ...
        }

        function privateFunctionX() /* -> type  */ {
            // ...
        }

    });

Creating a "Hello World" WebSocket example

Issue

Since you are using WebSocket, spender is correct. After recieving the initial data from the WebSocket, you need to send the handshake message from the C# server before any further information can flow.

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: websocket
Connection: Upgrade
WebSocket-Origin: example
WebSocket-Location: something.here
WebSocket-Protocol: 13

Something along those lines.

You can do some more research into how WebSocket works on w3 or google.

Links and Resources

Here is a protocol specifcation: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76#section-1.3

List of working examples:

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

On Windows use:

C:\PostgreSQL\pg10\bin>createuser -U postgres --pwprompt <USER>

Add --superuser or --createdb as appropriate.

See https://www.postgresql.org/docs/current/static/app-createuser.html for further options.

Split string in C every white space

Something going wrong is get_words() always returning one less than the actual word count, so eventually you attempt to:

char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */

newbuff[count2] = (char *)malloc(strlen(buffer))

count2, eventually, is always one more than the number of elements you've declared for newbuff[]. Why malloc() isn't returning a valid ptr, though, I don't know.

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

An example of how to use getopts in bash

The example packaged with getopt (my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a 
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

What is the use of the %n format specifier in C?

Those who want to use %n Format Specifier may want to look at this:

Do Not Use the "%n" Format String Specifier

Abstract

Careless use of "%n" format strings can introduce a vulnerability.

Description

There are many kinds of vulnerability that can be caused by misusing format strings. Most of these are covered elsewhere, but this document covers one specific kind of format string vulnerability that is entirely unique for format strings. Documents in the public are inconsistent in coverage of these vulnerabilities.

In C, use of the "%n" format specification in printf() and sprintf() type functions can change memory values. Inappropriate design/implementation of these formats can lead to a vulnerability generated by changes in memory content. Many format vulnerabilities, particularly those with specifiers other than "%n", lead to traditional failures such as segmentation fault. The "%n" specifier has generated more damaging vulnerabilities. The "%n" vulnerabilities may have secondary impacts, since they can also be a significant consumer of computing and networking resources because large guantities of data may have to be transferred to generate the desired pointer value for the exploit.

Avoid using the "%n" format specifier. Use other means to accomplish your purpose.

Source: link

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

    This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

    I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

    void find_squares(Mat& image, vector<vector<Point> >& squares)
    {
        // blur will enhance edge detection
        Mat blurred(image);
        medianBlur(image, blurred, 9);
    
        Mat gray0(blurred.size(), CV_8U), gray;
        vector<vector<Point> > contours;
    
        // find squares in every color plane of the image
        for (int c = 0; c < 3; c++)
        {
            int ch[] = {c, 0};
            mixChannels(&blurred, 1, &gray0, 1, ch, 1);
    
            // try several threshold levels
            const int threshold_level = 2;
            for (int l = 0; l < threshold_level; l++)
            {
                // Use Canny instead of zero threshold level!
                // Canny helps to catch squares with gradient shading
                if (l == 0)
                {
                    Canny(gray0, gray, 10, 20, 3); // 
    
                    // Dilate helps to remove potential holes between edge segments
                    dilate(gray, gray, Mat(), Point(-1,-1));
                }
                else
                {
                        gray = gray0 >= (l+1) * 255 / threshold_level;
                }
    
                // Find contours and store them in a list
                findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
    
                // Test contours
                vector<Point> approx;
                for (size_t i = 0; i < contours.size(); i++)
                {
                        // approximate contour with accuracy proportional
                        // to the contour perimeter
                        approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);
    
                        // Note: absolute value of an area is used because
                        // area may be positive or negative - in accordance with the
                        // contour orientation
                        if (approx.size() == 4 &&
                                fabs(contourArea(Mat(approx))) > 1000 &&
                                isContourConvex(Mat(approx)))
                        {
                                double maxCosine = 0;
    
                                for (int j = 2; j < 5; j++)
                                {
                                        double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                        maxCosine = MAX(maxCosine, cosine);
                                }
    
                                if (maxCosine < 0.3)
                                        squares.push_back(approx);
                        }
                }
            }
        }
    }
    

    After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

    opencv paper sheet detection

    I'm letting you write the function to find the largest square. ;)

    Convert java.util.Date to String

    tl;dr

    myUtilDate.toInstant()  // Convert `java.util.Date` to `Instant`.
              .atOffset( ZoneOffset.UTC )  // Transform `Instant` to `OffsetDateTime`.
              .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String.
              .replace( "T" , " " )  // Put a SPACE in the middle.
    

    2014-11-14 14:05:09

    java.time

    The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.

    First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

    Conversions to/from java.time are performed by new methods added to the old classes.

    Instant instant = myUtilDate.toInstant();
    

    Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.

    String output = instant.toString();  
    

    2014-11-14T14:05:09Z

    For other formats, you need to transform your Instant into the more flexible OffsetDateTime.

    OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
    

    odt.toString(): 2020-05-01T21:25:35.957Z

    See that code run live at IdeOne.com.

    To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.

    String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                       .replace( "T" , " " );
    

    2014-11-14 14:05:09

    By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.

    Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.

    To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.

    ZoneId z = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdt = instant.atZone( z );
    

    zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]

    To generate a formatted String, do the same as above but replace odt with zdt.

    String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                       .replace( "T" , " " );
    

    2014-11-14 14:05:09

    If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );  // Data-loss: Dropping any fractional second.
    

    Apply that formatter by passing the instance.

    String output = zdt.format( f );
    

    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to java.time.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

    get current date and time in groovy?

    Date has the time as well, just add HH:mm:ss to the date format:

    import java.text.SimpleDateFormat
    def date = new Date()
    def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
    println sdf.format(date)
    

    In case you are using JRE 8 you can use LoaclDateTime:

    import java.time.*
    
    LocalDateTime t = LocalDateTime.now();
    return t as String
    

    Get List of connected USB Devices

    To see the devices I was interested in, I had replace Win32_USBHub by Win32_PnPEntity in Adel Hazzah's code, based on this post. This works for me:

    namespace ConsoleApplication1
    {
      using System;
      using System.Collections.Generic;
      using System.Management; // need to add System.Management to your project references.
    
      class Program
      {
        static void Main(string[] args)
        {
          var usbDevices = GetUSBDevices();
    
          foreach (var usbDevice in usbDevices)
          {
            Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
                usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
          }
    
          Console.Read();
        }
    
        static List<USBDeviceInfo> GetUSBDevices()
        {
          List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
    
          ManagementObjectCollection collection;
          using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
            collection = searcher.Get();      
    
          foreach (var device in collection)
          {
            devices.Add(new USBDeviceInfo(
            (string)device.GetPropertyValue("DeviceID"),
            (string)device.GetPropertyValue("PNPDeviceID"),
            (string)device.GetPropertyValue("Description")
            ));
          }
    
          collection.Dispose();
          return devices;
        }
      }
    
      class USBDeviceInfo
      {
        public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
        {
          this.DeviceID = deviceID;
          this.PnpDeviceID = pnpDeviceID;
          this.Description = description;
        }
        public string DeviceID { get; private set; }
        public string PnpDeviceID { get; private set; }
        public string Description { get; private set; }
      }
    }
    

    Recursively look for files with a specific extension

    To find all the pom.xml files in your current directory and print them, you can use:

    find . -name 'pom.xml' -print
    

    What do \t and \b do?

    \t is the tab character, and is doing exactly what you're anticipating based on the action of \b - it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b.

    How do you reindex an array in PHP but with indexes starting from 1?

    You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.

    Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.

    When to use virtual destructors?

    Also be aware that deleting a base class pointer when there is no virtual destructor will result in undefined behavior. Something that I learned just recently:

    How should overriding delete in C++ behave?

    I've been using C++ for years and I still manage to hang myself.

    CSS media query to target iPad and iPad only?

    /*working only in ipad portrait device*/
    @media only screen and (width: 768px) and (height: 1024px) and (orientation:portrait) {
      body{
        background: red !important;
      }  
    }
    /*working only in ipad landscape device*/
    @media all and (width: 1024px) and (height: 768px) and (orientation:landscape){
      body{
        background: green !important;
      }   
    }
    
    In the media query of specific devices, please use '!important' keyword to override the default CSS. Otherwise that does not change your webpage view on that particular devices.
    

    How to remove elements from a generic list while iterating over it?

    Reverse iteration should be the first thing to come to mind when you want to remove elements from a Collection while iterating over it.

    Luckily, there is a more elegant solution than writing a for loop which involves needless typing and can be error prone.

    ICollection<int> test = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
    
    foreach (int myInt in test.Reverse<int>())
    {
        if (myInt % 2 == 0)
        {
            test.Remove(myInt);
        }
    }
    

    How to Convert UTC Date To Local time Zone in MySql Select Query

    In my case, where the timezones are not available on the server, this works great:

    SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`
    

    Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!

    How to access the correct `this` inside a callback?

    Another approach, which is the standard way since DOM2 to bind this within the event listener, that let you always remove the listener (among other benefits), is the handleEvent(evt)method from the EventListener interface:

    var obj = {
      handleEvent(e) {
        // always true
        console.log(this === obj);
      }
    };
    
    document.body.addEventListener('click', obj);
    

    Detailed information about using handleEvent can be found here: https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38

    How to install JQ on Mac by command-line?

    For most it is a breeze, however like you I had a difficult time installing jq

    The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/

    However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system

    What worked for me was removing all previous installs then pip install jq

    Hide header in stack navigator React navigation

    if you want remove the header from all screen goto app.js and add this code to Stack.Navigator

    screenOptions={ { headerShown: false } }
    

    Simple way to find if two different lists contain exactly the same elements?

    It depends on what concrete List class you are using. The abstract class AbstractCollection has a method called containsAll(Collection) that takes another collection ( a List is a collection) and:

    Returns true if this collection contains all of the elements in the specified collection.

    So if an ArrayList is being passed in you can call this method to see if they are exactly the same.

           List foo = new ArrayList();
        List bar = new ArrayList();
        String str = "foobar";
    
        foo.add(str);
        bar.add(str);
    
        foo.containsAll(bar);
    

    The reason for containsAll() is because it iterates through the first list looking for the match in the second list. So if they are out of order equals() will not pick it up.

    EDIT: I just want to make a comment here about the amortized running time of performing the various options being offered. Is running time important? Sure. Is it the only thing you should consider? No.

    The cost of copying EVERY single element from your lists into other lists takes time, and it also takes up a good chunk of memory (effectively doubling the memory you are using).

    So if memory in your JVM isn't a concern (which it should generally be) then you still need to consider the time it takes to copy every element from two lists into two TreeSets. Remember it is sorting every element as it enters them.

    My final advice? You need to consider your data set and how many elements you have in your data set, and also how large each object in your data set is before you can make a good decision here. Play around with them, create one each way and see which one runs faster. It's a good exercise.

    PHP - Get array value with a numeric index

    $array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
    $array = array_values($array);
    echo $array[0]; //bar
    echo $array[1]; //bin
    echo $array[2]; //ipsum
    

    Dump a mysql database to a plaintext (CSV) backup from the command line

    In MySQL itself, you can specify CSV output like:

    SELECT order_id,product_name,qty
    FROM orders
    INTO OUTFILE '/tmp/orders.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
    

    From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

    jquery - Click event not working for dynamically created button

    the simple and easy way to do that is use on event:

    $('body').on('click','#element',function(){
        //somthing
    });
    

    but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

    <div id='div1'></div>
    

    Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

    var dynamicDiv = jQuery('#div1').clone(true);
    

    Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

    How can I switch my signed in user in Visual Studio 2013?

    Derek's answer above didn't work for me. I am using VS 2013 Ultimate and after signing out of Visual Studio, when i tried to sign in as another user, it gave error.

    Then when connecting to the Team Project i saw the option to switch user, which is what i wanted all along.

    Link to the issue number on GitHub within a commit message

    One of my first projects as a programmer was a gem called stagecoach that (among other things) allowed the automatic adding of a github issue number to every commit message on a branch, which is a part of the question that hasn't really been answered.

    Essentially when creating a branch you'd use a custom command (something like stagecoach -b <branch_name> -g <issue_number>), and the issue number would then be assigned to that branch in a yml file. There was then a commit hook that appended the issue number to the commit message automatically.

    I wouldn't recommend it for production use as at the time I'd only been programming for a few months and I no longer maintain it, but it may be of interest to somebody.

    How to send Basic Auth with axios

    There is an "auth" parameter for Basic Auth:

    auth: {
      username: 'janedoe',
      password: 's00pers3cret'
    }
    

    Source/Docs: https://github.com/mzabriskie/axios

    Example:

    await axios.post(session_url, {}, {
      auth: {
        username: uname,
        password: pass
      }
    });
    

    How to change an input button image using CSS?

    If you're wanting to style the button using CSS, make it a type="submit" button instead of type="image". type="image" expects a SRC, which you can't set in CSS.

    Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.

    Number of times a particular character appears in a string

    BEST

    DECLARE @yourSpecialMark = '/';
    select len(@yourString) - len(replace(@yourString,@yourSpecialMark,''))
    

    It will count, how many times occours the special mark '/'

    Homebrew refusing to link OpenSSL

    I have a similar case. I need to install openssl via brew and then use pip to install mitmproxy. I get the same complaint from brew link --force. Following is the solution I reached: (without force link by brew)

    LDFLAGS=-L/usr/local/opt/openssl/lib 
    CPPFLAGS=-I/usr/local/opt/openssl/include
    PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig 
    pip install mitmproxy
    

    This does not address the question straightforwardly. I leave the one-liner in case anyone uses pip and requires the openssl lib.

    Note: the /usr/local/opt/openssl/lib paths are obtained by brew info openssl

    Create view with primary key?

    I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.

    CREATE VIEW [dbo].[vMyView]
    AS
    SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
    FROM  dbo.MyTable
    

    (XML) The markup in the document following the root element must be well-formed. Start location: 6:2

    After insuring that the string "strOutput" has a correct XML structure, you can do this:

    Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
    strOutput = junkMatcher.replaceFirst("<");
    

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

    You may also permanently (after reboots) add to the Path variable this way:

    Right click My Computer -> Click Properties -> Click Advanced system settings -> Click Environment Variables

    Reference: Change System/User Variables

    Java - Convert integer to string

    There are multiple ways:

    • String.valueOf(number) (my preference)
    • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
    • Integer.toString(number)

    Make selected block of text uppercase

    It is the same as in eclipse:

    • Select text for upper case and Ctrl + Shift + X
    • Select text for lower case and Ctrl + Shift + Y

    using BETWEEN in WHERE condition

    You should use

    $this->db->where('$accommodation >=', minvalue);
    $this->db->where('$accommodation <=', maxvalue);
    

    I'm not sure of syntax, so I beg your pardon if it's not correct.
    Anyway BETWEEN is implemented using >=min && <=max.
    This is the meaning of my example.

    EDITED:
    Looking at this link I think you could write:

    $this->db->where("$accommodation BETWEEN $minvalue AND $maxvalue");
    

    SELECT inside a COUNT

    You can move the count() inside your sub-select:

    SELECT a AS current_a, COUNT(*) AS b,
       ( SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d,
       from t group by a order by b desc
    

    How to enable MySQL Query Log?

    I also wanted to enable the MySQL log file to see the queries and I have resolved this with the below instructions

    1. Go to /etc/mysql/mysql.conf.d
    2. open the mysqld.cnf

    and enable the below lines

    general_log_file        = /var/log/mysql/mysql.log
    general_log             = 1
    
    1. restart the MySQL with this command /etc/init.d/mysql restart
    2. go to /var/log/mysql/ and check the logs

    Object comparison in JavaScript

    I have modified a bit the code above. for me 0 !== false and null !== undefined. If you do not need such strict check remove one "=" sign in "this[p] !== x[p]" inside the code.

    Object.prototype.equals = function(x){
        for (var p in this) {
            if(typeof(this[p]) !== typeof(x[p])) return false;
            if((this[p]===null) !== (x[p]===null)) return false;
            switch (typeof(this[p])) {
                case 'undefined':
                    if (typeof(x[p]) != 'undefined') return false;
                    break;
                case 'object':
                    if(this[p]!==null && x[p]!==null && (this[p].constructor.toString() !== x[p].constructor.toString() || !this[p].equals(x[p]))) return false;
                    break;
                case 'function':
                    if (p != 'equals' && this[p].toString() != x[p].toString()) return false;
                    break;
                default:
                    if (this[p] !== x[p]) return false;
            }
        }
        return true;
    }
    

    Then I have tested it with next objects:

    var a = {a: 'text', b:[0,1]};
    var b = {a: 'text', b:[0,1]};
    var c = {a: 'text', b: 0};
    var d = {a: 'text', b: false};
    var e = {a: 'text', b:[1,0]};
    var f = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var g = {a: 'text', b:[1,0], f: function(){ this.f = this.b; }};
    var h = {a: 'text', b:[1,0], f: function(){ this.a = this.b; }};
    var i = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var j = {
        a: 'text',
        c: {
            b: [1, 0],
            f: function(){
                this.a = this.b;
            }
        }
    };
    var k = {a: 'text', b: null};
    var l = {a: 'text', b: undefined};
    

    a==b expected true; returned true

    a==c expected false; returned false

    c==d expected false; returned false

    a==e expected false; returned false

    f==g expected true; returned true

    h==g expected false; returned false

    i==j expected true; returned true

    d==k expected false; returned false

    k==l expected false; returned false

    grep for multiple strings in file on different lines (ie. whole file, not line based search)?

    This is a blending of glenn jackman's and kurumi's answers which allows an arbitrary number of regexes instead of an arbitrary number of fixed words or a fixed set of regexes.

    #!/usr/bin/awk -f
    # by Dennis Williamson - 2011-01-25
    
    BEGIN {
        for (i=ARGC-2; i>=1; i--) {
            patterns[ARGV[i]] = 0;
            delete ARGV[i];
        }
    }
    
    {
        for (p in patterns)
            if ($0 ~ p)
                matches[p] = 1
                # print    # the matching line could be printed
    }
    
    END {
        for (p in patterns) {
            if (matches[p] != 1)
                exit 1
        }
    }
    

    Run it like this:

    ./multigrep.awk Dansk Norsk Svenska 'Language: .. - A.*c' dvdfile.dat
    

    Round double in two decimal places in C#?

    I think all these answers are missing the question. The problem was to "Round UP", not just "Round". It is my understanding that Round Up means that ANY fractional value about a whole digit rounds up to the next WHOLE digit. ie: 48.0000000 = 48 but 25.00001 = 26. Is this not the definition of rounding up? (or have my past 60 years in accounting been misplaced?

    Get protocol + host name from URL

    Python3 using urlsplit:

    from urllib.parse import urlsplit
    url = "http://stackoverflow.com/questions/9626535/get-domain-name-from-url"
    base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url))
    print(base_url)
    # http://stackoverflow.com/
    

    How to save a Seaborn plot into a file

    You should just be able to use the savefig method of sns_plot directly.

    sns_plot.savefig("output.png")
    

    For clarity with your code if you did want to access the matplotlib figure that sns_plot resides in then you can get it directly with

    fig = sns_plot.fig
    

    In this case there is no get_figure method as your code assumes.

    Error: Can't set headers after they are sent to the client

    Process.env does not change, so it must not be used for accessing per-request environment variables whose values may change on a per-request basis. So, if the user spawns an application process, but not as part of handling a request, then that application process will not have per-request environment variables stored inside OS-level environment variables. So, use this code to store process env and your program run successfully.

        const port = process.env.PORT || 2000;
        
        app.listen(port,()=>{
            console.log("Server running at port 2000");
        })
    

    @Html.DropDownListFor how to set default value

    I hope this is helpful to you.

    Please try this code,

     @Html.DropDownListFor(model => model.Items, new List<SelectListItem>
       { new SelectListItem{Text="Deactive", Value="False"},
         new SelectListItem{Text="Active", Value="True",  Selected = true},
         })
    

    Rails: Can't verify CSRF token authenticity when making a POST request

    If you only want to skip CSRF protection for one or more controller actions (instead of the entire controller), try this

    skip_before_action :verify_authenticity_token, only [:webhook, :index, :create]
    

    Where [:webhook, :index, :create] will skip the check for those 3 actions, but you can change to whichever you want to skip

    Reading content from URL with Node.js

    A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)

    function httpGet(url) {
      return new Promise((resolve, reject) => {
        const http = require('http'),
          https = require('https');
    
        let client = http;
    
        if (url.toString().indexOf("https") === 0) {
          client = https;
        }
    
        client.get(url, (resp) => {
          let chunks = [];
    
          // A chunk of data has been recieved.
          resp.on('data', (chunk) => {
            chunks.push(chunk);
          });
    
          // The whole response has been received. Print out the result.
          resp.on('end', () => {
            resolve(Buffer.concat(chunks));
          });
    
        }).on("error", (err) => {
          reject(err);
        });
      });
    }
    
    (async(url) => {
      var buf = await httpGet(url);
      console.log(buf.toString('utf-8'));
    })('https://httpbin.org/headers');
    

    Creating composite primary key in SQL Server

    If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

    enter image description here

    Command for this is,

    ALTER TABLE dbo.testRequest
    ADD CONSTRAINT PK_TestRequest 
    PRIMARY KEY (wardNo, BHTNo, TestID)
    

    MySQL timestamp select date range

    This SQL query will extract the data for you. It is easy and fast.

    SELECT *
      FROM table_name
      WHERE extract( YEAR_MONTH from timestamp)="201010";
    

    Reading string from input with space character?

    #include <stdio.h>
    // read a line into str, return length
    int read_line(char str[]) {
    int c, i=0;
    c = getchar();
    while (c != '\n' && c != EOF) { 
       str[i] = c;
       c = getchar();
       i++;
    }
    str[i] = '\0';
    return i;
    }
    

    How do I check if a Key is pressed on C++

    check if a key is pressed, if yes, then do stuff

    Consider 'select()', if this (reportedly Posix) function is available on your os.

    'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)


    from man page:

    'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"

    When select is invoked:

    a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.

    The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).

    b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.

    fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.


    Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...

    Then I get an fd to use in 'select()' by using open:

    // flag options are: O_RDONLY, O_WRONLY, or O_RDWR
    int inFD = open( "/dev/pts/5", O_RDONLY ); 
    

    It is useful to cout this value.

    Here is a snippet to consider (from man select):

      fd_set rfds;
      struct timeval tv;
      int retval;
    
      /* Watch stdin (fd 0) to see when it has input. */
      FD_ZERO(&rfds);
      FD_SET(0, &rfds);
    
      /* Wait up to five seconds. */
      tv.tv_sec = 5;
      tv.tv_usec = 0;
    
      retval = select(1, &rfds, NULL, NULL, &tv);
      /* Don't rely on the value of tv now! */
    
      if (retval == -1)
          perror("select()");
      else if (retval)
          printf("Data is available now.\n");  // i.e. doStuff()
          /* FD_ISSET(0, &rfds) will be true. */
      else
          printf("No data within five seconds.\n"); // i.e. key not pressed
    

    Setting log level of message at runtime in slf4j

    It is not possible to specify a log level in sjf4j 1.x out of the box. But there is hope for slf4j 2.0 to fix the issue. In 2.0 it might look like this:

    // POTENTIAL 2.0 SOLUTION
    import org.slf4j.helpers.Util;
    import static org.slf4j.spi.LocationAwareLogger.*;
    
    // does not work with slf4j 1.x
    Util.log(logger, DEBUG_INT, "hello world!");
    

    In the meanwhile, for slf4j 1.x, you can use this workaround:

    Copy this class into your classpath:

    import org.slf4j.Logger;
    import java.util.function.Function;
    
    public enum LogLevel {
    
        TRACE(l -> l::trace, Logger::isTraceEnabled),
        DEBUG(l -> l::debug, Logger::isDebugEnabled),
        INFO(l -> l::info, Logger::isInfoEnabled),
        WARN(l -> l::warn, Logger::isWarnEnabled),
        ERROR(l -> l::error, Logger::isErrorEnabled);
    
        interface LogMethod {
            void log(String format, Object... arguments);
        }
    
        private final Function<Logger, LogMethod> logMethod;
        private final Function<Logger, Boolean> isEnabledMethod;
    
        LogLevel(Function<Logger, LogMethod> logMethod, Function<Logger, Boolean> isEnabledMethod) {
            this.logMethod = logMethod;
            this.isEnabledMethod = isEnabledMethod;
        }
    
        public LogMethod prepare(Logger logger) {
            return logMethod.apply(logger);
        }
    
        public boolean isEnabled(Logger logger) {
            return isEnabledMethod.apply(logger);
        }
    }
    

    Then you can use it like this:

    Logger logger = LoggerFactory.getLogger(Application.class);
    
    LogLevel level = LogLevel.ERROR;
    level.prepare(logger).log("It works!"); // just message, without parameter
    level.prepare(logger).log("Hello {}!", "world"); // with slf4j's parameter replacing
    
    try {
        throw new RuntimeException("Oops");
    } catch (Throwable t) {
        level.prepare(logger).log("Exception", t);
    }
    
    if (level.isEnabled(logger)) {
        level.prepare(logger).log("logging is enabled");
    }
    

    This will output a log like this:

    [main] ERROR Application - It works!
    [main] ERROR Application - Hello world!
    [main] ERROR Application - Exception
    java.lang.RuntimeException: Oops
        at Application.main(Application.java:14)
    [main] ERROR Application - logging is enabled
    

    Is it worth it?

    • Pro It keeps the source code location (class names, method names, line numbers will point to your code)
    • Pro You can easily define variables, parameters and return types as LogLevel
    • Pro Your business code stays short and easy to read, and no additional dependencies required.

    The source code as minimal example is hosted on GitHub.

    How to launch html using Chrome at "--allow-file-access-from-files" mode?

    Depending on the file which will be put into filesystem, as long as that file is not a malware, then that would be safe.

    But don't worry to write/read file(s) to File System directory, cause you can tighten that directory security (include it's inheritance) by give a proper access right and security restriction. eg: read/write/modify.

    By default, File System, Local Storage, and Storage directory are located on "\Users[Current User]\AppData\Local\Google\Chrome\User Data\Default" directory.

    However you can customize it by using "--user-data-dir" flag.

    And this is a sample:

    "C:\Program Files (x86)\Google\Application\chrome.exe" --user-data-dir="C:\Chrome_Data\OO7" --allow-file-access-from-files
    

    Hope this helps anyone.

    How to move the cursor word by word in the OS X Terminal

    As answered previously, you can add set -o vi in your ~/.bashrc to use vi/vim key bindings, or else you can add following part in .bashrc to move with Ctrl and arrow keys:

    # bindings to move 1 word left/right with ctrl+left/right in terminal, just some apple stuff!
    bind '"\e[5C": forward-word'
    bind '"\e[5D": backward-word'
    # bindings to move 1 word left/right with ctrl+left/right in iTerm2, just some apple stuff!
    bind '"\e[1;5C": forward-word'
    bind '"\e[1;5D": backward-word'
    

    To start effect of these lines of code, either source ~/.bashrc or start a new terminal session.

    Getting all names in an enum as a String[]

    I would write it like this

    public static String[] names() {
    
        java.util.LinkedList<String> list = new LinkedList<String>();
        for (State s : State.values()) {
            list.add(s.name());
        }
    
        return list.toArray(new String[list.size()]);
    }
    

    how to run a winform from console application?

    You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

    C++ calling base class constructors

    Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.

    Build and Install unsigned apk on device without the development server?

    There are two extensions you can use for this. This is added to react-native for setting these:

    1. disableDevInDebug: true: Disables dev server in debug buildType
    2. bundleInDebug: true: Adds jsbundle to debug buildType.

    So, your final project.ext.react in android/app/build.gradle should look like below

    project.ext.react = [
        enableHermes: false,  // clean and rebuild if changing
        devDisabledInDev: true, // Disable dev server in dev release
        bundleInDev: true, // add bundle to dev apk
    ]
    

    jQuery removeClass wildcard

    A regex splitting on word boundary \b isn't the best solution for this:

    var prefix = "prefix";
    var classes = el.className.split(" ").filter(function(c) {
        return c.lastIndexOf(prefix, 0) !== 0;
    });
    el.className = classes.join(" ");
    

    or as a jQuery mixin:

    $.fn.removeClassPrefix = function(prefix) {
        this.each(function(i, el) {
            var classes = el.className.split(" ").filter(function(c) {
                return c.lastIndexOf(prefix, 0) !== 0;
            });
            el.className = classes.join(" ");
        });
        return this;
    };
    

    How to parse unix timestamp to time.Time

    The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix:

    package main
    
    import (
        "fmt"
        "time"
        "strconv"
    )
    
    func main() {
        i, err := strconv.ParseInt("1405544146", 10, 64)
        if err != nil {
            panic(err)
        }
        tm := time.Unix(i, 0)
        fmt.Println(tm)
    }
    

    Output:

    2014-07-16 20:55:46 +0000 UTC
    

    Playground: http://play.golang.org/p/v_j6UIro7a

    Edit:

    Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

    How to stop a function

    I'm just going to do this

    def function():
      while True:
        #code here
    
        break
    

    Use "break" to stop the function.

    How to clear variables in ipython?

    Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

    del variable1,variable2
    

    How do I mount a remote Linux folder in Windows through SSH?

    The best an easiest solution I found is https://github.com/billziss-gh/sshfs-win, connected servers shows up as a fully functioning network drives. This is not a 'Dokany' or 'dokan' based solution which from experiance seems more stable and performant, also see WinFsp Performance Testing.

    mount ssh on windows

    Please note previously this answer stated, https://github.com/Foreveryone-cz/win-sshfs and before that http://www.swish-sftp.org/ but I no longer use any of them, first one stopped working second one created drives not fully supported in all programs.

    Reading string by char till end of line C/C++

    A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

    if (c == '\n')

    What is the purpose of using WHERE 1=1 in SQL statements?

    As you said:

    if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.

    How to change TextField's height and width?

    You can try the margin property in the Container. Wrap the TextField inside a Container and adjust the margin property.

    new Container(
      margin: const EdgeInsets.only(right: 10, left: 10),
      child: new TextField( 
        decoration: new InputDecoration(
          hintText: 'username',
          icon: new Icon(Icons.person)),
      )
    ),
    

    Append lines to a file using a StreamWriter

    Replace this:

    StreamWriter file2 = new StreamWriter("c:/file.txt");
    

    with this:

    StreamWriter file2 = new StreamWriter("c:/file.txt", true);
    

    true indicates that it appends text.

    Minimum Hardware requirements for Android development

    Have a look at the android SDK system requirements Here

    I'm guessing some extra RAM would help your developing experience...Also the emulator does take some time to start on even the speediest systems.

    Execute Stored Procedure from a Function

    Here is another possible workaround:

    if exists (select * from master..sysservers where srvname = 'loopback')
        exec sp_dropserver 'loopback'
    go
    exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
    go
    
    create function testit()
        returns int
    as
    begin
        declare @res int;
        select @res=count(*) from openquery(loopback, 'exec sp_who');
        return @res
    end
    go
    
    select dbo.testit()
    

    It's not so scary as xp_cmdshell but also has too many implications for practical use.

    Convert all data frame character columns to factors

    As @Raf Z commented on this question, dplyr now has mutate_if. Super useful, simple and readable.

    > str(df)
    'data.frame':   5 obs. of  5 variables:
     $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
     $ B: int  1 2 3 4 5
     $ C: logi  TRUE TRUE FALSE FALSE TRUE
     $ D: chr  "a" "b" "c" "d" ...
     $ E: chr  "A a" "B b" "C c" "D d" ...
    
    > df <- df %>% mutate_if(is.character,as.factor)
    
    > str(df)
    'data.frame':   5 obs. of  5 variables:
     $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
     $ B: int  1 2 3 4 5
     $ C: logi  TRUE TRUE FALSE FALSE TRUE
     $ D: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
     $ E: Factor w/ 5 levels "A a","B b","C c",..: 1 2 3 4 5
    

    Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

    Call the Below Action Method from your JS file (To get the ipv4 ip address).

        [HttpGet]
        public string GetIP()
        {
            IPAddress[] ipv4Addresses = Array.FindAll(
                Dns.GetHostEntry(string.Empty).AddressList,
                a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
            return ipv4Addresses.ToString();
        }
    

    Check after keeping Breakpoint, and use as per your requirement. Its working fine for me.

    How to set session attribute in java?

    By default session object is available on jsp page(implicit object). It will not available in normal POJO java class. You can get the reference of HttpSession object on Servelt by using HttpServletRequest

    HttpSession s=request.getSession()
    s.setAttribute("name","value");
    

    You can get session on an ActionSupport based Action POJO class as follows

     ActionContext ctx= ActionContext.getContext();
       Map m=ctx.getSession();
       m.put("name", value);
    

    look at: http://ohmjavaclasses.blogspot.com/2011/12/access-session-in-action-class-struts2.html

    How to add scroll bar to the Relative Layout?

    I used the

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <RelativeLayout
    

    and works perfectly

    How to simulate a mouse click using JavaScript?

    An easier and more standard way to simulate a mouse click would be directly using the event constructor to create an event and dispatch it.

    Though the MouseEvent.initMouseEvent() method is kept for backward compatibility, creating of a MouseEvent object should be done using the MouseEvent() constructor.

    var evt = new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true,
        clientX: 20,
        /* whatever properties you want to give it */
    });
    targetElement.dispatchEvent(evt);
    

    Demo: http://jsfiddle.net/DerekL/932wyok6/

    This works on all modern browsers. For old browsers including IE, MouseEvent.initMouseEvent will have to be used unfortunately though it's deprecated.

    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", canBubble, cancelable, view,
                       detail, screenX, screenY, clientX, clientY,
                       ctrlKey, altKey, shiftKey, metaKey,
                       button, relatedTarget);
    targetElement.dispatchEvent(evt);
    

    Python update a key in dict if it doesn't exist

    According to the above answers setdefault() method worked for me.

    old_attr_name = mydict.setdefault(key, attr_name)
    if attr_name != old_attr_name:
        raise RuntimeError(f"Key '{key}' duplication: "
                           f"'{old_attr_name}' and '{attr_name}'.")
    

    Though this solution is not generic. Just suited me in this certain case. The exact solution would be checking for the key first (as was already advised), but with setdefault() we avoid one extra lookup on the dictionary, that is, though small, but still a performance gain.

    MVC razor form with multiple different submit buttons?

    Simplest way is to use the html5 FormAction and FormMethod

    <input type="submit" 
               formaction="Save"
               formmethod="post" 
               value="Save" />
        <input type="submit"
               formaction="SaveForLatter"
               formmethod="post" 
               value="Save For Latter" />
        <input type="submit"
               formaction="SaveAndPublish"
               formmethod="post"
               value="Save And Publish" />
    
    [HttpPost]
    public ActionResult Save(CustomerViewModel model) {...}
    
    [HttpPost]
    public ActionResult SaveForLatter(CustomerViewModel model){...}
    
    [HttpPost]
    public ActionResult SaveAndPublish(CustomerViewModel model){...}
    

    There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways

    Detect URLs in text with JavaScript

    First you need a good regex that matches urls. This is hard to do. See here, here and here:

    ...almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.

    Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.

    For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename.

    Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent.

    Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

    Anyway, this answer is not meant to give you the best regex but rather a proof of how to do the string wrapping inside the text, with JavaScript.

    OK so lets just use this one: /(https?:\/\/[^\s]+)/g

    Again, this is a bad regex. It will have many false positives. However it's good enough for this example.

    _x000D_
    _x000D_
    function urlify(text) {_x000D_
      var urlRegex = /(https?:\/\/[^\s]+)/g;_x000D_
      return text.replace(urlRegex, function(url) {_x000D_
        return '<a href="' + url + '">' + url + '</a>';_x000D_
      })_x000D_
      // or alternatively_x000D_
      // return text.replace(urlRegex, '<a href="$1">$1</a>')_x000D_
    }_x000D_
    _x000D_
    var text = 'Find me at http://www.example.com and also at http://stackoverflow.com';_x000D_
    var html = urlify(text);_x000D_
    _x000D_
    console.log(html)
    _x000D_
    _x000D_
    _x000D_

    // html now looks like:
    // "Find me at <a href="http://www.example.com">http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>"
    

    So in sum try:

    $$('#pad dl dd').each(function(element) {
        element.innerHTML = urlify(element.innerHTML);
    });
    

    How to get item count from DynamoDB?

    With the aws dynamodb cli you can get it via scan as follows:

    aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"
    

    The response will look similar to this:

    {
        "Count": 123,
        "ScannedCount": 123,
        "ConsumedCapacity": null
    }
    

    notice that this information is in real time in contrast to the describe-table api

    What's "P=NP?", and why is it such a famous question?

    There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.

    Is there a good JSP editor for Eclipse?

    MyEclipse has a pretty decent one, it costs money however. One of the reasons I went over to Netbeans is because of their JSP editor, which is still far from perfect but better then vanilla Eclipse.

    Git push error pre-receive hook declined

    You might not have developer access to the project or master branch. You need dev access to push new work up.

    New work meaning new branches and commits.

    Javascript get object key name

    ECMAscript edition 5 also offers you the neat methods Object.keys() and Object.getOwnPropertyNames().

    So

    Object.keys( buttons );  // ['button1', 'button2'];
    

    How to identify numpy types in python?

    That actually depends on what you're looking for.

    • If you want to test whether a sequence is actually a ndarray, a isinstance(..., np.ndarray) is probably the easiest. Make sure you don't reload numpy in the background as the module may be different, but otherwise, you should be OK. MaskedArrays, matrix, recarray are all subclasses of ndarray, so you should be set.
    • If you want to test whether a scalar is a numpy scalar, things get a bit more complicated. You could check whether it has a shape and a dtype attribute. You can compare its dtype to the basic dtypes, whose list you can find in np.core.numerictypes.genericTypeRank. Note that the elements of this list are strings, so you'd have to do a tested.dtype is np.dtype(an_element_of_the_list)...

    Embedding a media player in a website using HTML

    I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.

    <audio controls>
      <source src="horse.mp3" type="audio/mpeg">
      <embed height="50" width="100" src="horse.mp3">
    </audio>
    

    Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.

    How to set timeout for a line of c# code

    You can use the IAsyncResult and Action class/interface to achieve this.

    public void TimeoutExample()
    {
        IAsyncResult result;
        Action action = () =>
        {
            // Your code here
        };
    
        result = action.BeginInvoke(null, null);
    
        if (result.AsyncWaitHandle.WaitOne(10000))
             Console.WriteLine("Method successful.");
        else
             Console.WriteLine("Method timed out.");
    }
    

    invalid operands of types int and double to binary 'operator%'

    Because % is only defined for integer types. That's the modulus operator.

    5.6.2 of the standard:

    The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

    As Oli pointed out, you can use fmod(). Don't forget to include math.h.

    How can I deploy an iPhone application from Xcode to a real iPhone device?

    You can't, not if you are talking about applications built with the official SDK and deploying straight from xcode.

    How to Use -confirm in PowerShell

    -Confirm is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host cmdlet:

    $confirmation = Read-Host "Are you Sure You Want To Proceed:"
    if ($confirmation -eq 'y') {
        # proceed
    }
    

    or the PromptForChoice() method of the host user interface:

    $title    = 'something'
    $question = 'Are you sure you want to proceed?'
    
    $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
    $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
    $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
    
    $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
    if ($decision -eq 0) {
        Write-Host 'confirmed'
    } else {
        Write-Host 'cancelled'
    }
    

    Edit:

    As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.

    $title    = 'something'
    $question = 'Are you sure you want to proceed?'
    $choices  = '&Yes', '&No'
    
    $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
    if ($decision -eq 0) {
        Write-Host 'confirmed'
    } else {
        Write-Host 'cancelled'
    }
    

    unexpected T_VARIABLE, expecting T_FUNCTION

    You cannot use function calls in a class construction, you should initialize that value in the constructor function.

    From the PHP Manual on class properties:

    This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

    A working code sample:

    <?php
        class UserDatabaseConnection
        {
            public $connection;
            public function __construct()
            {
                $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
            }
            public function lookupUser($username)
            {
                // rest of my code...
                // example usage (procedural way):
                $query = sqlite_exec($this->connection, "SELECT ...", $error);
                // object oriented way:
                $query = $this->connection->queryExec("SELECT ...", $error);
            }
        }
    
        $udb = new UserDatabaseConnection;
    ?>
    

    Depending on your needs, protected or private might be a better choice for $connection. That protects you from accidentally closing or messing with the connection.

    Export table data from one SQL Server to another

    Try this:

    1. create your table on the target server using your scripts from the Script Table As / Create Script step

    2. on the target server, you can then issue a T-SQL statement:

      INSERT INTO dbo.YourTableNameHere
         SELECT *
         FROM [SourceServer].[SourceDatabase].dbo.YourTableNameHere
      

    This should work just fine.

    How to replace sql field value

    To avoid update names that contain .com like [email protected] to [email protected], you can do this:

    UPDATE Yourtable
    SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')
    

    html table span entire width?

    you need to set the margin of the body to 0 for the table to stretch the full width. alternatively you can set the margin of the table to a negative number as well.

    Updating Python on Mac

    Echoing above on not messing with OS X install. Have been faced with a couple of reinstalls thinking I could beat the system. The 3.1 install Scott Griffiths offers above works fine with Yosemite, for any Beta testers out there.. Yosemite has Python 2.7.6 as part of OS install, and typing "python3.1" from terminal launches Python 3.1. Same for Python 3.4 (install here).

    Find the index of a char in string?

    Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim myString As String = "abcdef"
        Dim numberString As String = String.Empty
    
        If myString.Contains("d") Then
            numberString = myString.IndexOf("d")
        End If
    End Sub
    

    Another sample with TextBox

      Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim myString As String = "abcdef"
        Dim numberString As String = String.Empty
    
        If myString.Contains(me.TextBox1.Text) Then
            numberString = myString.IndexOf(Me.TextBox1.Text)
        End If
    End Sub
    

    Regards

    What is SaaS, PaaS and IaaS? With examples

    I know this question has been answered a while ago but this could help.

    What do the following terms mean?

    SaaS

    Software as a Service - Essentially, any application that runs with its contents from the cloud is referred to as Software as a Service, As long as you do not own it.

    Some examples are Gmail, Netflix, OneDrive etc.

    AUDIENCE: End users, everybody

    IaaS

    Infrastructure as a Service means that the provider allows a portion of their computing power to its customers, It is purchased by the potency of the computing power and they are bundled in Virtual Machines. A company like Google Cloud platform, AWS, Alibaba Cloud can be referred to as IaaS providers because they sell processing powers (servers, storage, networking) to their users in terms of Virtual Machines.

    AUDIENCE: IT professionals, System Admins

    PaaS

    Platform as a Service is more like the middle-man between IaaS and SaaS, Instead of a customer having to deal with the nitty-gritty of servers, networks and storage, everything is readily available by the PaaS providers. Essentially a development environment is initialized to make building applications easier.

    Examples would be Heroku, AWS Elastic Beanstalk, Google App Engine etc

    AUDIENCE: Software developers.

    There are various cloud services available today, such as Amazon's EC2 and AWS, Apache Hadoop, Microsoft Azure and many others. Which category does each belong to and why?

    Amazon EC2 and AWS - is an Infrastructure as a Service because you'll need System Administrators to manage the working process of your operating system. There is no abstraction to build a fully featured app ordinarily. Microsoft Azure would also fall under this category following the aforementioned guidelines.

    I really haven't used Apache Hadoop, so I really cannot say.

    Shell equality operators (=, ==, -eq)

    Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

    But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

    Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

    $ rht="A*"
    $ lft="AB"
    $ [ $lft = $rht ] && echo yes
    $ [ $lft == $rht ] && echo yes
    $ [[ $lft = $rht ]] && echo yes
    yes
    $ [[ $lft == $rht ]] && echo yes
    yes
    $ [[ $lft == "$rht" ]] && echo yes
    $
    

    Executing multiple SQL queries in one statement with PHP

    This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.

    Security considerations

    The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

    PHP Doc

    Broadcast Receiver within a Service

    as your service is already setup, simply add a broadcast receiver in your service:

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
            //action for sms received
          }
          else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
               //action for phone state changed
          }     
       }
    };
    

    in your service's onCreate do this:

    IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    filter.addAction("your_action_strings"); //further more
    filter.addAction("your_action_strings"); //further more
    
    registerReceiver(receiver, filter);
    

    and in your service's onDestroy:

    unregisterReceiver(receiver);
    

    and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

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

    How to make CSS3 rounded corners hide overflow in Chrome/Opera

    I found another solution for this problem. This looks like another bug in WebKit (or probably Chrome), but it works. All you need to do - is to add a WebKit CSS Mask to the #wrapper element. You can use a single pixel png image and even include it to the CSS to save a HTTP request.

    #wrapper {
    width: 300px; height: 300px;
    border-radius: 100px;
    overflow: hidden;
    position: absolute; /* this breaks the overflow:hidden in Chrome/Opera */
    
    /* this fixes the overflow:hidden in Chrome */
    -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
    }
    
    #box {
    width: 300px; height: 300px;
    background-color: #cde;
    }?
    

    JSFiddle Example

    How to use mouseover and mouseout in Angular 6

    To avoid blinking problem use following code
    its not mouseover and mouseout instead of that use mouseenter and mouseleave
    
    
    **app.component.html**
    
        <div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
          <span *ngIf="!changeText">Hide</span>
          <span *ngIf="changeText">Show</span>
        </div>
    
    **app.component.ts**
    
    @Component({
       selector: 'app-main',
       templateUrl: './app.component.html'
    })
    export class AppComponent {
        changeText: boolean;
        constructor() {
           this.changeText = false;
        }
    }
    

    How can I list the contents of a directory in Python?

    In Python 3.4+, you can use the new pathlib package:

    from pathlib import Path
    for path in Path('.').iterdir():
        print(path)
    

    Path.iterdir() returns an iterator, which can be easily turned into a list:

    contents = list(Path('.').iterdir())
    

    Add a list item through javascript

    If you want to create a li element for each input/name, then you have to create it, with document.createElement [MDN].

    Give the list the ID:

    <ol id="demo"></ol>
    

    and get a reference to it:

    var list = document.getElementById('demo');
    

    In your event handler, create a new list element with the input value as content and append to the list with Node.appendChild [MDN]:

    var firstname = document.getElementById('firstname').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstname));
    list.appendChild(entry);
    

    DEMO

    angular.js ng-repeat li items with html content

    If you want some element to contain a value that is HTML, take a look at ngBindHtmlUnsafe.

    If you want to style options in a native select, no it is not possible.

    What to do with branch after merge

    If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.

    What does -> mean in C++?

    x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().

    datetime to string with series in python pandas

    As of version 17.0, you can format with the dt accessor:

    dates.dt.strftime('%Y-%m-%d')
    

    Reference

    How to use mongoimport to import csv

    you will most likely need to authenticate if you're working in production sort of environments. You can use something like this to authenticate against the correct database with appropriate credentials.

    mongoimport -d db_name -c collection_name --type csv --file filename.csv --headerline --host hostname:portnumber --authenticationDatabase admin --username 'iamauser' --password 'pwd123'
    

    SVN upgrade working copy

    If you're getting this error from Netbeans (7.2+) then it means that your separately installed version of Subversion is higher than the version in netbeans. In my case Netbeans (v7.3.1) had SVN v1.7 and I'd just upgraded my SVN to v1.8.

    If you look in Tools > Options > Miscellaneous (tab) > Versioning (tab) > Subversion (pane), set the Preferred Client = CLI, then you can set the path the the installed SVN which for me was C:\Program Files\TortoiseSVN\bin.

    More can be found on the Netbeans Subversion Clients FAQ.

    Early exit from function?

    Apparently you can do this:

    function myFunction() {myFunction:{
        console.log('i get executed');
        break myFunction;
        console.log('i do not get executed');
    }}
    

    See block scopes through the use of a label: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

    I can't see any downsides yet. But it doesn't seem like a common use.

    Derived this answer: JavaScript equivalent of PHP’s die

    Bootstrap 3: Keep selected tab on page refresh

    I tried this and it works: ( Please replace this with the pill or tab you are using )

        jQuery(document).ready(function() {
            jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
                localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
            });
    
            // Here, save the index to which the tab corresponds. You can see it 
            // in the chrome dev tool.
            var activeTab = localStorage.getItem('activeTab');
    
            // In the console you will be shown the tab where you made the last 
            // click and the save to "activeTab". I leave the console for you to 
            // see. And when you refresh the browser, the last one where you 
            // clicked will be active.
            console.log(activeTab);
    
            if (activeTab) {
               jQuery('a[href="' + activeTab + '"]').tab('show');
            }
        });
    

    I hope it would help somebody.

    Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/

    How do I create an HTML table with a fixed/frozen left column and a scrollable body?

    Alternatively, style the tbody with a predetermined size (via height:20em, for example) and use overflow-y:scroll;

    Then, you can have a huge tbody, which will scroll independently of the rest of the page.

    Connect to SQL Server Database from PowerShell

    I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.

    What is the difference between signed and unsigned int

    Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

    smtpclient " failure sending mail"

    Five years later (I hope this developer isn't still waiting for a fix to this..)

    I had the same issue, caused by the same error: I was declaring the SmtpClient inside the loop.

    The fix is simple - declare it once, outside the loop...

    MailAddress mail = null;
    SmtpClient client = new SmtpClient();
    client.Port = 25;
    client.EnableSsl = false;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = true;
    client.Host = smtpAddress;       //  Enter your company's email server here!
    
    for(int i = 0; i < number ; i++)
    {
        mail = new MailMessage(iMail.from, iMail.to);
        mail.Subject = iMail.sub;
        mail.Body = iMail.body;
        mail.IsBodyHtml = true;
        mail.Priority = MailPriority.Normal;
        mail.Sender = from;
        client.Send(mail);
    }
    mail.Dispose();
    client.Dispose();
    

    How to add a ScrollBar to a Stackpanel

    If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.

    So try something like this:

       <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel Width="311">
                  <TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
                  <TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
            </StackPanel>
        </Grid>
    

    You could even make this work with a ScrollViewer

    How can I iterate JSONObject to get individual items

    You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

    public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
        Iterator<String> keys = json.keys();
        while(keys.hasNext()){
            String key = keys.next();
            String val = null;
            try{
                 JSONObject value = json.getJSONObject(key);
                 parse(value,out);
            }catch(Exception e){
                val = json.getString(key);
            }
    
            if(val != null){
                out.put(key,val);
            }
        }
        return out;
    }
    
     public static void main(String[] args) throws JSONException {
    
        String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
    
        JSONObject object = new JSONObject(json);
    
        JSONObject info = object.getJSONObject("ipinfo");
    
        Map<String,String> out = new HashMap<String, String>();
    
        parse(info,out);
    
        String latitude = out.get("latitude");
        String longitude = out.get("longitude");
        String city = out.get("city");
        String state = out.get("state");
        String country = out.get("country");
        String postal = out.get("postal_code");
    
        System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
    
        System.out.println("ALL VALUE " + out);
    
    }
    

    Output:

        Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
    ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}
    

    java collections - keyset() vs entrySet() in map

    Every call to the Iterator.next() moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?

    for (String key : map.keySet()) {
        System.out.println(key + ":" + map.get(key));
    }
    

    Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry implementations usually implement the toString() method, so you don't have to print the key-value pair manually.

    for (Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry);
    }
    

    PHP: cannot declare class because the name is already in use

    Class Parent cannot be declared because it is PHP reserved keyword so in effect it's already in use

    SQLAlchemy: how to filter date field?

    from app import SQLAlchemyDB as db
    
    Chance.query.filter(Chance.repo_id==repo_id, 
                        Chance.status=="1", 
                        db.func.date(Chance.apply_time)<=end, 
                        db.func.date(Chance.apply_time)>=start).count()
    

    it is equal to:

    select
       count(id)
    from
       Chance
    where
       repo_id=:repo_id 
       and status='1'
       and date(apple_time) <= end
       and date(apple_time) >= start
    

    wish can help you.

    How to view the assembly behind the code using Visual C++?

    For MSVC you can use the linker.

    link.exe /dump /linenumbers /disasm /out:foo.dis foo.dll

    foo.pdb needs to be available to get symbols

    How to handle notification when app in background in Firebase

    Remove notification payload completely from your server request. Send only data and handle it in onMessageReceived(), otherwise your onMessageReceived will not be triggered when the app is in background or killed.

    Here is what I am sending from server:

    {
      "data":{
        "id": 1,
        "missedRequests": 5
        "addAnyDataHere": 123
      },
      "to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......"
    }
    

    So you can receive your data in onMessageReceived(RemoteMessage message) like this: (let's say I have to get the id)

    Object obj = message.getData().get("id");
            if (obj != null) {
                int id = Integer.valueOf(obj.toString());
            }
    

    And similarly you can get any data which you have sent from server within onMessageReceived().

    Removing page title and date when printing web page (with CSS?)

    Its simple. Just use css.

    <style>
    @page { size: auto;  margin: 0mm; }
    </style>
    

    How do you get the contextPath from JavaScript, the right way?

    Got it :D

    function getContextPath() {
       return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
    }
    alert(getContextPath());
    

    Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.

    Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

    This is the limitation in MYSQL 5.5 version. You need to update the version to 5.6.

    Error
    

    I was getting this error in adding a table in MYSQL

    Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause My new MYSQL

    table looks something like this.

    create table table_name (col1 int(5) auto_increment primary key, col2 varchar(300), col3 varchar(500), col4 int(3), col5 tinyint(2), col6 timestamp default current_timestamp, col7 timestamp default current_timestamp on update current_timestamp, col8 tinyint(1) default 0, col9 tinyint(1) default 1);

    After some time of reading about changes in different MYSQL versions and some of the googling. I found out that there was some changes that were made in MYSQL version 5.6 over version 5.5.

    This article will help you to resolve the issue. http://www.oyewiki.com/MYSQL/Incorrect-table-definition-there-can-be-only-one-timestamp-column

    How do I find the MySQL my.cnf location

    For Ubuntu 16: /etc/mysql/mysql.conf.d/mysqld.cnf

    How to unstage large number of files without deleting the content

    If you want to unstage all the changes use below command,

    git reset --soft HEAD
    

    In the case you want to unstage changes and revert them from the working directory,

    git reset --hard HEAD
    

    Android intent for playing video?

    from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException error from the uriString. I think some of that code from VideoActivity:

    Intent myIntent = getIntent();
    String uri = myIntent.getStringExtra("uri");
    Bundle b = myIntent.getExtras();
    
    startVideo(b.getString(uri));
    

    Cannot receive the uri from here:

    public void playsquirrelmp4(View v) {
        Intent VideoIntent = (new Intent(this, VideoActivity.class));
        VideoIntent.putExtra("android.resource://" + getPackageName()
            + "/"+   R.raw.squirrel, uri);
        startActivity(VideoIntent);
    }
    

    Sort objects in ArrayList by date?

    With introduction of Java 1.8, streams are very useful in solving this kind of problems:

    Comparator <DateTime> myComparator = (arg1, arg2) 
                    -> {
                        if(arg1.lt(arg2)) 
                           return -1;
                        else if (arg1.lteq(arg2))
                           return 0;
                        else
                           return 1;
                       };
    
    ArrayList<DateTime> sortedList = myList
                       .stream()
                       .sorted(myComparator)
                       .collect(Collectors.toCollection(ArrayList::new));
    

    Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

    As described by Gideon, this is a known issue with Chrome that has been open for more than 5 years with no apparent interest in fixing it.

    Unfortunately, in my case, the window.onunload = function() { debugger; } workaround didn't work either. So far the best workaround I've found is to use Firefox, which does display response data even after a navigation. The Firefox devtools also have a lot of nice features missing in Chrome, such as syntax highlighting the response data if it is html and automatically parsing it if it is JSON.