Programs & Examples On #Nolock

A SQL Server table hint that can be used to prevent queries from issuing shared read locks. While often used to prevent a query from blocking other queries it also makes it susceptible to dirty reads and other potential data issues.

SQL Server NOLOCK and joins

I won't address the READ UNCOMMITTED argument, just your original question.

Yes, you need WITH(NOLOCK) on each table of the join. No, your queries are not the same.

Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK) hint on it.

What is "with (nolock)" in SQL Server?

I've used to retrieve a "next batch" for things to do. It doesn't matter in this case which exact item, and I have a lot of users running this same query.

Is the NOLOCK (Sql Server hint) bad practice?

If you don't care about dirty reads (i.e. in a predominately READ situation), then NOLOCK is fine.

BUT, be aware that the majority of locking problems are due to not having the 'correct' indexes for your query workload (assuming the hardware is up to the task).

And the guru's explanation was correct. It is usually a band-aid solution to a more serious problem.

Edit: I'm definitely not suggesting that NOLOCK should be used. I guess I should have made that obviously clear. (I would only ever use it, in extreme circumstances where I had analysed that it was OK). AS an example, a while back I worked on some TSQL that had been sprinkled with NOLOCK to try and alleviate locking problems. I removed them all, implemented the correct indexes, and ALL of the deadlocks went away.

Simple way to create matrix of random numbers

Take a look at numpy.random.rand:

Docstring: rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1).

>>> import numpy as np
>>> np.random.rand(2,3)
array([[ 0.22568268,  0.0053246 ,  0.41282024],
       [ 0.68824936,  0.68086462,  0.6854153 ]])

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

In my case these sort of issues were solved using defer

<script src="<your file>.js" defer></script>

You need to take into account browsers's support of this option though (I haven't seen problems)

How to try convert a string to a Guid

Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.

Those are:

  • ArgumentNullException
  • FormatException
  • OverflowException

I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.

Returning JSON from PHP to JavaScript?

Php has an inbuilt JSON Serialising function.



Please use that if you can and don't suffer Not Invented Here syndrome.

How to use WHERE IN with Doctrine 2

Found how to do it in the year of 2016:


Here is how to do it properly:

$em->createQuery(“SELECT users 
     FROM Entities\User users 
     WHERE  IN (:userids)”)
     array(‘userids’ => $userIds)

The method setParameters will take the given array and implode it properly to be used in the “IN” statement.

How to find out when an Oracle table was updated the last time

Could you run a checksum of some sort on the result and store that locally? Then when your application queries the database, you can compare its checksum and determine if you should import it?

It looks like you may be able to use the ORA_HASH function to accomplish this.

Update: Another good resource: 10g’s ORA_HASH function to determine if two Oracle tables’ data are equal

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

Search and destroy (or move cautiously) any my.ini files (windows or program files), which is affecting the mysql service failure. also check port 3306 is used by using either netstat or portqry tool. this should help. Also if there is a file system issue you can run check disk.

Phone number formatting an EditText in Android

Follow the instructions in this Answer to format the EditText mask.

And after that, you can catch the original numbers from the masked string with:

String phoneNumbers = maskedString.replaceAll("[^\\d]", "");

Difference between h:button and h:commandButton

h:button - clicking on a h:button issues a bookmarkable GET request.

h:commandbutton - Instead of a get request, h:commandbutton issues a POST request which sends the form data back to the server.

Iframe positioning

It's because you're missing position:relative; on #contentframe

<div id="contentframe" style="position:relative; top: 160px; left: 0px;">

position:absolute; positions itself against the closest ancestor that has a position that is not static. Since the default is static that is what was causing your issue.

How do you UDP multicast in Python?

Just another answer to explain some subtle points in the code of the other answers:

  • socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
  • Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works

Multicast receiver:

import socket
import struct
import argparse

def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))

python3 --iface='' --join-mcast-groups '' '' '' --bind-group ''

python3 --iface='' --join-mcast-groups ''

Multicast sender:

import socket
import argparse

def run(group, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from ' +
                f'group: {group}, port: {port}'.encode(), (group, port))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage: # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet

python3 --mcast-group ''

python3 --mcast-group ''

Windows 7 - Add Path

I think you are editing something in the windows registry but that has no effect on the path.

Try this:

How to Add, Remove or Edit Environment variables in Windows 7

the variable of interest is the PATH

also you can type on the command line:

Set PATH=%PATH%;(your new path);

How to get a time zone from a location using latitude and longitude coordinates?

It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):

import pytz
from datetime import datetime
from tzwhere import tzwhere

def timezoned_unixtime(latitude, longitude, dt):
    tzw = tzwhere.tzwhere()
    timezone_str = tzw.tzNameAt(latitude, longitude)
    timezone = pytz.timezone(timezone_str)
    timezone_aware_datetime = timezone.localize(dt, is_dst=None)
    unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
    return unix_time

dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)

Passing ArrayList from servlet to JSP

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

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


        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while ( {
                Actor actor = new Actor();
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs = null;
                if (stmt != null) {
                    stmt = null;
                if (con != null) {
                    con = null;
            } catch (SQLException e) {



bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Install LXML parser in python environment.

pip install lxml

Your problem will be resolve. You can also use built-in python package for the same as:

soup = BeautifulSoup(s,  "html.parser")

Note: The "HTMLParser" module has been renamed to "html.parser" in Python3

Unable to connect with remote debugger

Inculding all impressive answers the expert developers specially Ribamar Santos provided, if you didn't get it working, you must check something more tricky!

Something like Airplane mode of your (emulated) phone! Or your network status of Emulator (Data status and Voice status on Cellular tab of Emulator configuration) that might be manipulated to don't express network! for some emulation needs!

I've overcome to this problem by this trick! It was a bit breathtaking debug to find this hole!

How to do a GitHub pull request

For those of us who have a account, but only get a nasty error message when we type "git" into the command-line, here's how to do it all in your browser :)

  1. Same as Tim and Farhan wrote: Fork your own copy of the project: Step 1: Fork
  2. After a few seconds, you'll be redirected to your own forked copy of the project: Step 2
  3. Navigate to the file(s) you need to change and click "Edit this file" in the toolbar: Step 3: Edit a file
  4. After editing, write a few words describing the changes and then "Commit changes", just as well to the master branch (since this is only your own copy and not the "main" project). Step 4: Commit changes
  5. Repeat steps 3 and 4 for all files you need to edit, and then go back to the root of your copy of the project. There, click the green "Compare, review..." button: Step 5: Start submit
  6. Finally, click "Create pull request" ..and then "Create pull request" again after you've double-checked your request's heading and description: enter image description here

Trigger insert old values- values that was updated

In your trigger, you have two pseudo-tables available, Inserted and Deleted, which contain those values.

In the case of an UPDATE, the Deleted table will contain the old values, while the Inserted table contains the new values.

So if you want to log the ID, OldValue, NewValue in your trigger, you'd need to write something like:

CREATE TRIGGER trgEmployeeUpdate
ON dbo.Employees AFTER UPDATE
   INSERT INTO dbo.LogTable(ID, OldValue, NewValue)
      SELECT i.ID, d.Name, i.Name
      FROM Inserted i
      INNER JOIN Deleted d ON i.ID = d.ID

Basically, you join the Inserted and Deleted pseudo-tables, grab the ID (which is the same, I presume, in both cases), the old value from the Deleted table, the new value from the Inserted table, and you store everything in the LogTable

Play audio from a stream using C#

Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..

How to download a file from my server using SSH (using PuTTY on Windows)

If your server have a http service you can compress your directory and download the compressed file.


tar -zcvf archive-name.tar.gz -C directory-name .

Download throught your browser:


If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.

How to revert multiple git commits?

I'm so frustrated that this question can't just be answered. Every other question is in relation to how to revert correctly and preserve history. This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."

git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f

I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without Pull-Request) pushed like 5 bad commits trying to fix and fix and fix a mistake he made 5 commits ago. Not only that, but one or two Pull Requests were accepted, which were now bad. So forget it, I found the last good commit (abc1234) and just ran the basic script:

git checkout testing
git reset --hard abc1234
git push -f

I told the other 5 guys working in this repo that they better make note of their changes for the last few hours and Wipe/Re-Branch from the latest testing. End of the story.

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

You may want to use the BIT data type, probably setting is as NOT NULL:

Quoting the MSDN article:

bit (Transact-SQL)

An integer data type that can take a value of 1, 0, or NULL.

The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on.

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

How to copy data from another workbook (excel)?

Best practice is to open the source file (with a false visible status if you don't want to be bother) read your data and then we close it.

A working and clean code is avalaible on the link below :

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"


Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

Git command to show which specific files are ignored by .gitignore

(extending the other answers)

Note, git check-ignore uses the committed .gitignore and not the one in your working tree! To play with it without polluting your git history, you might freely try to edit it, and then commit with a git commit --amend.

This problem happens mainly if you need a workaround of the problem, that git doesn't follow directories. Enter in the .gitignore:


.keep should be a zero-length file in dirtokeep.

The result will be that everything in dirtokeep will be ignored, except dirtokeep/.keep, which will result that also the dirtokeep directory will be constructed on clone/checkout.

How to set the locale inside a Debian/Ubuntu Docker container?

I actually happened to have suffered from the same problem, but none of the provided answers are 100% working with debian:latest, even if they provide good hints.

The biggest difference is that you should make sure both locales and locales-all are installed, the latter already containing en_US.UTF-8, so you don't have to generate it with local-gen or dpkg-reconfigure.

Here's what I've done in my Dockerfile to make it work:

FROM debian:latest
RUN apt-get update
RUN apt-get install -y locales locales-all

Drawing a simple line graph in Java

There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV) file with the XChart library. Disclaimer: I'm the lead developer of the project.

In this example, two text files exist in ./CSV/CSVChartRows/. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1 contains x, y, and error bar data, whereas series2 contains just x and y, data.





Source Code

public class CSVChartRows {

  public static void main(String[] args) throws Exception {

    // import chart from a folder containing CSV files
    XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);

    // Show it
    new SwingWrapper(chart).displayChart();

Resulting Plot

enter image description here

How to count days between two dates in PHP?

If you want to know the number of days (if any), the number of hours (if any), minutues (if any) and seconds, you can do the following:

$previousTimeStamp = strtotime("2011/07/01 21:12:34");
$lastTimeStamp = strtotime("2013/09/17 12:34:11");


$showing= $menos . " seconds ago";
$showing= $minsfinal . " minutes and " . $secondsfinal. " seconds ago";

$showing= $hoursfinal . "hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";

$showing= $daysfinal. "days, " .$hourssuperfinal . " hours, " . $minssuperfinal . " minutes and " . $secondsfinal. " seconds ago";

echo $showing;

You could use the same logic if you want to add months and years.

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
    <location path="YourFileNameHere.xml">
                <clientCache cacheControlMode="DisableCache" />

ModuleNotFoundError: No module named 'sklearn'

I did the following:

import sys
!{sys.executable} -m pip install sklearn

C compiler for Windows?

Be careful to use a C compiler, not C++ if you're actually doing C. While most programs in C will work using a C++ compiler there are enough differences that there can be problems. I would agree with the people who suggest using gcc via cygwin.

EDIT: shows some of the major differences

How to apply slide animation between two activities in Android?

Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.

Slide animations can be slid right, slide left, slide up and slide down.

Slide up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=""
        android:toYScale="0.0" />

Slide down

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android=""
        android:toYScale="1.0" />

overridePendingTransition(R.anim.slide_down, R.anim.slide_up);

See activity transition animation examples for more activity transition examples.

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:


There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

What are the different types of keys in RDBMS?

Sharing my notes which I usually maintain while reading from Internet, I hope it may be helpful to someone

Candidate Key or available keys

Candidate keys are those keys which is candidate for primary key of a table. In simple words we can understand that such type of keys which full fill all the requirements of primary key which is not null and have unique records is a candidate for primary key. So thus type of key is known as candidate key. Every table must have at least one candidate key but at the same time can have several.

Primary Key

Such type of candidate key which is chosen as a primary key for table is known as primary key. Primary keys are used to identify tables. There is only one primary key per table. In SQL Server when we create primary key to any table then a clustered index is automatically created to that column.

Foreign Key

Foreign key are those keys which is used to define relationship between two tables. When we want to implement relationship between two tables then we use concept of foreign key. It is also known as referential integrity. We can create more than one foreign key per table. Foreign key is generally a primary key from one table that appears as a field in another where the first table has a relationship to the second. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B.

Alternate Key or Secondary

If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table. Like here we can take a very simple example to understand the concept of alternate key. Suppose we have a table named Employee which has two columns EmpID and EmpMail, both have not null attributes and unique value. So both columns are treated as candidate key. Now we make EmpID as a primary key to that table then EmpMail is known as alternate key.

Composite Key

When we create keys on more than one column then that key is known as composite key. Like here we can take an example to understand this feature. I have a table Student which has two columns Sid and SrefNo and we make primary key on these two column. Then this key is known as composite key.

Natural keys

A natural key is one or more existing data attributes that are unique to the business concept. For the Customer table there was two candidate keys, in this case CustomerNumber and SocialSecurityNumber. Link

Surrogate key

Introduce a new column, called a surrogate key, which is a key that has no business meaning. An example of which is the AddressID column of the Address table in Figure 1. Addresses don't have an "easy" natural key because you would need to use all of the columns of the Address table to form a key for itself (you might be able to get away with just the combination of Street and ZipCode depending on your problem domain), therefore introducing a surrogate key is a much better option in this case. Link

Unique key

A unique key is a superkey--that is, in the relational model of database organization, a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set

Aggregate or Compound keys

When more than one column is combined to form a unique key, their combined value is used to access each row and maintain uniqueness. These keys are referred to as aggregate or compound keys. Values are not combined, they are compared using their data types.

Simple key

Simple key made from only one attribute.

Super key

A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a super key can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.

Partial Key or Discriminator key

It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.

convert json ipython notebook(.ipynb) to .py file

Copy all the (''.ipynb) files in the Desired folder then execute:

import os    

desired_path = 'C:\\Users\\Docs\\Ipynb Covertor'


list_of_directory = os.listdir(desired_path)

for file in list_of_directory:
        os.system('ipython nbconvert --to script ' + str(file))

How can I check if a MySQL table exists with PHP?

$connection = mysqli_connect("localhost","root","","php_sample_login_register"); 

if ($connection){
        echo "DB is Connected <br>";
        $sql = "CREATE TABLE user(
            name VARCHAR(255)NOT NULL,
            email VARCHAR(255)NOT NULL,
            password VARCHAR(255) NOT NULL
        if(mysqli_query($connection,$sql)) {
            echo "Created user table";
        } else{
            echo "User table already exists";
    } else {
        echo "error : DB isnot connected";
    } ?>

How to add a primary key to a MySQL table?

Existing Column

If you want to add a primary key constraint to an existing column all of the previously listed syntax will fail.

To add a primary key constraint to an existing column use the form:


How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')

How can you integrate a custom file browser/uploader with CKEditor?

Start by registering your custom browser/uploader when you instantiate CKEditor.

<script type="text/javascript">
CKEDITOR.replace('content', {
    filebrowserUploadUrl: "Upload File Url",//http://localhost/phpwork/test/ckFileUpload.php
    filebrowserWindowWidth  : 800,
    filebrowserWindowHeight : 500

Code for upload file(ckFileUpload.php) & put the upload file on root dir of your project.


$upload_dir = array(
 'img'=> '/phpwork/test/uploads/editor-images/',
 'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'

$imgset = array(
 'maxsize' => 2000,     // maximum file size, in KiloBytes (2 MB)
 'maxwidth' => 900,     // maximum allowed width, in pixels
 'maxheight' => 800,    // maximum allowed height, in pixels
 'minwidth' => 10,      // minimum allowed width, in pixels
 'minheight' => 10,     // minimum allowed height, in pixels
 'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'),  // allowed extensions

$audioset = array(
 'maxsize' => 20000,    // maximum file size, in KiloBytes (20 MB)
 'type' => array('mp3', 'ogg', 'wav'),  // allowed extensions

// If 1 and filename exists, RENAME file, adding "_NR" to the end of filename (name_1.ext, name_2.ext, ..)
// If 0, will OVERWRITE the existing file
define('RENAME_F', 1);

$re = '';
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
  define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name'])));  //get filename without extension

  // get protocol and host name to send the absolute image path to CKEditor
  $protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
  $site = $protocol. $_SERVER['SERVER_NAME'] .'/';
  $sepext = explode('.', strtolower($_FILES['upload']['name']));
  $type = end($sepext);    // gets extension
  $upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
  $upload_dir = trim($upload_dir, '/') .'/';

  //checkings for image or audio
  if(in_array($type, $imgset['type'])){
    list($width, $height) = getimagesize($_FILES['upload']['tmp_name']);  // image width and height
    if(isset($width) && isset($height)) {
      if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
      if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
      if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
  else if(in_array($type, $audioset['type'])){
    if($_FILES['upload']['size'] > $audioset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $audioset['maxsize']. ' KB.';
  else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';

  //set filename; if file exists, and RENAME_F is 1, set "img_name_I"
  // $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
  function setFName($p, $fn, $ex, $i){
    if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
    else return $fn .$ex;

  $f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
  $uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name;  // full file path

  // If no errors, upload the image, else, output the errors
  if($re == '') {
    if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
      $CKEditorFuncNum = $_GET['CKEditorFuncNum'];
      $url = $site. $upload_dir . $f_name;
      $msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
      $re = in_array($type, $imgset['type']) ? "$CKEditorFuncNum, '$url', '$msg')"  //for img
       : 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent();  dialog.hide();';
    else $re = 'alert("Unable to upload the file")';
  else $re = 'alert("'. $re .'")';

@header('Content-type: text/html; charset=utf-8');
echo '<script>'. $re .';</script>';

Ck-editor documentation is not clear after doing alot of R&D for custom file upload finally i have found this solution. It work for me and i hope it will helpful to others as well.

HAX kernel module is not installed

If you are running a modern Intel processor make sure HAXM (Intel® Hardware Accelerated Execution Manager) is installed:

  1. In Android SDK Manager, ensure the option is ticked (and then installed)

  2. Run the HAXM installer via the path below:


This video shows all the required steps which may help you to solve the problem.

For AMD CPUs (or older Intel CPUs without VT-x technology), you will not be able to install this and the best option is to emulate your apps using Genymotion. See: Intel's HAXM equivalent for AMD on Windows OS

How can I install a .ipa file to my iPhone simulator

First of all, IPAs usually only have ARM slices because the App Store does not currently accept Simulator slices in uploads.

Secondly, as of Xcode 8.3 you can drag & drop a .app bundle into the Simulator window and it will be installed. You can find the app in your build products directory ~/Library/Developer/Xcode/DerivedData/projectname-xyzzyabcdefg/Build/Products/Debug-iphonesimulator if you want to save it or distribute it to other people.

To install from the command line use xcrun simctl install <device> <path>.

device can be the device UUID, its name, or booted which means the currently booted device.

Best JavaScript compressor

YUI Compressor is the way to go. It has a great compression rate, is well tested and is in use among many top sites, and, well, personally recommended by me.

I've used it for my projects without a single JavaScript error or hiccup. And it has nice documentation.

I've never used its CSS compression capabilities, but they exist as well. CSS compression works just as well.

Note: Although Dean Edwards's /packer/ achieves a better compression rate than YUI Compressor, I ran into a few JavaScript errors when using it.

use a javascript array to fill up a drop down select box

Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.

var cuisines = ["Chinese","Indian"];     
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisines[i];
    opt.value = cuisines[i];


UPDATE: Using createDocumentFragment and forEach

If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.

var cuisines = ["Chinese","Indian"];     

var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();

cuisines.forEach(function(cuisine, index) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisine;
    opt.value = cuisine;



Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I ran into this exact issue upon a new install of Apache 2.4. After a few hours of googling and testing I finally found out that I also had to allow access to the directory that contains the (non-existent) target of the Alias directive. That is, this worked for me:

# File: /etc/apache2/conf-available/php5-fpm.conf
<IfModule mod_fastcgi.c>
    AddHandler php5-fcgi .php
    Action php5-fcgi /php5-fcgi
    Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
    FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization

    # NOTE: using '/usr/lib/cgi-bin/php5-cgi' here does not work,
    #   it doesn't exist in the filesystem!
    <Directory /usr/lib/cgi-bin>
        Require all granted

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet, it has nothing to do with the distance between the two routers. The propagation delay is the time taken by a bit to to propagate form one router to the next

Android 8: Cleartext HTTP traffic not permitted

Ok, that is ?? NOT ?? the thousands repeat of add it to your Manifest, but an hint which base on this, but give you additional Benefit (and maybe some Background Info).

Android has a kind of overwriting functionality for the src-Directory.

By default, you have


But you can add additional directories to overwrite your AndroidManifest.xml. Here is how it works:

  • Create the Directory /app/src/debug
  • Inside create the AndroidManifest.xml

Inside of this File, you don't have to put all the Rules inside, but only the ones you like to overwrite from your /app/src/main/AndroidManifest.xml

Here an Example how it looks like for the requested CLEARTEXT-Permission:

<manifest xmlns:android=""



With this knowledge it's now easy as 1,2,3 for you to overload your Permissions depending on your debug | main | release Enviroment.

The big benefit on it... you don't have debug-stuff in your production-Manifest and you keep an straight and easy maintainable structure

How would I access variables from one class to another?

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1

class ClassB(ClassA):
    def __init__(self, class_a):
        self.var1 = class_a.var1
        self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
    var1 = 0
    var2 = 0
    def __init__(self):
        ClassA.var1 = 1
        ClassA.var2 = 2

    def methodA(self):
        ClassA.var1 = ClassA.var1 + ClassA.var2
        return ClassA.var1

class ClassB(ClassA):
    def __init__(self):
        print ClassA.var1
        print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

Note, however, that class variables are shared among all instances of its class.

How to declare a local variable in Razor?

I think you were pretty close, try this:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>

XPath Query: get attribute href from a tag

For the following HTML document:

    <a href="">Example</a> 
    <a href="">SO</a> 

The xpath query /html/body//a/@href (or simply //a/@href) will return:

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.

Chrome violation : [Violation] Handler took 83ms of runtime

Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout like below:

[Violation] 'setTimeout' handler took 43129ms

That number (43129ms) depends on how long you stop in your async function

How to make a gap between two DIV within the same column

I know this was an old answer, but i would like to share my simple solution.

give style="margin-top:5px"

<div style="margin-top:5px">
  div 1
<div style="margin-top:5px">
  div2 elements
div3 elements

Text Editor For Linux (Besides Vi)?

for multiple tab text editor "medit" is the best . its like notepad++ in windows . for stylish and good looking "schite Text editor " is best .

C# switch on type

Update: This got fixed in C# 7.0 with pattern matching

switch (MyObj)
    case Type1 t1: 
    case Type2 t2:
    case Type3 t3:

Old answer:

It is a hole in C#'s game, no silver bullet yet.

You should google on the 'visitor pattern' but it might be a little heavy for you but still something you should know about.

Here's another take on the matter using Linq:

Otherwise something along these lines could help

// nasty..
  case "Type1": etc

// clumsy...
if myObj  is Type1 then
if myObj is Type2 then


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

For Windows, first install the git base from here:

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

How do I put double quotes in a string in vba?

All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard", In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.

How do you subtract Dates in Java?

It's indeed one of the biggest epic failures in the standard Java API. Have a bit of patience, then you'll get your solution in flavor of the new Date and Time API specified by JSR 310 / ThreeTen which is (most likely) going to be included in the upcoming Java 8.

Until then, you can get away with JodaTime.

DateTime dt1 = new DateTime(2000, 1, 1, 0, 0, 0, 0);
DateTime dt2 = new DateTime(2010, 1, 1, 0, 0, 0, 0);
int days = Days.daysBetween(dt1, dt2).getDays();

Its creator, Stephen Colebourne, is by the way the guy behind JSR 310, so it'll look much similar.

Netbeans installation doesn't find JDK

Set JAVA_HOME in environment variable.

set JAVA_HOME to only JDK1.6.0_23 or whatever jdk folder you have. dont include bin folder in path.

How to Add a Dotted Underline Beneath HTML Text

HTML5 element can give dotted underline so the beneath text will have dotted line rather than regular underline. And the title attribute creates a tool tip for the user when they hover their cursor over the element:

NOTE: The dotted border/underline is shown by default in Firefox and Opera, but IE8, Safari, and Chrome need a line of CSS:

<abbr title="Hyper Text Markup Language">HTML</abbr>

Set cursor position on contentEditable <div>

This is compatible with the standards-based browsers, but will probably fail in IE. I'm providing it as a starting point. IE doesn't support DOM Range.

var editable = document.getElementById('editable'),
    selection, range;

// Populates selection and range variables
var captureSelection = function(e) {
    // Don't capture selection outside editable region
    var isOrContainsAnchor = false,
        isOrContainsFocus = false,
        sel = window.getSelection(),
        parentAnchor = sel.anchorNode,
        parentFocus = sel.focusNode;

    while(parentAnchor && parentAnchor != document.documentElement) {
        if(parentAnchor == editable) {
            isOrContainsAnchor = true;
        parentAnchor = parentAnchor.parentNode;

    while(parentFocus && parentFocus != document.documentElement) {
        if(parentFocus == editable) {
            isOrContainsFocus = true;
        parentFocus = parentFocus.parentNode;

    if(!isOrContainsAnchor || !isOrContainsFocus) {

    selection = window.getSelection();

    // Get range (standards)
    if(selection.getRangeAt !== undefined) {
        range = selection.getRangeAt(0);

    // Get range (Safari 2)
    } else if(
        document.createRange &&
        selection.anchorNode &&
        selection.anchorOffset &&
        selection.focusNode &&
    ) {
        range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
    } else {
        // Failure here, not handled by the rest of the script.
        // Probably IE or some older browser

// Recalculate selection while typing
editable.onkeyup = captureSelection;

// Recalculate selection after clicking/drag-selecting
editable.onmousedown = function(e) {
    editable.className = editable.className + ' selecting';
document.onmouseup = function(e) {
    if(editable.className.match(/\sselecting(\s|$)/)) {
        editable.className = editable.className.replace(/ selecting(\s|$)/, '');

editable.onblur = function(e) {
    var cursorStart = document.createElement('span'),
        collapsed = !!range.collapsed; = 'cursorStart';

    // Insert beginning cursor marker

    // Insert end cursor marker if any text is selected
    if(!collapsed) {
        var cursorEnd = document.createElement('span'); = 'cursorEnd';

// Add callbacks to afterFocus to be called after cursor is replaced
// if you like, this would be useful for styling buttons and so on
var afterFocus = [];
editable.onfocus = function(e) {
    // Slight delay will avoid the initial selection
    // (at start or of contents depending on browser) being mistaken
    setTimeout(function() {
        var cursorStart = document.getElementById('cursorStart'),
            cursorEnd = document.getElementById('cursorEnd');

        // Don't do anything if user is creating a new selection
        if(editable.className.match(/\sselecting(\s|$)/)) {
            if(cursorStart) {
            if(cursorEnd) {
        } else if(cursorStart) {
            var range = document.createRange();

            if(cursorEnd) {

                // Delete cursor markers

                // Select range
            } else {

                // Select range

                // Delete cursor marker
                document.execCommand('delete', false, null);

        // Call callbacks here
        for(var i = 0; i < afterFocus.length; i++) {
        afterFocus = [];

        // Register selection again
    }, 10);

Finding and removing non ascii characters from an Oracle Varchar2

Answer given by Francisco Hayoz is the best. Don't use pl/sql functions if sql can do it for you.

Here is the simple test in Oracle 11.2.03

select s
     , regexp_replace(s,'[^'||chr(1)||'-'||chr(127)||']','') "rep ^1-127"
     , dump(regexp_replace(s,'['||chr(127)||'-'||chr(225)||']','')) "rep 127-255"
from (
select listagg(c, '') within group (order by c) s
  from (select 127+level l,chr(127+level) c from dual connect by level < 129))

And "rep 127-255" is

Typ=1 Len=30: 226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255

i.e for some reason this version of Oracle does not replace char(226) and above. Using '['||chr(127)||'-'||chr(225)||']' gives the desired result. If you need to replace other characters just add them to the regex above or use nested replace|regexp_replace if the replacement is different then '' (null string).

Removing credits link

Both of the following code will work fine for removing from the chart:-

credits: false



Disabling vertical scrolling in UIScrollView

You need to pass 0 in content size to disable in which direction you want.

To disable vertical scrolling

scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,0);

To disable horizontal scrolling

scrollView.contentSize = CGSizeMake(0,scrollView.contentSize.height);

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

if you are getting id from url try

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

if getting from form you need to use POST method cause your form has method="post"

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

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

How do I import a .bak file into Microsoft SQL Server 2012?

Using the RESTORE DATABASE command most likely. bak is a common extension used for a database backup file. You'll find documentation for this command on MSDN.

How do I write a backslash (\) in a string?

There is a special function made for this Path.Combine()

var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/ = /etc/myapp/keyStore = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/");
Properties p = new Properties(System.getProperties());

JavaScript ternary operator example with functions

I know question is already answered.

But let me add one point here. This is not only case of true or false. See below:

var val="Do";

Var c= (val == "Do" || val == "Done")
          ? 7
          : 0

Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.

This is actually another perspective of this operator.

Installing Java 7 on Ubuntu

sudo apt-get update
sudo apt-get install openjdk-7-jdk

and if you already have other JDK versions installed

sudo update-alternatives --config java

then select the Java 7 version.

Bootstrap push div content to new line

If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.

This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).

<link href="" rel="stylesheet">_x000D_
<div class="grid">_x000D_
  <div class="row">_x000D_
    <div class="col-sm-3">Under me should be a DIV</div>_x000D_
    <div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
    <div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_

Omit rows containing specific column of NA

It is possible to use na.omit for data.table:

na.omit(data, cols = c("x", "z"))

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I manage to solve this in excel 97-2003, in a file with .xls extension this way: I went to the page where I had the linked data, with the cursor over the imported data table, go to tab Design --> External Data Table --> Unlink Unlink all tables (conections), delete all conections in Data --> Conections --> Conections save your work and done! regards, Dan

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

Build Eclipse Java Project from Command Line

Short answer. No. Eclipse does not have a command line switch like Visual Studio to build a project.

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx)

This is what apps like quicken, ms money etc use.

Implement division with bit-wise operator

All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.

public static Point divide(int a, int b) {

    if (a < b)
        return new Point(0,a);
    if (a == b)
        return new Point(1,0);
    int q = b;
    int c = 1;
    while (q<<1 < a) {
        q <<= 1;
        c <<= 1;
    Point r = divide(a-q, b);
    return new Point(c + r.x, r.y);

public static class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;

    public int compare(Point b) {
        if (b.x - x != 0) {
            return x - b.x;
        } else {
            return y - b.y;

    public String toString() {
        return " (" + x + " " + y + ") ";

Easiest way to read from and write to files

Use File.ReadAllText and File.WriteAllText.

MSDN example excerpt:

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);


// Open the file to read from.
string readText = File.ReadAllText(path);

Test if string is URL encoded in PHP

You'll never know for sure if a string is URL-encoded or if it was supposed to have the sequence %2B in it. Instead, it probably depends on where the string came from, i.e. if it was hand-crafted or from some application.

Is it better to search the string for characters which would be encoded, which aren't, and if any exist then its not encoded.

I think this is a better approach, since it would take care of things that have been done programmatically (assuming the application would not have left a non-encoded character behind).

One thing that will be confusing here... Technically, the % "should be" encoded if it will be present in the final value, since it is a special character. You might have to combine your approaches to look for should-be-encoded characters as well as validating that the string decodes successfully if none are found.

Git diff says subproject is dirty

EDIT: This answer (and most of the others) are obsolete; see Devpool's answer instead.

Originally, there were no config options to make "git diff --ignore-submodules" and "git status --ignore-submodules" the global default (but see also Setting git default flags on commands). An alternative is to set a default ignore config option on each individual submodule you want to ignore (for both git diff and git status), either in the .git/config file (local only) or .gitmodules (will be versioned by git). For example:

[submodule "foobar"]
    url = [email protected]:foo/bar.git
    ignore = untracked

ignore = untracked to ignore just untracked files, ignore = dirty to also ignore modified files, and ignore = all to ignore also commits. There's apparently no way to wildcard it for all submodules.

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

All too often a new developer asks this simple question which is a common problem specifically with Visual Studio IDE's. Few people answer the specific question and often critique the question or give "guesses" for solutions which don't answer the common problems. The first common problem is the IDE leads you to create new projects rather than add new files (.java, .py, .cpp, .c) to the existing solution (by default it creates a new solution) unless you change the project name and add to the current solution. This problem occurs for Python, java, c#, C++ and C project folders.

The new developer selecting "new>project>project name and changing the solution directory to "use same solution" still creates a new "project" in the same solution space, but not in the same directory space as the current user interface file or command line file which still leads to problems with "package not found" errors when building and running the project or solution. This is why the above coding suggestions to importing packages, classes, methods and functions only work (and thus don't answer the question) when the "library" file or "separate behavior" file is not only in the same solution directory path, but also in the same "user interface" or "command shell" application directory space. This does does not happen when you add another project using the new>project>project type commands of the IDE. The problem here is the new project is stored in a different directory than the existing Client or User interface code files. To create a new "file" in the same project space rather than new project the beginner needs to do the following that Microsoft won't do for you and even misleads you away from the intuitively obvious by default.

  1. Select the "application" you want to import the new behavior into (from another file)
  2. Select project>add new item
  3. Select the "program file template type" such as,, filetype.c, filetype.cpp, filetype.C#, etc. or a library class file type (something other than startup file options you see when you create a new application project or create a new library project).
  4. A new file name with default name is created in your project.
  5. Change the default name of the file to something like or faç, etc.

NOW the code recommendations to import libraries or using namespaces will work as described in the comments above and you don't have to change path statements or change solutions paths and solution names that Microsoft won't let you change easily (i.e. you can change the filenames or project names but the IDE won't automatically change the project path or the solution path names).

The following is a Python example but works similar for C#, java, or C/C++ using the includes, namespaces or using code commands appropriate to each language to find code in other classes/projects in the SAME DIRECTORY SPACE.

The application file "hello world" importing from other code files in the same directory.

Note the python white space delimiters are not going to space correctly in this stackoverflow comment editor:

print ("test")

from CIXMPythonFacade import ClassA


from CIXMPythonFacade import functionA 


class ClassName(object): 
         def __init__(object, parameter):
         object.parameter = value

The library file or "façade" file containing classes, methods or functions you want to import.

class class1(object):
    """description of class"""

class ClassA(object):
    print ("test2")
    def methodA():
        print ("test3")

def functionA ():
    print ("test4")
    return (0)


NOW how do you actually solve the mess that the IDE leads you into? To import code from another file in the same directory space you add a reference to it.

  1. Select the application file
  2. Select Project>add reference
  3. Choose the filename visible with the right directory path (check it)
  4. The reference is now available to the interpreter, the code checker and/or the compiler.

OK so now that you have this problem solved, how do you really link two separate projects together in the same solution space?

  1. You have to go to both the indexer or "intellisense" options and the compiler/interpreter and physically check or change/add the directory path statements if they are something other than what points to your "second" project or solution space. When you do the path changes or change the path variables to your workspace and to the specific locations of the projects which are different directory spaces the compiler and the code analyzer can then find these libraries, headers.h, namespaces, project or file locations.
  2. To remove old projects you created by mistake it is even worse. You have to exit the Visual Studio IDE, open windows explorer, go to the workspace directory ...documents\visualstudio xxx\solutionname\packagename select the file or folder, right click and "delete" file or folder.
  3. When you re-enter the IDE and select open solution or open package/solution, the old files and solution/package names are gone as are their misleading path statements which fools the compiler and code analyzer to look at the old directory even though you changed the filename and changed the project name, it does not change the directory path with it.

Microsoft really, really needs to fix these problem so you can intuitively create what most people want to create as new files in the same directories and remove solutions by selecting them and deleting them from the IDE. Beginners get so frustrated with directory path statements so flexible for seasoned developers, but so unfair to new developers in their defaults.

Hope this really helps you new guys and stops seasoned developers from giving you the wrong answers that don't work for you. They assume you already understand path statements and just want to type the right code...which is also why the tunnel in on trying to correct your code but does not help you fix the problem. This is probably the most common problem continually described on stackoverflow with wrong answers that don't work for new programmers.

What are some examples of commonly used practices for naming git branches?

Why does it take three branches/merges for every task? Can you explain more about that?

If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like "ResizeWindow-43523". It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.

Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with --squash, the entire history of the branch will still exist should you ever need it.

Calculate MD5 checksum for a file

This is how I do it:

using System.IO;
using System.Security.Cryptography;

public string checkMD5(string filename)
    using (var md5 = MD5.Create())
        using (var stream = File.OpenRead(filename))
            return Encoding.Default.GetString(md5.ComputeHash(stream));

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Iterate through <select> options

Another variation on the already proposed answers without jQuery.

Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))

How do I convert between ISO-8859-1 and UTF-8 in Java?

If you have a String, you can do that:

String s = "test";
try {
} catch(UnsupportedEncodingException uee) {

If you have a 'broken' String, you did something wrong, converting a String to a String in another encoding is defenetely not the way to go! You can convert a String to a byte[] and vice-versa (given an encoding). In Java Strings are AFAIK encoded with UTF-16 but that's an implementation detail.

Say you have a InputStream, you can read in a byte[] and then convert that to a String using

byte[] bs = ...;
String s;
try {
    s = new String(bs, encoding);
} catch(UnsupportedEncodingException uee) {

or even better (thanks to erickson) use InputStreamReader like that:

InputStreamReader isr;
try {
     isr = new InputStreamReader(inputStream, encoding);
} catch(UnsupportedEncodingException uee) {

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Look. This is way old, but on the off chance that someone from Google finds this, absolutely the best solution to this - (and it is AWESOME) - is to use ConEmu (or a package that includes and is built on top of ConEmu called cmder) and then either use plink or putty itself to connect to a specific machine, or, even better, set up a development environment as a local VM using Vagrant.

This is the only way I can ever see myself developing from a Windows box again.

I am confident enough to say that every other answer - while not necessarily bad answers - offer garbage solutions compared to this.

Update: As Of 1/8/2020 not all other solutions are garbage - Windows Terminal is getting there and WSL exists.

Create a folder if it doesn't already exist

Faster way to create folder:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);

How can I check file size in Python?

Using os.path.getsize:

>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b

The output is in bytes.

How to embed images in html email

I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.

Regarding displaying embedded (inline) images, here's what's on their documentation:

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

To give you a more complete example of how it would work:

$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = ""; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment(''); // this is a regular attachment (Not inline)
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!


Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.

One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.

For example:

You can replace the line that send the email:


With this:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want

Hope that helps. Let me know if you run into trouble using it.

'Framework not found' in Xcode

Here is the solution :

Turn the "$(PROJECT_DIR)" attribute(might be non-recursive by default) into recursive option in Select Project Click on Targets Click - Build Settings Search for 'Framework Search Path' - Double click the input.

Scratched from

Re-render React component when prop changes

You have to add a condition in your componentDidUpdate method.

The example is using fast-deep-equal to compare the objects.

import equal from 'fast-deep-equal'


  this.updateUser = this.updateUser.bind(this);

componentDidMount() {

componentDidUpdate(prevProps) {
  if(!equal(this.props.user, prevProps.user)) // Check if it's a new user, you can also use some unique property, like the ID  ( !==

updateUser() {
  if (this.props.isManager) {
  } else {
    const currentUserId = this.props.user.get('id')

Using Hooks (React 16.8.0+)

import React, { useEffect } from 'react';

const SitesTableContainer = ({
}) => {
  useEffect(() => {
    if(isManager) {
    } else {
      const currentUserId = user.get('id')
  }, [user]); 

  return (
    return <SitesTable sites={sites}/>


If the prop you are comparing is an object or an array, you should use useDeepCompareEffect instead of useEffect.

How do you import a large MS SQL .sql file?

I am using MSSQL Express 2014 and none of the solutions worked for me. They all just crashed SQL. As I only needed to run a one off script with many simple insert statements I got around it by writing a little console app as a very last resort:

class Program
    static void Main(string[] args)

    private static void RunScript()
        My_DataEntities db = new My_DataEntities();

        string line;

        System.IO.StreamReader file =
           new System.IO.StreamReader("c:\\ukpostcodesmssql.sql");
        while ((line = file.ReadLine()) != null)


How to vertically align text with icon font?

To expand on Marian Udrea's answer: In my scenario, I was trying to align the text with a material icon. There's something weird about material icons that prevented it from being aligned. None of the answers were working, until I added the vertical-align to the icon element, instead of the parent element.

So, if the icon is 24px in height:

.parent {
    line-height: 24px; // Same as icon height

    i.material-icons {  // Only if you're using material icons
      display: inline-flex;
      vertical-align: top;

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

Excellent answer already provide onsite here.

See the summary below:

  1. Go to the Build Path settings in the project properties.
  2. Remove the JRE System Library
  3. Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.

git pull error :error: remote ref is at but expected

I faced same issue , I just deleted the remote branch and created new branch from the master and merged my changes from old feature branch to new feature branch . Now i tried pull and push requests its worked for me

No output to console from a WPF application?

You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work).

Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type.

With the following class, you just need to write ConsoleManager.Show() somewhere before any call to Console.Write...

public static class ConsoleManager
    private const string Kernel32_DllName = "kernel32.dll";

    private static extern bool AllocConsole();

    private static extern bool FreeConsole();

    private static extern IntPtr GetConsoleWindow();

    private static extern int GetConsoleOutputCP();

    public static bool HasConsole
        get { return GetConsoleWindow() != IntPtr.Zero; }

    /// <summary>
    /// Creates a new console instance if the process is not attached to a console already.
    /// </summary>
    public static void Show()
        //#if DEBUG
        if (!HasConsole)

    /// <summary>
    /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.
    /// </summary>
    public static void Hide()
        //#if DEBUG
        if (HasConsole)

    public static void Toggle()
        if (HasConsole)

    static void InvalidateOutAndError()
        Type type = typeof(System.Console);

        System.Reflection.FieldInfo _out = type.GetField("_out",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        System.Reflection.FieldInfo _error = type.GetField("_error",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        Debug.Assert(_out != null);
        Debug.Assert(_error != null);

        Debug.Assert(_InitializeStdOutError != null);

        _out.SetValue(null, null);
        _error.SetValue(null, null);

        _InitializeStdOutError.Invoke(null, new object[] { true });

    static void SetOutAndErrorNull()

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

For my VB.Net Friends -

Dim scriptManager As ScriptManager = scriptManager.GetCurrent(Me.Page)

How to have comments in IntelliSense for function in Visual Studio?

Define Methods like this and you will get the help you need.

    /// <summary>
    /// Adds two numbers and returns the result
    /// </summary>
    /// <param name="first">first number to add</param>
    /// <param name="second">second number to </param>
    /// <returns></returns>
    private int Add(int first, int second)
        return first + second;

Screenshot of the code usage

How to retrieve a file from a server via SFTP?

Andy, to delete file on remote system you need to use (channelExec) of JSch and pass unix/linux commands to delete it.

Windows service on Local Computer started and then stopped error

Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:

protected override void OnStart(string[] args)

than you could attach your visual studio to the process and have better debug abilities.

hope this was helpful, good luck

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
    $.post('', function() {
      window.location = '';
    return false;

How to call a method defined in an AngularJS directive?

Below solution will be useful when, you are having controllers (both parent and directive (isolated)) in 'controller As' format

someone might find this useful,

directive :

var directive = {
        link: link,
        restrict: 'E',
        replace: true,
        scope: {
            clearFilters: '='
        templateUrl: "/temp.html",
        bindToController: true, 
        controller: ProjectCustomAttributesController,
        controllerAs: 'vmd'
    return directive;

    function link(scope, element, attrs) {
        scope.vmd.clearFilters = scope.vmd.SetFitlersToDefaultValue;

directive Controller :

function DirectiveController($location, dbConnection, uiUtility) {
  vmd.SetFitlersToDefaultValue = SetFitlersToDefaultValue;

function SetFitlersToDefaultValue() {
           //your logic

html code :

      <Test-directive clear-filters="vm.ClearFilters"></Test-directive>
    <a class="pull-right" style="cursor: pointer" ng-click="vm.ClearFilters()"><u>Clear</u></a> 
//this button is from parent controller which will call directive controller function

How to use timeit module

If you want to use timeit in an interactive Python session, there are two convenient options:

  1. Use the IPython shell. It features the convenient %timeit special function:

    In [1]: def f(x):
       ...:     return x*x
    In [2]: %timeit for x in range(100): f(x)
    100000 loops, best of 3: 20.3 us per loop
  2. In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement:

    >>> def f(x):
    ...     return x * x 
    >>> import timeit
    >>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f",
    [2.0640320777893066, 2.0876040458679199, 2.0520210266113281]

UICollectionView cell selection and cell reuse

Thanks to your answer @RDC.

The following codes works with Swift 3

// MARK: - UICollectionViewDataSource protocol
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    //prepare your cell here..
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCell
    cell.myLabel.text =  "my text"

    //Add background view for normal cell
    let backgroundView: UIView = UIView(frame: cell.bounds)
    backgroundView.backgroundColor = UIColor.lightGray
    cell.backgroundView = backgroundView

    //Add background view for selected cell
    let selectedBGView: UIView = UIView(frame: cell.bounds)
    selectedBGView.backgroundColor =
    cell.selectedBackgroundView = selectedBGView

    return cell

// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
    return true

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
    return true

How to change the output color of echo in Linux

Here there is a simple script to easily manage the text style in bash shell promt:

Import the code using:


Use the imported variable in echo command (use the -e option!):


It is possible to combine more elements:

echo -e ${PALETTE_GREEN}${PALETTE_BLINK}${PALETTE_RED_U}Green Blinking Text over Red Background${PALETTE_RESET}

enter image description here

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

OS X Bash, 'watch' command

Use MacPorts:

$ sudo port install watch

Multiple submit buttons in an HTML form

This works without JavaScript or CSS in most browsers:

    <p><input type="text" name="field1" /></p>
    <p><a href="previous.html">
    <button type="button">Previous Page</button></a>
    <button type="submit">Next Page</button></p>

Firefox, Opera, Safari, and Google Chrome all work.
As always, Internet Explorer is the problem.

This version works when JavaScript is turned on:

    <p><input type="text" name="field1" /></p>
    <p><a href="previous.html">
    <button type="button" onclick="window.location='previous.html'">Previous Page</button></a>
    <button type="submit">Next Page</button></p>

So the flaw in this solution is:

Previous Page does not work if you use Internet Explorer with JavaScript off.

Mind you, the back button still works!

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:


So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

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

I tried to do something similar and used a workaround solution: I thought about implicit and explicit operator on structure: The idea is to wrap the Type in a structure that can be converted into Type implicitly.

Here is such a structure:

public struct InterfaceType { private Type _type;

public InterfaceType(Type type)
    _type = type;

public static explicit operator Type(InterfaceType value)
    return value._type;

public static implicit operator InterfaceType(Type type)
    return new InterfaceType(type);

private static void CheckType(Type type)
    if (type == null) throw new NullReferenceException("The type cannot be null");
    if (!type.IsInterface) throw new NotSupportedException(string.Format("The given type {0} is not an interface, thus is not supported", type.Name));


basic usage:

// OK
InterfaceType type1 = typeof(System.ComponentModel.INotifyPropertyChanged);

// Throws an exception
InterfaceType type2 = typeof(WeakReference);

You have to imagine your own mecanism around this, but an example could be a method taken a InterfaceType in parameter instead of a type

this.MyMethod(typeof(IMyType)) // works
this.MyMethod(typeof(MyType)) // throws exception

A method to override that should returns interface types:

public virtual IEnumerable<InterfaceType> GetInterfaces()

There are maybe things to do with generics also, but I didn't tried

Hope this can help or gives ideas :-)

Reading/parsing Excel (xls) files with Python

If the file is really an old .xls, this works for me on python3 just using base open() and pandas:

df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='\t')

Note that the file I'm using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.

I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.

Manually adding a Userscript to Google Chrome

This parameter is is working for me:


Do the following:

  1. Right click on your "Chrome" icon.
  2. Choose properties
  3. At the end of your target line, place these parameters: --enable-easy-off-store-extension-install
  4. It should look like: chrome.exe --enable-easy-off-store-extension-install
  5. Start Chrome by double-clicking on the icon

Check if value exists in dataTable?

You can use Linq. Something like:

bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;

Eclipse Optimize Imports to Include Static Imports

Shortcut for static import: CTRL + SHIFT + M

Why does Eclipse Java Package Explorer show question mark on some classes?

this is because your project has been linked to a git-hub repository, and the file having question mark on it, is not been added yet. if you want to remove this sign you will have to add this file to git-hub repository.

how to create virtual host on XAMPP

Apache Virtual Host documentation Setting up a virtual host (vhost) provides several benefits:

  • Virtual Hosts make URLs cleaner – localhost/mysite vs mysite.local.
  • Virtual Hosts make permissions easier – restrict access for a single vhost on a local network vs permitting access to all sites on your local network.
  • Some applications require a “.” in the URL (ahem Magento). While you can setup by editing the Windows hosts file, creating a vhost is a better solution.

VirtualHost Directive Contains directives that apply only to a specific hostname or IP address

Location Directive Applies the enclosed directives only to matching URLs

Example changes over configuration file - D:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin localhost
    DocumentRoot "D:/xampp/htdocs"
    ServerName localhost

<VirtualHost localhost:80>
  ServerAdmin [email protected]
  DocumentRoot "/www/docs/"
  #DocumentRoot "D:\xampp\htdocs\phpPages"
  ErrorLog "logs/"
  TransferLog "logs/"

# To get view of PHP application in the Browser.
<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "D:\xampp\htdocs\app1"
    ErrorLog "logs/"
    CustomLog "logs/" combined
    # App1 communication proxy call to Java War applications from XAMP
    <Location /ServletApp1>
            Order Allow,Deny
            Allow from all

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "D:\xampp\htdocs\app2"
    ErrorLog "logs/"
    CustomLog "logs/" combined
    # App1 communication proxy call to Java War applications from XAMP
    <Location /ServletApp2>
            Order Allow,Deny
            Allow from all

Update Your Windows Hosts File « Open your Windows hosts file located in C:\Windows\System32\drivers\etc\hosts.

# localhost name resolution is handled within DNS itself.
#       localhost
#   ::1             localhost

D:\xampp\apache\conf\httpd.conf, [httpd-ssl.conf](

# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost> directive.
# Listen | [::]:80
Listen 80

LoadModule proxy_http_module modules/
LoadModule speling_module modules/

# ServerAdmin: Your address, where problems with the server should be e-mailed.
# This address appears on some server-generated pages, such as error documents.
#  e.g. [email protected]
ServerAdmin postmaster@localhost
ServerName localhost:80
DocumentRoot "D:/xampp/htdocs"

<Directory "D:/xampp/htdocs">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted

# Virtual hosts
Include "conf/extra/httpd-vhosts.conf"

# ===== httpd-ssl.conf - SSL Virtual Host Context =====
# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
#       Listen directives: "Listen [::]:443" and "Listen"
Listen 443
## SSL Virtual Host Context
<VirtualHost _default_:443>
    DocumentRoot "D:\xampp\htdocs\projectFolderSSL"
    ServerAdmin webmaster@localhost
    ErrorLog "logs/error.log"
    <IfModule log_config_module>
        CustomLog "logs/access.log" combined
    ## Redirecting URL from Web server to Application server over different machine.
    <Location /path>
        Order Allow,Deny
        Allow from all
    #SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateFile "D:\SSL_Vendor\yash.crt"
    #SSLCertificateKeyFile "conf/ssl.key/server.key"
    SSLCertificateKeyFile "D:\SSL_Vendor\private-key.key"
    #SSLCertificateChainFile "conf/ssl.crt/server-ca.crt"
    SSLCertificateChainFile "D:\SSL_Vendor\intermediate.crt"
# ===== httpd-ssl.conf - SSL Virtual Host Context =====


iOS 8 UITableView separator inset 0 not working

Adding this snippet, simple elegant in Swift works for me in iOS8 :)

    // tableview single line
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.preservesSuperviewLayoutMargins = false
    cell.layoutMargins = UIEdgeInsetsZero

What is the difference between Hibernate and Spring Data JPA

Hibernate is implementation of "JPA" which is a specification for Java objects in Database.

I would recommend to use w.r.t JPA as you can switch between different ORMS.

When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

How do I create a batch file timer to execute / call another batch throughout the day

better code that doesn't involve ping:

XCOPY "Server\*" "c:\minecraft\backups\server_backup_%COUNTER%" /i /s
timeout /t 600 /nobreak >nul
goto loop

600 seconds is 10 minutes, however you can set it whatever time you'd like

Correct format specifier to print pointer or address?

As an alternative to the other (very good) answers, you could cast to uintptr_t or intptr_t (from stdint.h/inttypes.h) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.

How do I run a program with a different working directory from current, from Linux shell?

If you always want it to go to /C, use an absolute path when you write the file.

How do you share code between projects/solutions in Visual Studio?

Two main steps involved are

1- Creating a C++ dll

In visual studio

New->Project->Class Library in c++ template. Name of project here is first_dll in 
visual studio 2010. Now declare your function as public in first_dll.h file and 
write the code in first_dll.cpp file as shown below.

Header File code

// first_dll.h

using namespace System;

namespace first_dll 

public ref class Class1
    static double sum(int ,int );
    // TODO: Add your methods for this class here.

Cpp File

#include "stdafx.h"

#include "first_dll.h"

namespace first_dll

    double Class1:: sum(int x,int y)
        return x+y;


Check This

**Project-> Properties -> Configuration/General -> Configuration Type** 

this option should be Dynamic Library(.dll) and build the solution/project now.

first_dll.dll file is created in Debug folder

2- Linking it in C# project

Open C# project

Rightclick on project name in solution explorer -> Add -> References -> Browse to path 
where first_dll.dll is created and add the file.

Add this line at top in C# project

Using first_dll; 

Now function from dll can be accessed using below statement in some function

double var = Class1.sum(4,5);

I created dll in c++ project in VS2010 and used it in VS2013 C# project.It works well.

WordPress path url in js script file

You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head() is called, holding the template URL. Like:

<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';

And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others): = " url('"+templateUrl+"/images/searchfield_clear.png') ";

Multiple lines of text in UILabel

In IB, set number of lines to 0 (allows unlimited lines)

When typing within the text field using IB, use "alt-return" to insert a return and go to the next line (or you can copy in text already separated out by lines).

Regular expression for exact match of a string

You may also try appending a space at the start and end of keyword: /\s+123456\s+/i.

Invalidating JSON Web Tokens

This seems really difficult to solve without a DB lookup upon every token verification. The alternative I can think of is keeping a blacklist of invalidated tokens server-side; which should be updated on a database whenever a change happens to persist the changes across restarts, by making the server check the database upon restart to load the current blacklist.

But if you keep it in the server memory (a global variable of sorts) then it's not gonna be scalable across multiple servers if you are using more than one, so in that case you can keep it on a shared Redis cache, which should be set-up to persist the data somewhere (database? filesystem?) in case it has to be restarted, and every time a new server is spun up it has to subscribe to the Redis cache.

Alternative to a black-list, using the same solution, you can do it with a hash saved in redis per session as this other answer points out (not sure that would be more efficient with many users logging in though).

Does it sound awfully complicated? it does to me!

Disclaimer: I have not used Redis.

What is the best project structure for a Python application?

Non-python data is best bundled inside your Python modules using the package_data support in setuptools. One thing I strongly recommend is using namespace packages to create shared namespaces which multiple projects can use -- much like the Java convention of putting packages in com.yourcompany.yourproject (and being able to have a shared com.yourcompany.utils namespace).

Re branching and merging, if you use a good enough source control system it will handle merges even through renames; Bazaar is particularly good at this.

Contrary to some other answers here, I'm +1 on having a src directory top-level (with doc and test directories alongside). Specific conventions for documentation directory trees will vary depending on what you're using; Sphinx, for instance, has its own conventions which its quickstart tool supports.

Please, please leverage setuptools and pkg_resources; this makes it much easier for other projects to rely on specific versions of your code (and for multiple versions to be simultaneously installed with different non-code files, if you're using package_data).

Show an image preview before upload

HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .

Here's a quick example that makes use of the FileReader class to read an image as DataURL and renders a thumbnail by setting the src attribute of an image tag to a data URL:

The html code:

<input type="file" id="files" />
<img id="image" />

The JavaScript code:

document.getElementById("files").onchange = function () {
    var reader = new FileReader();

    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("image").src =;

    // read the image file as a data URL.

Here's a good article on using the File APIs in JavaScript.

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

function handleFileSelect(evt) {_x000D_
    var files =;_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
      var reader = new FileReader();_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            '" title="', escape(, _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
      // Read in the image file as a data URL._x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

body { background: red; }_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_

Custom UITableViewCell from nib in Swift

You did not register your nib as below:

tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")

How to add background-image using ngStyle (angular2)?

Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.

.bg-img {                \/          \/
    background-image: url('http://...');

To do so escape quot character in HTML via \'

                                          \/                                  \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>

Scroll to the top of the page after render in react.js

Since the original solution was provided for very early version of react, here is an update:

constructor(props) {
    this.myRef = React.createRef()   // Create a ref object 

componentDidMount() {
  this.myRef.current.scrollTo(0, 0);

render() {
    return <div ref={this.myRef}></div> 
}   // attach the ref property to a dom element

Finding local maxima/minima with Numpy in a 1D numpy array

While this question is really old. I believe there is a much simpler approach in numpy (a one liner).

import numpy as np

list = [1,3,9,5,2,5,6,9,7]

np.diff(np.sign(np.diff(list))) #the one liner

array([ 0, -2,  0,  2,  0,  0, -2])

To find a local max or min we essentially want to find when the difference between the values in the list (3-1, 9-3...) changes from positive to negative (max) or negative to positive (min). Therefore, first we find the difference. Then we find the sign, and then we find the changes in sign by taking the difference again. (Sort of like a first and second derivative in calculus, only we have discrete data and don't have a continuous function.)

The output in my example does not contain the extrema (the first and last values in the list). Also, just like calculus, if the second derivative is negative, you have max, and if it is positive you have a min.

Thus we have the following matchup:

[1,  3,  9,  5,  2,  5,  6,  9,  7]
    [0, -2,  0,  2,  0,  0, -2]
        Max     Min         Max

Best way to check if object exists in Entity Framework?

I just check if object is null , it works 100% for me

        var ID = Convert.ToInt32(Request.Params["ID"]);
        var Cert = (from cert in db.TblCompCertUploads where cert.CertID == ID select cert).FirstOrDefault();
        if (Cert != null)
            ViewBag.Msg = "Deleted Successfully";
            ViewBag.Msg = "Not Found !!";
        ViewBag.Msg = "Something Went wrong";

How to fix Error: laravel.log could not be opened?

Delete "/var/www/laravel/app/storage/logs/laravel.log" and try again:

rm storage/logs/laravel.log

No numeric types to aggregate - change in groupby() behaviour?

How are you generating your data?

See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.

In [31]: data
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)

look ?

Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float).

You can also call frame.astype(float)

C: How to free nodes in the linked list?

One function can do the job,

void free_list(node *pHead)
    node *pNode = pHead, *pNext;

    while (NULL != pNode)
        pNext = pNode->next;
        pNode = pNext;


Load image from resources area of project in C#

I looked at the designer code from one of my projects and noticed it used this notation

myButton.Image = global::MyProjectName.Properties.Resources.max;

where max is the name of the resource I uploaded into the project.

Script not served by static file handler on IIS7.5

Navigate to your flavor of .Net and CPU architecture directory using CMD or powershell

Enter this command: aspnet_regiis –r

How do I change the UUID of a virtual disk?

The command fails because it has space in one of the folder name, i.e. 'VirtualBox VMs.

VBoxManage internalcommands sethduuid /home/user/VirtualBox VMs/drupal/drupal.vhd

If there is no space at folder name or file name, then the command will work even without quoting it, e.g. after changing 'VirtualBox VMs' into 'VBoxVMs'

VBoxManage internalcommands sethduuid /home/user/VBoxVMs/drupal/drupal.vhd

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

How to get the IP address of the docker host from inside a docker container

The only way is passing the host information as environment when you create a container

run --env <key>=<value>

How to return a result (startActivityForResult) from a TabHost Activity?


If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.

Formatting ISODate from Mongodb

you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

enter image description here

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Uninstall mongoDB from ubuntu

use command with sudo,

sudo apt-get autoremove --purge mongodb


sudo apt-get remove mongodb* --purge

It will remove complete mongodb

Resizing Images in VB.NET

This is basically Muhammad Saqib's answer except two diffs:

1: Adds width and height function parameters.

2: This is a small nuance which can be ignored... Saying 'As Bitmap', instead of 'As Image'. 'As Image' does work just fine. I just prefer to match Return types. See Image VS Bitmap Class.

Public Shared Function ResizeImage(ByVal InputBitmap As Bitmap, width As Integer, height As Integer) As Bitmap
    Return New Bitmap(InputImage, New Size(width, height))
End Function


Dim someimage As New Bitmap("C:\somefile")
someimage = ResizeImage(someimage,800,600)


INSERT INTO table_name1
SELECT id, name, address, contact_number FROM table_name2;   

How to receive JSON as an MVC 5 action method parameter

Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.

To solve your requirement, here is the working solution -

First create your ViewModels in following way. PersonModel can have list of RoleModels.

public class PersonModel
    public List<RoleModel> Roles { get; set; }
    public string Name { get; set; }

public class RoleModel
    public string RoleName { get; set;}
    public string Description { get; set;}

Then have a index action which will be serving basic index view -

public ActionResult Index()
    return View();

Index view will be having following JQuery AJAX POST operation -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    $(function () {
        $('#click1').click(function (e) {

            var jsonObject = {
                "Name" : "Rami",
                "Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]

                url: "@Url.Action("AddUser")",
                type: "POST",
                data: JSON.stringify(jsonObject),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                success: function (response) {


<input type="button" value="click1" id="click1" />

Index action posts to AddUser action -

public ActionResult AddUser(PersonModel model)
    if (model != null)
        return Json("Success");
        return Json("An Error Has occoured");

So now when the post happens you can get all the posted data in the model parameter of action.


For core, to get JSON data as your action parameter you should add the [FromBody] attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController] attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)

enter image description here

wget ssl alert handshake failure

Below command for download files from TLSv1.2 website.

curl -v --tlsv1.2

It`s worked!

Calling Scalar-valued Functions in SQL

Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

How to allow http content within an iframe on a https site

All you need to do is just use Google as a Proxy server.[YourHttpLink].

<iframe src="[Your http link]"></frame>

It worked for me.


What are the differences between C, C# and C++ in terms of real-world applications?

C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.

C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.

C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.

How do you do a deep copy of an object in .NET?

I have a simpler idea. Use LINQ with a new selection.

public class Fruit
  public string Name {get; set;}
  public int SeedCount {get; set;}

void SomeMethod()
  List<Fruit> originalFruits = new List<Fruit>();
  originalFruits.Add(new Fruit {Name="Apple", SeedCount=10});
  originalFruits.Add(new Fruit {Name="Banana", SeedCount=0});

  //Deep Copy
  List<Fruit> deepCopiedFruits = from f in originalFruits
              select new Fruit {Name=f.Name, SeedCount=f.SeedCount};

How do I apply CSS3 transition to all properties except background-position?

You can try using the standard W3C way:

.transition { transition: all 0.2s, top 0s, left 0s, width 0s, height 0s; }

What Does This Mean in PHP -> or =>

-> is used to call a method, or access a property, on the object of a class

=> is used to assign values to the keys of an array


    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2); 

And since PHP 7.4+ the operator => is used too for the added arrow functions, a more concise syntax for anonymous functions.

React Native TextInput that only accepts numeric characters

React Native TextInput provides keyboardType props with following possible values : default number-pad decimal-pad numeric email-address phone-pad

so for your case you can use keyboardType='number-pad' for accepting only numbers. This doesn't include '.'


  keyboardType = 'number-pad'
  onChangeText = {(text)=> this.onChanged(text)}
  value = {this.state.myNumber}

is what you have to use in your case.

for more details please refer the official doc link for TextInput :

How to decompile a whole Jar file?

Something like:

jar -xf foo.jar && find . -iname "*.class" | xargs /opt/local/bin/jad -r


How do I programmatically click on an element in JavaScript?

Using jQuery you can do exactly the same thing, for example:


Which will "click" all anchors on the page.

Algorithm to detect overlapping periods

How about a custom interval-tree structure? You'll have to tweak it a little bit to define what it means for two intervals to "overlap" in your domain.

This question might help you find an off-the-shelf interval-tree implementation in C#.

How do I mock a static method that returns void with PowerMock?

In simpler terms, Imagine if you want mock below line:


then you write below lines of code to mock:


MySQL: Set user variable from result of query

Just add parenthesis around the query:

set @user = 123456;
set @group = (select GROUP from USER where User = @user);
select * from USER where GROUP = @group;

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

There are possible solutions here:,64808,254785#msg-254785 and here:,23138,254786#msg-254786

All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.

Finally, more or less by accident, I bumped into the file:


Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.

What do two question marks together mean in C#?

?? is there to provide a value for a nullable type when the value is null. So, if formsAuth is null, it will return new FormsAuthenticationWrapper().

Update .NET web service to use TLS 1.2

Three steps needed:

  1. Explicitly mark SSL2.0, TLS1.0, TLS1.1 as forbidden on your server machine, by adding Enabled=0 and DisabledByDefault=1 to your registry (the full path is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols). See screen for details registry

  2. Explicitly enable TLS1.2 by following the steps from 1. Just use Enabled=1 and DisabledByDefault=0 respectively.

NOTE: verify server version: Windows Server 2003 does not support the TLS 1.2 protocol

  1. Enable TLS1.2 only on app level, like @John Wu suggested above.

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Hope this guide helps.

UPDATE As @Subbu mentioned: Official guide

Why do we use Base64?

Your first mistake is thinking that ASCII encoding and Base64 encoding are interchangeable. They are not. They are used for different purposes.

  • When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.
  • When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.

To understand why Base64 was necessary in the first place we need a little history of computing.

Computers communicate in binary - 0s and 1s - but people typically want to communicate with more rich forms data such as text or images. In order to transfer this data between computers it first has to be encoded into 0s and 1s, sent, then decoded again. To take text as an example - there are many different ways to perform this encoding. It would be much simpler if we could all agree on a single encoding, but sadly this is not the case.

Originally a lot of different encodings were created (e.g. Baudot code) which used a different number of bits per character until eventually ASCII became a standard with 7 bits per character. However most computers store binary data in bytes consisting of 8 bits each so ASCII is unsuitable for tranferring this type of data. Some systems would even wipe the most significant bit. Furthermore the difference in line ending encodings across systems mean that the ASCII character 10 and 13 were also sometimes modified.

To solve these problems Base64 encoding was introduced. This allows you to encode arbitrary bytes to bytes which are known to be safe to send without getting corrupted (ASCII alphanumeric characters and a couple of symbols). The disadvantage is that encoding the message using Base64 increases its length - every 3 bytes of data is encoded to 4 ASCII characters.

To send text reliably you can first encode to bytes using a text encoding of your choice (for example UTF-8) and then afterwards Base64 encode the resulting binary data into a text string that is safe to send encoded as ASCII. The receiver will have to reverse this process to recover the original message. This of course requires that the receiver knows which encodings were used, and this information often needs to be sent separately.

Historically it has been used to encode binary data in email messages where the email server might modify line-endings. A more modern example is the use of Base64 encoding to embed image data directly in HTML source code. Here it is necessary to encode the data to avoid characters like '<' and '>' being interpreted as tags.

Here is a working example:

I wish to send a text message with two lines:


If I send it as ASCII (or UTF-8) it will look like this:

72 101 108 108 111 10 119 111 114 108 100 33

The byte 10 is corrupted in some systems so we can base 64 encode these bytes as a Base64 string:


Which when encoded using ASCII looks like this:

83 71 86 115 98 71 56 75 100 50 57 121 98 71 81 104

All the bytes here are known safe bytes, so there is very little chance that any system will corrupt this message. I can send this instead of my original message and let the receiver reverse the process to recover the original message.

How do function pointers in C work?

Starting from scratch function has Some Memory Address From Where They start executing. In Assembly Language They Are called as (call "function's memory address").Now come back to C If function has a memory address then they can be manipulated by Pointers in C.So By the rules of C

1.First you need to declare a pointer to function 2.Pass the Address of the Desired function

****Note->the functions should be of same type****

This Simple Programme will Illustrate Every Thing.

void (*print)() ;//Declare a  Function Pointers
void sayhello();//Declare The Function Whose Address is to be passed
                //The Functions should Be of Same Type
int main()
 print=sayhello;//Addressof sayhello is assigned to print
 print();//print Does A call To The Function 
 return 0;

void sayhello()
 printf("\n Hello World");

enter image description hereAfter That lets See How machine Understands Them.Glimpse of machine instruction of the above programme in 32 bit architecture.

The red mark area is showing how the address is being exchanged and storing in eax. Then their is a call instruction on eax. eax contains the desired address of the function.

Start / Stop a Windows Service from a non-Administrator user account

subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

What does it mean when an HTTP request returns status code 0?

An HTTP response code of 0 indicates that the AJAX request was cancelled.

This can happen either from a timeout, XHR abortion or a firewall stomping on the request. A timeout is common, it means the request failed to execute within a specified time. An XHR Abortion is very simple to do... you can actually call .abort() on an XMLHttpRequest object to cancel the AJAX call. (This is good practice for a single page application if you don't want AJAX calls returning and attempting to reference objects that have been destroyed.) As mentioned in the marked answer, a firewall would also be capable of cancelling the request and trigger this 0 response.

XHR Abort: Abort Ajax requests using jQuery

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
       alert( "Data Saved: " + msg );

//kill the request

It's worth noting that running the .abort() method on an XHR object will also fire the error callback. If you're doing any kind of error handling that parses these objects, you'll quickly notice that an aborted XHR and a timeout XHR are identical, but with jQuery the textStatus that is passed to the error callback will be "abort" when aborted and "timeout" with a timeout occurs. If you're using Zepto (very very similar to jQuery) the errorType will be "error" when aborted and "timeout" when a timeout occurs.

jQuery: error(jqXHR, textStatus, errorThrown);
Zepto:  error(xhr, errorType, error);

Jackson - best way writes a java list to a json array

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

public void writeListToJsonArray() throws IOException {  
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(out, list);

    final byte[] data = out.toByteArray();
    System.out.println(new String(data));

How do I set a path in Visual Studio?

If you only need to add one path per configuration (debug/release), you could set the debug command working directory:

Project | Properties | Select Configuration | Configuration Properties | Debugging | Working directory

Repeat for each project configuration.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

Simply use the "utf-8-sig" codec:

fp = open("file.txt")
s =
u = s.decode("utf-8-sig")

That gives you a unicode string without the BOM. You can then use

s = u.encode("utf-8")

to get a normal UTF-8 encoded string back in s. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:

import os, sys, codecs

BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)

path = sys.argv[1]
with open(path, "r+b") as fp:
    chunk =
    if chunk.startswith(codecs.BOM_UTF8):
        i = 0
        chunk = chunk[BOMLEN:]
        while chunk:
            i += len(chunk)
  , os.SEEK_CUR)
            chunk =, os.SEEK_CUR)

It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.

As for guessing the encoding, then you can just loop through the encoding from most to least specific:

def decode(s):
    for encoding in "utf-8-sig", "utf-16":
            return s.decode(encoding)
        except UnicodeDecodeError:
    return s.decode("latin-1") # will always work

An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).

How to Create simple drag and Drop in angularjs

small scripts for drag and drop by angular

(function(angular) {
  'use strict';
angular.module('drag', []).
  directive('draggable', function($document) {
    return function(scope, element, attr) {
      var startX = 0, startY = 0, x = 0, y = 0;
       position: 'relative',
       border: '1px solid red',
       backgroundColor: 'lightgrey',
       cursor: 'pointer',
       display: 'block',
       width: '65px'
      element.on('mousedown', function(event) {
        // Prevent default dragging of selected content
        startX = event.screenX - x;
        startY = event.screenY - y;
        $document.on('mousemove', mousemove);
        $document.on('mouseup', mouseup);

      function mousemove(event) {
        y = event.screenY - startY;
        x = event.screenX - startX;
          top: y + 'px',
          left:  x + 'px'

      function mouseup() {
        $'mousemove', mousemove);
        $'mouseup', mouseup);

source link

Angular 4 - Select default value in dropdown [Reactive Forms]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>

In Chrome and Firefox works fine.

Is there an exponent operator in C#?

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.

It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.

You asked:

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

Math.Pow supports double parameters so there is no need for you to write your own.

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

How do I install imagemagick with homebrew?

You could do:

brew reinstall php55-imagick

Where php55 is your PHP version.

How to change colors of a Drawable in Android?

In your Activity you can tint your PNG image resources with a single colour:

protected void onCreate(Bundle savedInstanceState) {

private void myColorTint() {
    int tint = Color.parseColor("#0000FF"); //;
    PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
    // add your drawable resources you wish to tint to the drawables array...
    int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
    for (int id : drawables) {
        Drawable icon = getResources().getDrawable(id);

Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.

Given a view, how do I get its viewController?

The fast and generic way in Swift 3:

extension UIResponder {
    func parentController<T: UIViewController>(of type: T.Type) -> T? {
        guard let next = else {
            return nil
        return (next as? T) ?? next.parentController(of: T.self)

class MyView: UIView {
    let parentController = self.parentController(of: MyViewController.self)

What is the .idea folder?

There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.

It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.

How do I give PHP write access to a directory?

I had the same problem:

As I was reluctant to give 0777 to my php directory, I create a tmp directory with rights 0777, where I create the files I need to write to.

My php directory continue to be protected. If somebody hackes the tmp directory, the site continue to work as usual.

How to reload .bash_profile from the command line?

Simply type source ~/.bash_profile

Alternatively, if you like saving keystrokes you can type . ~/.bash_profile

Include PHP inside JavaScript (.js) files

This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.

I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.

Pointers, smart pointers or shared pointers?

Sydius outlined the types fairly well:

  • Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point.
  • Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense.
  • Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted.

How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.

There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.

There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.

The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.

How to round an image with Glide library?

Circle crop + placeholder + crossfade


enter image description here

How to convert Java String into byte[]?

You might wanna try return new String(byteout.toByteArray(Charset.forName("UTF-8")))

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Get an element by index in jQuery

$(...)[index]      // gives you the DOM element at index
$(...).get(index)  // gives you the DOM element at index
$(...).eq(index)   // gives you the jQuery object of element at index

DOM objects don't have css function, use the last...

$('ul li').eq(index).css({'background-color':'#343434'});


.get(index) Returns: Element

.eq(index) Returns: jQuery

Returning a C string from a function

You can create the array in the caller, which is the main function, and pass the array to the callee which is your myFunction(). Thus myFunction can fill the string into the array. However, you need to declare myFunction() as

char* myFunction(char * buf, int buf_len){
  strncpy(buf, "my string", buf_len);
  return buf;

And in main function, myFunction should be called in this way:

char array[51];
memset(array, 0, 51); /* All bytes are set to '\0' */
printf("%s", myFunction(array, 50)); /* The buf_len argument  is 50, not 51. This is to make sure the string in buf is always null-terminated (array[50] is always '\0') */

However, a pointer is still used.

How to call function that takes an argument in a Django template?

You cannot call a function that requires arguments in a template. Write a template tag or filter instead.

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

Same font except its weight seems different on different browsers

I have many sites with this issue & finally found a fix to firefox fonts being thicker than chrome.

You need this line next to your -webkit fix -moz-osx-font-smoothing: grayscale;

    text-rendering: optimizeLegibility;
   -webkit-font-smoothing: subpixel-antialiased;
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;