Programs & Examples On #Corecon

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Another cause might be the fact that you're pointing to the wrong port.

Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.

Check the ports and run some query against the db.

Override default Spring-Boot application.properties settings in Junit Test

Simple explanation:

If you are like me and you have the same application.properties in src/main/resources and src/test/resources, and you are wondering why the application.properties in your test folder is not overriding the application.properties in your main resources, read on...

If you have application.properties under src/main/resources and the same application.properties under src/test/resources, which application.properties gets picked up, depends on how you are running your tests. The folder structure src/main/resources and src/test/resources, is a Maven architectural convention, so if you run your test like mvnw test or even gradlew test, the application.properties in src/test/resources will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test in Eclipse/STS, the application.properties in src/main/resources will get picked up, as main classpath precedes test classpath.

You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line".

You will see something like this:

XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;

Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)

Side-note: Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

Try to specify the port in

conn = DriverManager.getConnection("jdbc:mysql://localhost/mysql?"
                                        + "user=root&password=onelife");

I think you should have something like this:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?"
                                            + "user=root&password=onelife");

Also, the port number in my example (3306) is the default port, but you may change it while installing MySQL.

I think that a better way to specify password and user is to separate them from the URL like this:

connection = DriverManager.getConnection(url, login, password);

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

You should specify the db you are connecting to:

jdbc:mysql://localhost:3306/mydb

Solving a "communications link failure" with JDBC and MySQL

I have had the same problem in two of my programs. My error was this:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I spent several days to solve this problem. I have tested many approaches that have been mentioned in different web sites, but non of them worked. Finally I changed my code and found out what was the problem. I'll try to tell you about different approaches and sum them up here.

While I was seeking the internet to find the solution for this error, I figured out that there are many solutions that worked for at least one person, but others say that it doesn't work for them! why there are many approaches to this error? It seems this error can occur generally when there is a problem in connecting to the server. Maybe the problem is because of the wrong query string or too many connections to the database.

So I suggest you to try all the solutions one by one and don't give up!

Here are the solutions that I found on the internet and for each of them, there is at least on person who his problem has been solved with that solution.

Tip: For the solutions that you need to change the MySQL settings, you can refer to the following files:

  • Linux: /etc/mysql/my.cnf or /etc/my.cnf (depending on the Linux distribution and MySQL package used)

  • Windows: C:**ProgramData**\MySQL\MySQL Server 5.6\my.ini (Notice it's ProgramData, not Program Files)

Here are the solutions:

  • changing "bind-address" attribute

Uncomment "bind-address" attribute or change it to one of the following IPs:

bind-address="127.0.0.1"

or

bind-address="0.0.0.0"

  • commenting out "skip-networking"

If there is a "skip-networking" line in your MySQL config file, make it comment by adding "#" sign at the beginning of that line.

  • change "wait_timeout" and "interactive_timeout"

Add these lines to the MySQL config file:

wait_timeout = number

interactive_timeout = number

connect_timeout = number

  • Make sure Java isn't translating 'localhost' to [:::1] instead of [127.0.0.1]

Since MySQL recognizes 127.0.0.1 (IPv4) but not :::1 (IPv6)

This could be avoided by using one of two approaches:

Option #1: In the connection string use 127.0.0.1 instead of localhost to avoid localhost being translated to :::1

Option #2: Run java with the option -Djava.net.preferIPv4Stack=true to force java to use IPv4 instead of IPv6. On Linux, this could also be achieved by running (or placing it inside /etc/profile:

export _JAVA_OPTIONS="-Djava.net.preferIPv4Stack=true"
  • check Operating System proxy settings, firewalls and anti-virus programs

Make sure the Firewall, or Anti-virus software isn't blocking MySQL service.

Stop iptables temporarily on linux. If iptables are misconfigured they may allow tcp packets to be sent to mysql port, but block tcp packets from coming back on the same connection.

# Redhat enterprise and CentOS
systemctl stop iptables.service
# Other linux distros
service iptables stop

Stop anti-virus software on Windows.

  • change connection string

Check your query string. your connection string should be some thing like this:

dbName = "my_database";
dbUserName = "root";
dbPassword = "";
String connectionString = "jdbc:mysql://localhost/" + dbName + "?user=" + dbUserName + "&password=" + dbPassword + "&useUnicode=true&characterEncoding=UTF-8";

Make sure you don't have spaces in your string. All the connection string should be continues without any space characters.

Try to replace "localhost" with the loopback address 127.0.0.1. Also try to add port number to your connection string, like:

String connectionString = "jdbc:mysql://localhost:3306/my_database?user=root&password=Pass&useUnicode=true&characterEncoding=UTF-8";

Usually default port for MySQL is 3306.

Don't forget to change username and password to the username and password of your MySQL server.

  • update your JDK driver library file
  • test different JDK and JREs (like JDK 6 and 7)
  • don't change max_allowed_packet

"max_allowed_packet" is a variable in MySQL config file that indicates the maximum packet size, not the maximum number of packets. So it will not help to solve this error.

  • change tomcat security

change TOMCAT6_SECURITY=yes to TOMCAT6_SECURITY=no

  • use validationQuery property

use validationQuery="select now()" to make sure each query has responses

  • AutoReconnect

Add this code to your connection string:

&autoReconnect=true&failOverReadOnly=false&maxReconnects=10

Although non of these solutions worked for me, I suggest you to try them. Because there are some people who solved their problem with following these steps.

But what solved my problem?

My problem was that I had many SELECTs on database. Each time I was creating a connection and then closing it. Although I was closing the connection every time, but the system faced with many connections and gave me that error. What I did was that I defined my connection variable as a public (or private) variable for whole class and initialized it in the constructor. Then every time I just used that connection. It solved my problem and also increased my speed dramatically.

Conclusion

There is no simple and unique way to solve this problem. I suggest you to think about your own situation and choose above solutions. If you take this error at the beginning of the program and you are not able to connect to the database at all, you might have problem in your connection string. But If you take this error after several successful interaction to the database, the problem might be with number of connections and you may think about changing "wait_timeout" and other MySQL settings or rewrite your code how that reduce number of connections.

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

C++ static virtual members?

No, there's no way to do it, since what would happen when you called Object::GetTypeInformation()? It can't know which derived class version to call since there's no object associated with it.

You'll have to make it a non-static virtual function to work properly; if you also want to be able to call a specific derived class's version non-virtually without an object instance, you'll have to provide a second redunduant static non-virtual version as well.

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

How can I pass a parameter to a setTimeout() callback?

setTimeout(function() {
    postinsql(topicId);
}, 4000)

You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout() or setInterval(), it's slower because it has to be evaluated and it just isn't right.

UPDATE:

As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using Function.prototype.bind().

Example:

setTimeout(postinsql.bind(null, topicId), 4000);

Show loading image while $.ajax is performed

You can add ajax start and complete event, this is work for when you click on button event

 $(document).bind("ajaxSend", function () {
            $(":button").html('<i class="fa fa-spinner fa-spin"></i> Loading');
            $(":button").attr('disabled', 'disabled');
        }).bind("ajaxComplete", function () {
            $(":button").html('<i class="fa fa-check"></i> Show');
            $(":button").removeAttr('disabled', 'disabled');
        });

How to resize images proportionally / keeping the aspect ratio?

If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-width and max-height to 100%.

<div style="height: 100px">
<img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg"
    style="max-height: 100%; max-width: 100%">
</div>?

Here's the fiddle: http://jsfiddle.net/9EQ5c/

Google Maps API v3: InfoWindow not sizing correctly

Add a min-height to your infoWindow class element.

That will resolve the issue if your infoWindows are all the same size.

If not, add this line of jQuery to your click function for the infoWindow:

//remove overflow scrollbars
$('#myDiv').parent().css('overflow','');

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

Express: How to pass app-instance to routes from a different file?

For database separate out Data Access Service that will do all DB work with simple API and avoid shared state.

Separating routes.setup looks like overhead. I would prefer to place a configuration based routing instead. And configure routes in .json or with annotations.

Declare and assign multiple string variables at the same time

You can to do it this way:

string Camnr = "", Klantnr = "", ... // or String.Empty

Or you could declare them all first and then in the next line use your way.

iterating over and removing from a map

Java 8 support a more declarative approach to iteration, in that we specify the result we want rather than how to compute it. Benefits of the new approach are that it can be more readable, less error prone.

public static void mapRemove() {

    Map<Integer, String> map = new HashMap<Integer, String>() {
        {
            put(1, "one");
            put(2, "two");
            put(3, "three");
        }
    };

    map.forEach( (key, value) -> { 
        System.out.println( "Key: " + key + "\t" + " Value: " + value );  
    }); 

    map.keySet().removeIf(e->(e>2)); // <-- remove here

    System.out.println("After removing element");

    map.forEach( (key, value) -> { 
        System.out.println( "Key: " + key + "\t" + " Value: " + value ); 
    });
}

And result is as follows:

Key: 1   Value: one
Key: 2   Value: two
Key: 3   Value: three
After removing element
Key: 1   Value: one
Key: 2   Value: two

How to save a Seaborn plot into a file

Just FYI, the below command worked in seaborn 0.8.1 so I guess the initial answer is still valid.

sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")

Git: How to check if a local repo is up to date?

you can use git status -uno to check if your local branch is up-to-date with the origin one.

How to fix: Error device not found with ADB.exe

For me, I have to Revoke USB debugging authorizations in Developer Options. Here is the steps:

  1. Turn off USB Debugging,
  2. Revoke USB debugging authorizations,
  3. Plug the cable back in,
  4. Turn on USB Debugging

How to draw circle by canvas in Android?

Try this

enter image description here

The entire code for drawing a circle or download project source code and test it on your android studio. Draw circle on canvas programmatically.

import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.graphics.Point;
    import android.graphics.PorterDuff;
    import android.graphics.PorterDuffXfermode;
    import android.graphics.Rect;
    import android.graphics.RectF;
    import android.widget.ImageView;


        public class Shape {

            private Bitmap bmp;
            private ImageView img;
            public Shape(Bitmap bmp, ImageView img) {

                this.bmp=bmp;
                this.img=img;
                onDraw();
            }

            private void onDraw(){
                 Canvas canvas=new Canvas();
                 if (bmp.getWidth() == 0 || bmp.getHeight() == 0) {
                     return;
                }

                int w = bmp.getWidth(), h = bmp.getHeight();

                Bitmap roundBitmap = getRoundedCroppedBitmap(bmp, w);

                img.setImageBitmap(roundBitmap);

            }

            public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
                Bitmap finalBitmap;
                if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
                    finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                            false);
                else
                    finalBitmap = bitmap;
                Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                        finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(output);

                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                        finalBitmap.getHeight());

                paint.setAntiAlias(true);
                paint.setFilterBitmap(true);
                paint.setDither(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(Color.parseColor("#BAB399"));
                canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f, finalBitmap.getWidth() / 2 + 0.1f, paint);
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                canvas.drawBitmap(finalBitmap, rect, rect, paint);

                return output;
            }

Try reinstalling `node-sass` on node 0.12?

you may also want to npm remove gulp-sass and re-install gulp-sass if you've switched node versions.

Set Response Status Code

PHP <=5.3

The header() function has a parameter for status code. If you specify it, the server will take care of it from there.

header('HTTP/1.1 401 Unauthorized', true, 401);

PHP >=5.4

See Gajus' answer: https://stackoverflow.com/a/14223222/362536

I can’t find the Android keytool

Okay, so this post is from six months ago, but I thought I would add some info here for people who are confused about the whole API key/MD5 fingerprint business. It took me a while to figure out, so I assume others have had trouble with it too (unless I'm just that dull).

These directions are for Windows XP, but I imagine it is similar for other versions of Windows. It appears Mac and Linux users have an easier time with this so I won't address them.

So in order to use mapviews in your Android apps, Google wants to check in with them so you can sign off on an Android Maps APIs Terms Of Service agreement. I think they don't want you to make any turn-by-turn GPS apps to compete with theirs or something. I didn't really read it. Oops.

So go to http://code.google.com/android/maps-api-signup.html and check it out. They want you to check the "I have read and agree with the terms and conditions" box and enter your certificate's MD5 fingerprint. Wtf is that, you might say. I don't know, but just do what I say and your Android app doesn't get hurt.

Go to Start>Run and type cmd to open up a command prompt. You need to navigate to the directory with the keytool.exe file, which might be in a slightly different place depending on which version JDK you have installed. Mine is in C:\Program Files\Java\jdk1.6.0_21\bin but try browsing to the Java folder and see what version you have and change the path accordingly.

After navigating to C:\Program Files\Java\<"your JDK version here">\bin in the command prompt, type

keytool -list -keystore "C:/Documents and Settings/<"your user name here">/.android/debug.keystore"

with the quotes. Of course <"your user name here"> would be your own Windows username.

(If you are having trouble finding this path and you are using Eclipse, you can check Window>preferences>Android>Build and check out the "Default Debug keystore")

Press enter and it will prompt you for a password. Just press enter. And voila, at the bottom is your MD5 fingerprint. Type your fingerprint into the text box at the Android Maps API Signup page and hit Generate API Key.

And there's your key in all its glory, with a handy sample xml layout with your key entered for you to copy and paste.

Testing if a checkbox is checked with jQuery

// use ternary operators
$("#ans").is(':checked') ? 1 : 0;

How to use variables in SQL statement in Python?

Many ways. DON'T use the most obvious one (%s with %) in real code, it's open to attacks.

Here copy-paste'd from pydoc of sqlite3:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

More examples if you need:

# Multiple values single statement/execution
c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO'))
print c.fetchall()
c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO'))
print c.fetchall()
# This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice.
c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO')
print c.fetchall()
# Insert a single item
c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00))

Is a Python dictionary an example of a hash table?

There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:

>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438

Yet it doesn't break the dictionary:

>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'

Sanity check:

>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438

Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.

(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8).)

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

Add ArrayList to another ArrayList in java

Initiate the NodeList inside the for loop and you will get the desired output.

ArrayList<String> nodes = new ArrayList<String>();
 ArrayList list=new ArrayList();

        for(int i=0;i<PropertyNode.getLength()-1;i++){
            ArrayList NodeList=new ArrayList();
            Node childNode =  PropertyNode.item(i);
                NodeList Children = childNode.getChildNodes();

                if(Children!=null){
                    nodes.clear();
                    nodes.add("PropertyStart");
                    nodes.add(Children.item(3).getTextContent());
                    nodes.add(Children.item(7).getTextContent());
                    nodes.add(Children.item(9).getTextContent());
                    nodes.add(Children.item(11).getTextContent());
                    nodes.add(Children.item(13).getTextContent());
                    nodes.add("PropertyEnd");

                }   
                NodeList.addAll(nodes);
                list.add(NodeList);
        }

Explanation: NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once. The loop is only adding its variables in single NodeList array hence you must be seeing

[/*list*/    [  /*NodeList*/   ]   ]

and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]

How do I mock an autowired @Value field in Spring with Mockito?

Also note that I have no explicit "setter" methods (e.g. setDefaultUrl) in my class and I don't want to create any just for the purposes of testing.

One way to resolve this is change your class to use Constructor Injection, that is used for testing and Spring injection. No more reflection :)

So, you can pass any String using the constructor:

class MySpringClass {

    private final String defaultUrl;
    private final String defaultrPassword;

    public MySpringClass (
         @Value("#{myProps['default.url']}") String defaultUrl, 
         @Value("#{myProps['default.password']}") String defaultrPassword) {
        this.defaultUrl = defaultUrl;
        this.defaultrPassword= defaultrPassword;
    }

}

And in your test, just use it:

MySpringClass MySpringClass  = new MySpringClass("anyUrl", "anyPassword");

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I solved mine by deleting the .settings folder and .project file in the project and then reimporting the project.

Declaring variables inside or outside of a loop

You have a risk of NullPointerException if your calculateStr() method returns null and then you try to call a method on str.

More generally, avoid having variables with a null value. It stronger for class attributes, by the way.

Is the sizeof(some pointer) always equal to four?

In addition to what people have said about 64-bit (or whatever) systems, there are other kinds of pointer than pointer-to-object.

A pointer-to-member might be almost any size, depending how they're implemented by your compiler: they aren't necessarily even all the same size. Try a pointer-to-member of a POD class, and then a pointer-to-member inherited from one of the base classes of a class with multiple bases. What fun.

Redirecting Output from within Batch file

if you want both out and err streams redirected

dir >> a.txt 2>&1

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

Git clone without .git directory

Alternatively, if you have Node.js installed, you can use the following command:

npx degit GIT_REPO

npx comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit globally using npm i -g degit).

Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...

Can I do Android Programming in C++, C?

You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.

Confirmation before closing of tab/browser

The shortest solution for the year 2020 (for those happy people who don't need to support IE)

Tested in Chrome, Firefox, Safari.

function onBeforeUnload(e) {
    if (thereAreUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = '';
        return;
    }

    delete e['returnValue'];
}

window.addEventListener('beforeunload', onBeforeUnload);

Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user. Instead they show their own confirmation text (it depends on browser). But we still need to return some (even empty) string to trigger that confirmation on Chrome.

More explanations see on MDN here and here.

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Selecting text in an element (akin to highlighting with your mouse)

Tim's method works perfectly for my case - selecting the text in a div for both IE and FF after I replaced the following statement:

range.moveToElementText(text);

with the following:

range.moveToElementText(el);

The text in the div is selected by clicking it with the following jQuery function:

$(function () {
    $("#divFoo").click(function () {
        selectElementText(document.getElementById("divFoo"));
    })
});

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

PHP Composer behind http proxy

on Windows insert:

set http_proxy=<proxy>
set https_proxy=<proxy>

before

php "%~dp0composer.phar" %*

or on Linux insert:

export http_proxy=<proxy>
export https_proxy=<proxy>

before

php "${dir}/composer.phar" "$@"

Server.Transfer Vs. Response.Redirect

enter image description here

"response.redirect" and "server.transfer" helps to transfer user from one page to other page while the page is executing. But the way they do this transfer / redirect is very different.

In case you are visual guy and would like see demonstration rather than theory I would suggest to see the below facebook video which explains the difference in a more demonstrative way.

https://www.facebook.com/photo.php?v=762186150488997

The main difference between them is who does the transfer. In "response.redirect" the transfer is done by the browser while in "server.transfer" it’s done by the server. Let us try to understand this statement in a more detail manner.

In "Server.Transfer" following is the sequence of how transfer happens:-

1.User sends a request to an ASP.NET page. In the below figure the request is sent to "WebForm1" and we would like to navigate to "Webform2".

2.Server starts executing "Webform1" and the life cycle of the page starts. But before the complete life cycle of the page is completed “Server.transfer” happens to "WebForm2".

3."Webform2" page object is created, full page life cycle is executed and output HTML response is then sent to the browser.

enter image description here

While in "Response.Redirect" following is the sequence of events for navigation:-

1.Client (browser) sends a request to a page. In the below figure the request is sent to "WebForm1" and we would like to navigate to "Webform2".

2.Life cycle of "Webform1" starts executing. But in between of the life cycle "Response.Redirect" happens.

3.Now rather than server doing a redirect , he sends a HTTP 302 command to the browser. This command tells the browser that he has to initiate a GET request to "Webform2.aspx" page.

4.Browser interprets the 302 command and sends a GET request for "Webform2.aspx".

enter image description here

In other words "Server.Transfer" is executed by the server while "Response.Redirect" is executed by thr browser. "Response.Redirect" needs to two requests to do a redirect of the page.

So when to use "Server.Transfer" and when to use "Response.Redirect" ?

Use "Server.Transfer" when you want to navigate pages which reside on the same server, use "Response.Redirect" when you want to navigate between pages which resides on different server and domain.

enter image description here

Below is a summary table of which chalks out differences and in which scenario to use.

enter image description here

Get client IP address via third party web service

Checking your linked site, you may include a script tag passing a ?var=desiredVarName parameter which will be set as a global variable containing the IP address:

<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
                                                      <!-- ^^^^ -->
<script>alert(myip);</script>

Demo

I believe I don't have to say that this can be easily spoofed (through either use of proxies or spoofed request headers), but it is worth noting in any case.


HTTPS support

In case your page is served using the https protocol, most browsers will block content in the same page served using the http protocol (that includes scripts and images), so the options are rather limited. If you have < 5k hits/day, the Smart IP API can be used. For instance:

<script>
var myip;
function ip_callback(o) {
    myip = o.host;
}
</script>
<script src="https://smart-ip.net/geoip-json?callback=ip_callback"></script>
<script>alert(myip);</script>

Demo

Edit: Apparently, this https service's certificate has expired so the user would have to add an exception manually. Open its API directly to check the certificate state: https://smart-ip.net/geoip-json


With back-end logic

The most resilient and simple way, in case you have back-end server logic, would be to simply output the requester's IP inside a <script> tag, this way you don't need to rely on external resources. For example:

PHP:

<script>var myip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script>

There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.

C#:

<script>var myip = '<%= Request.UserHostAddress %>';</script>

Java double comparison epsilon

Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.

0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.

Case insensitive std::string.find()

Also make sense to provide Boost version: This will modify original strings.

#include <boost/algorithm/string.hpp>

string str1 = "hello world!!!";
string str2 = "HELLO";
boost::algorithm::to_lower(str1)
boost::algorithm::to_lower(str2)

if (str1.find(str2) != std::string::npos)
{
    // str1 contains str2
}

or using perfect boost xpression library

#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
....
std::string long_string( "very LonG string" );
std::string word("long");
smatch what;
sregex re = sregex::compile(word, boost::xpressive::icase);
if( regex_match( long_string, what, re ) )
{
    cout << word << " found!" << endl;
}

In this example you should pay attention that your search word don't have any regex special characters.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How do I do top 1 in Oracle?

With Oracle 12c (June 2013), you are able to use it like the following.

SELECT * FROM   MYTABLE
--ORDER BY COLUMNNAME -OPTIONAL          
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

Specifying maxlength for multiline textbox

you can specify the max length for the multiline textbox in pageLoad Javascript Event

function pageLoad(){
                     $("[id$='txtInput']").attr("maxlength","10");
                    }

I have set the max length property of txtInput multiline textbox to 10 characters in pageLoad() Javascript function

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

How do I add the contents of an iterable to a set?

For the benefit of anyone who might believe e.g. that doing aset.add() in a loop would have performance competitive with doing aset.update(), here's an example of how you can test your beliefs quickly before going public:

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 294 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 950 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 458 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 598 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 1.89 msec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 891 usec per loop

Looks like the cost per item of the loop approach is over THREE times that of the update approach.

Using |= set() costs about 1.5x what update does but half of what adding each individual item in a loop does.

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

Allow multiple roles to access controller action

If you want use custom roles, you can do this:

CustomRoles class:

public static class CustomRoles
{
    public const string Administrator = "Administrador";
    public const string User = "Usuario";
}

Usage

[Authorize(Roles = CustomRoles.Administrator +","+ CustomRoles.User)]

If you have few roles, maybe you can combine them (for clarity) like this:

public static class CustomRoles
{
     public const string Administrator = "Administrador";
     public const string User = "Usuario";
     public const string AdministratorOrUser = Administrator + "," + User;  
}

Usage

[Authorize(Roles = CustomRoles.AdministratorOrUser)]

filename and line number of Python script

Thanks to mcandre, the answer is:

#python3
from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

print(frameinfo.filename, frameinfo.lineno)

Get only specific attributes with from Laravel Collection

  1. You need to define $hidden and $visible attributes. They'll be set global (that means always return all attributes from $visible array).

  2. Using method makeVisible($attribute) and makeHidden($attribute) you can dynamically change hidden and visible attributes. More: Eloquent: Serialization -> Temporarily Modifying Property Visibility

HTML "overlay" which allows clicks to fall through to elements behind it

A silly hack I did was to set the height of the element to zero but overflow:visible; combining this with pointer-events:none; seems to cover all the bases.

.overlay {
    height:0px;
    overflow:visible;
    pointer-events:none;
    background:none !important;
}

textarea's rows, and cols attribute in CSS

As far as I know, you can't.

Besides, that isnt what CSS is for anyway. CSS is for styling and HTML is for markup.

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
    Module1.StartTimer
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

What is default color for text in textview?

I found that android:textColor="@android:color/secondary_text_dark" provides a closer result to the default TextView color than android:textColor="@android:color/tab_indicator_text". I suppose you have to switch between secondary_text_dark/light depending on the Theme you are using

A CSS selector to get last visible div

It is not possible with CSS, however you could do this with jQuery.

JSFIDDLE DEMO

jQuery:

$('li').not(':hidden').last().addClass("red");

HTML:

<ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li class="hideme">Item 4</li>    
</ul>

CSS:

.hideme {
    display:none;
}

.red {
    color: red;
}

jQuery (previous solution):

var $items = $($("li").get().reverse());

$items.each(function() {

    if ($(this).css("display") != "none") {
        $(this).addClass("red");
        return false;
    }

});

Select last N rows from MySQL

select * from Table ORDER BY id LIMIT 30

Notes: * id should be unique. * You can control the numbers of rows returned by replacing the 30 in the query

Android and setting alpha for (image) view alpha

The alpha can be set along with the color using the following hex format #ARGB or #AARRGGBB. See http://developer.android.com/guide/topics/resources/color-list-resource.html

Sending a notification from a service in Android

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification()
{
    NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context);
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0);

    //set
    builder.setContentIntent(contentIntent);
    builder.setSmallIcon(R.drawable.cal_icon);
    builder.setContentText("Contents");
    builder.setContentTitle("title");
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);

    Notification notification = builder.build();
    nm.notify((int)System.currentTimeMillis(),notification);
}

Log4Net configuring log level

you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters

in ur appender section add

<filter type="log4net.Filter.LevelMatchFilter">
    <levelToMatch value="Info" />
    <acceptOnMatch value="true" />
</filter>

the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

  1. CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

  1. PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  1. DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

you can find more about on_delete by reading the documentation.

How can I export a GridView.DataSource to a datatable or dataset?

Personally I would go with:

DataTable tbl = Gridview1.DataSource as DataTable;

This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.

Supporting Documentation: MSDN Documentation on "as"

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Using this code to multiple order by in single query.

$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get(); 
return $query->result();

Array of an unknown length in C#

Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.

Search for them in System.Collections and System.Collections.Generics.

Serialize Class containing Dictionary member

Dictionaries and Hashtables are not serializable with XmlSerializer. Therefore you cannot use them directly. A workaround would be to use the XmlIgnore attribute to hide those properties from the serializer and expose them via a list of serializable key-value pairs.

PS: constructing an XmlSerializer is very expensive, so always cache it if there is a chance of being able to re-use it.

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

Uses for the '&quot;' entity in HTML

In my experience it may be the result of auto-generation by a string-based tools, where the author did not understand the rules of HTML.

When some developers generate HTML without the use of special XML-oriented tools, they may try to be sure the resulting HTML is valid by taking the approach that everything must be escaped.

Referring to your example, the reason why every occurrence of " is represented by &quot; could be because using that approach, you can safely use such "special" characters in both attributes and values.

Another motivation I've seen is where people believe, "We must explicitly show that our symbols are not part of the syntax." Whereas, valid HTML can be created by using the proper string-manipulation tools, see the previous paragraph again.

Here is some pseudo-code loosely based on C#, although it is preferred to use valid methods and tools:

public class HtmlAndXmlWriter
{
    private string Escape(string badString)
    {
        return badString.Replace("&", "&amp;").Replace("\"", "&quot;").Replace("'", "&apos;").Replace(">", "&gt;").Replace("<", "&lt;");

    }

    public string GetHtmlFromOutObject(Object obj)
    {
        return "<div class='type_" + Escape(obj.Type) + "'>" + Escape(obj.Value) + "</div>";    

    }

}

It's really very common to see such approaches taken to generate HTML.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

concat.js is being included in the concat task's source files public/js/*.js. You could have a task that removes concat.js (if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.

If doing the latter, you could put all your sources under ./src and your built files under ./dest

src
+-- css
¦   +-- 1.css
¦   +-- 2.css
¦   +-- 3.css
+-- js
    +-- 1.js
    +-- 2.js
    +-- 3.js

Then set up your concat task

concat: {
  js: {
    src: 'src/js/*.js',
    dest: 'dest/js/concat.js'
  },
  css: {
    src: 'src/css/*.css',
    dest: 'dest/css/concat.css'
  }
},

Your min task

min: {
  js: {
    src: 'dest/js/concat.js',
    dest: 'dest/js/concat.min.js'
  }
},

The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file

grunt.loadNpmTasks('grunt-css');

And then set it up

cssmin: {
  css:{
    src: 'dest/css/concat.css',
    dest: 'dest/css/concat.min.css'
  }
}

Notice that the usage is similar to the built-in min.

Change your default task to

grunt.registerTask('default', 'concat min cssmin');

Now, running grunt will produce the results you want.

dest
+-- css
¦   +-- concat.css
¦   +-- concat.min.css
+-- js
    +-- concat.js
    +-- concat.min.js

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

How to get client IP address in Laravel 5+

Looking at the Laravel API:

Request::ip();

Internally, it uses the getClientIps method from the Symfony Request Object:

public function getClientIps()
{
    $clientIps = array();
    $ip = $this->server->get('REMOTE_ADDR');
    if (!$this->isFromTrustedProxy()) {
        return array($ip);
    }
    if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
        $forwardedHeader = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
        preg_match_all('{(for)=("?\[?)([a-z0-9\.:_\-/]*)}', $forwardedHeader, $matches);
        $clientIps = $matches[3];
    } elseif (self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
        $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
    }
    $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
    $ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies
    foreach ($clientIps as $key => $clientIp) {
        // Remove port (unfortunately, it does happen)
        if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
            $clientIps[$key] = $clientIp = $match[1];
        }
        if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
            unset($clientIps[$key]);
        }
    }
    // Now the IP chain contains only untrusted proxies and the client IP
    return $clientIps ? array_reverse($clientIps) : array($ip);
} 

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

How can I group data with an Angular filter?

In addition to the accepted answer you can use this if you want to group by multiple columns:

<ul ng-repeat="(key, value) in players | groupBy: '[team,name]'">

Making the Android emulator run faster

Update your current Android Studio to Android Studio 2.0 And also update system images.

Android Studio 2.0 emulator runs ~3x faster than Android’s previous emulator, and with ADB enhancements you can now push apps and data 10x faster to the emulator than to a physical device. Like a physical device, the official Android emulator also includes Google Play Services built-in, so you can test out more API functionality. Finally, the new emulator has rich new features to manage calls, battery, network, GPS, and more.

How to make an HTTP POST web request

Why is this not totally trivial? Doing the request is not and especially not dealing with the results and seems like there are some .NET bugs involved as well - see Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException

I ended up with this code:

static async Task<(bool Success, WebExceptionStatus WebExceptionStatus, HttpStatusCode? HttpStatusCode, string ResponseAsString)> HttpRequestAsync(HttpClient httpClient, string url, string postBuffer = null, CancellationTokenSource cts = null) {
    try {
        HttpResponseMessage resp = null;

        if (postBuffer is null) {
            resp = cts is null ? await httpClient.GetAsync(url) : await httpClient.GetAsync(url, cts.Token);

        } else {
            using (var httpContent = new StringContent(postBuffer)) {
                resp = cts is null ? await httpClient.PostAsync(url, httpContent) : await httpClient.PostAsync(url, httpContent, cts.Token);
            }
        }

        var respString = await resp.Content.ReadAsStringAsync();
        return (resp.IsSuccessStatusCode, WebExceptionStatus.Success, resp.StatusCode, respString);

    } catch (WebException ex) {
        WebExceptionStatus status = ex.Status;
        if (status == WebExceptionStatus.ProtocolError) {
            // Get HttpWebResponse so that you can check the HTTP status code.
            using (HttpWebResponse httpResponse = (HttpWebResponse)ex.Response) {
                return (false, status, httpResponse.StatusCode, httpResponse.StatusDescription);
            }
        } else {
            return (false, status, null, ex.ToString()); 
        }

    } catch (TaskCanceledException ex) {
        if (cts is object && ex.CancellationToken == cts.Token) {
            // a real cancellation, triggered by the caller
            return (false, WebExceptionStatus.RequestCanceled, null, ex.ToString());
        } else {
            // a web request timeout (possibly other things!?)
            return (false, WebExceptionStatus.Timeout, null, ex.ToString());
        }

    } catch (Exception ex) {
        return (false, WebExceptionStatus.UnknownError, null, ex.ToString());
    }
}

This will do a GET or POST depends if postBuffer is null or not

if Success is true the response will then be in ResponseAsString

if Success is false you can check WebExceptionStatus, HttpStatusCode and ResponseAsString to try to see what went wrong.

Is there a way to reduce the size of the git folder?

One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.

Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).

In this article on git space, AlBlue mentions:

Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.

If you have large binaries stored in your git repo, you may consider:

As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

From my testing Write-Output and [Console]::WriteLine() perform much better than Write-Host.

Depending on how much text you need to write out this may be important.

Below if the result of 5 tests each for Write-Host, Write-Output and [Console]::WriteLine().

In my limited experience, I've found when working with any sort of real world data I need to abandon the cmdlets and go straight for the lower level commands to get any decent performance out of my scripts.

measure-command {$count = 0; while ($count -lt 1000) { Write-Host "hello"; $count++ }}

1312ms
1651ms
1909ms
1685ms
1788ms


measure-command { $count = 0; while ($count -lt 1000) { Write-Output "hello"; $count++ }}

97ms
105ms
94ms
105ms
98ms


measure-command { $count = 0; while ($count -lt 1000) { [console]::WriteLine("hello"); $count++ }}

158ms
105ms
124ms
99ms
95ms

ESLint not working in VS Code?

I'm giving the response assuming that you have already defined rules in you local project root with .eslintrc and .eslintignore. After Installing VSCode Eslint Extension several configurations which need to do in settings.json for vscode

eslint.enable: true
eslint.nodePath: <directory where your extensions available>

Installing eslint local as a project dependency is the last ingredient for this to work. consider not to install eslint as global which could conflict with your local installed package.

Max parallel http connections in a browser?

Firefox stores that number in this setting (you find it in about:config): network.http.max-connections-per-server

For the max connections, Firefox stores that in this setting: network.http.max-connections

Get list of Excel files in a folder using VBA

Sub test()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder1 = FSO.GetFolder(FromPath).Files
    FolderPath_1 = "D:\Arun\Macro Files\UK Marco\External Sales Tool for Au\Example Files\"
    Workbooks.Add
    Set Movenamelist = ActiveWorkbook
    For Each fil In folder1
        Movenamelist.Activate
        Range("A100000").End(xlUp).Offset(1, 0).Value = fil
        ActiveCell.Offset(1, 0).Select
    Next
End Sub

Bootstrap carousel multiple frames at once

Reference to above link i added 1 new thing called show 4 at time, slide one at a time for bootstrap 3 (v3.3.7)

CODEPLY:- https://www.codeply.com/go/eWUbGlspqU

LIVE SNIPPET

_x000D_
_x000D_
(function(){_x000D_
  $('#carousel123').carousel({ interval: 2000 });_x000D_
}());_x000D_
_x000D_
(function(){_x000D_
  $('.carousel-showmanymoveone .item').each(function(){_x000D_
    var itemToClone = $(this);_x000D_
_x000D_
    for (var i=1;i<4;i++) {_x000D_
      itemToClone = itemToClone.next();_x000D_
_x000D_
      // wrap around if at end of item collection_x000D_
      if (!itemToClone.length) {_x000D_
        itemToClone = $(this).siblings(':first');_x000D_
      }_x000D_
_x000D_
      // grab item, clone, add marker class, add to collection_x000D_
      itemToClone.children(':first-child').clone()_x000D_
        .addClass("cloneditem-"+(i))_x000D_
        .appendTo($(this));_x000D_
    }_x000D_
  });_x000D_
}());
_x000D_
body {_x000D_
    margin-top: 50px;_x000D_
}_x000D_
_x000D_
.carousel-showmanymoveone .carousel-control {_x000D_
  width: 4%;_x000D_
  background-image: none;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-control.left {_x000D_
  margin-left: 15px;_x000D_
}_x000D_
.carousel-showmanymoveone .carousel-control.right {_x000D_
  margin-right: 15px;_x000D_
}_x000D_
.carousel-showmanymoveone .cloneditem-1,_x000D_
.carousel-showmanymoveone .cloneditem-2,_x000D_
.carousel-showmanymoveone .cloneditem-3 {_x000D_
  display: none;_x000D_
}_x000D_
@media all and (min-width: 768px) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev {_x000D_
    left: -50%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .next {_x000D_
    left: 50%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .active {_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner .cloneditem-1 {_x000D_
    display: block;_x000D_
  }_x000D_
}_x000D_
@media all and (min-width: 768px) and (transform-3d), all and (min-width: 768px) and (-webkit-transform-3d) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.next {_x000D_
    -webkit-transform: translate3d(50%, 0, 0);_x000D_
            transform: translate3d(50%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev {_x000D_
    -webkit-transform: translate3d(-50%, 0, 0);_x000D_
            transform: translate3d(-50%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active {_x000D_
    -webkit-transform: translate3d(0, 0, 0);_x000D_
            transform: translate3d(0, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
}_x000D_
@media all and (min-width: 992px) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev {_x000D_
    left: -25%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .next {_x000D_
    left: 25%;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .active {_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner .cloneditem-2,_x000D_
  .carousel-showmanymoveone .carousel-inner .cloneditem-3 {_x000D_
    display: block;_x000D_
  }_x000D_
}_x000D_
@media all and (min-width: 992px) and (transform-3d), all and (min-width: 992px) and (-webkit-transform-3d) {_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.next {_x000D_
    -webkit-transform: translate3d(25%, 0, 0);_x000D_
            transform: translate3d(25%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev {_x000D_
    -webkit-transform: translate3d(-25%, 0, 0);_x000D_
            transform: translate3d(-25%, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.left,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.prev.right,_x000D_
  .carousel-showmanymoveone .carousel-inner > .item.active {_x000D_
    -webkit-transform: translate3d(0, 0, 0);_x000D_
            transform: translate3d(0, 0, 0);_x000D_
    left: 0;_x000D_
  }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<div class="carousel carousel-showmanymoveone slide" id="carousel123">_x000D_
 <div class="carousel-inner">_x000D_
  <div class="item active">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/0054A6/fff/&amp;text=1" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002d5a/fff/&amp;text=2" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/d6d6d6/333&amp;text=3" class="img-responsive"></a></div>_x000D_
  </div>          _x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002040/eeeeee&amp;text=4" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/0054A6/fff/&amp;text=5" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/002d5a/fff/&amp;text=6" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/eeeeee&amp;text=7" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
  <div class="item">_x000D_
   <div class="col-xs-12 col-sm-6 col-md-3"><a href="#"><img src="http://placehold.it/500/40a1ff/002040&amp;text=8" class="img-responsive"></a></div>_x000D_
  </div>_x000D_
 </div>_x000D_
 <a class="left carousel-control" href="#carousel123" data-slide="prev"><i class="glyphicon glyphicon-chevron-left"></i></a>_x000D_
 <a class="right carousel-control" href="#carousel123" data-slide="next"><i class="glyphicon glyphicon-chevron-right"></i></a>_x000D_
</div>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
_x000D_
_x000D_
_x000D_

How to round a number to significant figures in Python

import math

  def sig_dig(x, n_sig_dig):
      num_of_digits = len(str(x).replace(".", ""))
      if n_sig_dig >= num_of_digits:
          return x
      n = math.floor(math.log10(x) + 1 - n_sig_dig)
      result = round(10 ** -n * x) * 10 ** n
      return float(str(result)[: n_sig_dig + 1])


    >>> sig_dig(1234243, 3)
    >>> sig_dig(243.3576, 5)

        1230.0
        243.36

Using ListView : How to add a header view?

You simply can't use View as a Header of ListView.

Because the view which is being passed in has to be inflated.

Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.

EDIT:

Look at this tutorial Android ListView and ListActivity - Tutorial .

EDIT 2: This link is broken Android ListActivity with a header or footer

Java Switch Statement - Is "or"/"and" possible?

Observations on an interesting Switch case trap --> fall through of switch

"The break statements are necessary because without them, statements in switch blocks fall through:" Java Doc's example

Snippet of consecutive case without break:

    char c = 'A';/* switch with lower case */;
    switch(c) {
        case 'a':
            System.out.println("a");
        case 'A':
            System.out.println("A");
            break;
    }

O/P for this case is:

A

But if you change value of c, i.e., char c = 'a';, then this get interesting.

O/P for this case is:

a A

Even though the 2nd case test fails, program goes onto print A, due to missing break which causes switch to treat the rest of the code as a block. All statements after the matching case label are executed in sequence.

Setting attribute disabled on a SPAN element does not prevent click events

@click=" canClick ? doClick : void 0"

User click but nothing happen can meet your

I use it in vuejs work fine

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

How To Convert A Number To an ASCII Character?

C# represents a character in UTF-16 coding rather than ASCII. Therefore converting a integer to character do not make any difference for A-Z and a-z. But I was working with ASCII Codes besides alphabets and number which did not work for me as system uses UTF-16 code. Therefore I browsed UTF-16 code for all UTF-16 character. Here is the module :

void utfchars()
{
 int i, a, b, x;
 ConsoleKeyInfo z;
  do
  {
   a = 0; b = 0; Console.Clear();
    for (i = 1; i <= 10000; i++)
    {
     if (b == 20)
     {
      b = 0;
      a = a + 1;
     }
    Console.SetCursorPosition((a * 15) + 1, b + 1);
    Console.Write("{0} == {1}", i, (char)i);
   b = b+1;
   if (i % 100 == 0)
  {
 Console.Write("\n\t\t\tPress any key to continue {0}", b);
 a = 0; b = 0;
 Console.ReadKey(true); Console.Clear();
 }
}
Console.Write("\n\n\n\n\n\n\n\t\t\tPress any key to Repeat and E to exit");
z = Console.ReadKey();
if (z.KeyChar == 'e' || z.KeyChar == 'E') Environment.Exit(0);
} while (1 == 1);
}

C++: Where to initialize variables in constructor

There are many other reasons. You should always initialize all member variables in the initialization list if possible.

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

How to solve static declaration follows non-static declaration in GCC C code?

I have had this issue in a case where the static function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.

tap gesture recognizer - which object was tapped?

Swift 5

In my case I needed access to the UILabel that was clicked, so you could do this inside the gesture recognizer.

let label:UILabel = gesture.view as! UILabel

The gesture.view property contains the view of what was clicked, you can simply downcast it to what you know it is.

@IBAction func tapLabel(gesture: UITapGestureRecognizer) {

        let label:UILabel = gesture.view as! UILabel

        guard let text = label.attributedText?.string else {
            return
        }

        print(text)
}

So you could do something like above for the tapLabel function and in viewDidLoad put...

<Label>.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(tapLabel(gesture:))))

Just replace <Label> with your actual label name

Typescript sleep

With RxJS:

import { timer } from 'rxjs';

// ...

timer(your_delay_in_ms).subscribe(x => { your_action_code_here })

x is 0.

If you give a second argument period to timer, a new number will be emitted each period milliseconds (x = 0 then x = 1, x = 2, ...).

See the official doc for more details.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

remove table row with specific id

ID attributes cannot start with a number and they should be unique. In any case, you can use :eq() to select a specific row using a 0-based integer:

// Remove the third row
$("#test tr:eq(2)").remove();

Alternatively, rewrite your HTML so that it's valid:

<table id="test">
 <tr id=test1><td>bla</td></tr>
 <tr id=test2><td>bla</td></tr>
 <tr id=test3><td>bla</td></tr>
 <tr id=test4><td>bla</td></tr>
</table>

And remove it referencing just the id:

$("#test3").remove();

Create a folder and sub folder in Excel VBA

I found a much better way of doing the same, less code, much more efficient. Note that the """" is to quote the path in case it contains blanks in a folder name. Command line mkdir creates any intermediary folder if necessary to make the whole path exist.

If Dir(YourPath, vbDirectory) = "" Then
    Shell ("cmd /c mkdir """ & YourPath & """")
End If

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Your selector is a little off, it's missing the trailing ]

var mySelect = $('select[name=' + name + ']')

you may also need to put quotes around the name, like so:

var mySelect = $('select[name="' + name + '"]')

Remove border radius from Select tag in bootstrap 3

You can use -webkit-border-radius: 0;. Like this:-

-webkit-border-radius: 0;
border: 0;
outline: 1px solid grey;
outline-offset: -1px;

This will give square corners as well as dropdown arrows. Using -webkit-appearance: none; is not recommended as it will turn off all the styling done by Chrome.

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

What are "res" and "req" parameters in Express functions?

I noticed one error in Dave Ward's answer (perhaps a recent change?): The query string paramaters are in request.query, not request.params. (See https://stackoverflow.com/a/6913287/166530 )

request.params by default is filled with the value of any "component matches" in routes, i.e.

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

and, if you have configured express to use its bodyparser (app.use(express.bodyParser());) also with POST'ed formdata. (See How to retrieve POST query parameters? )

How to clear mysql screen console in windows?

just type \system cls

took me a couple hours to get it jejej

How to change the interval time on bootstrap carousel?

       <div class="carousel-inner text-right">
                  <div class="carousel-item active text-center" id="first"  data-interval="1000" >
                    <img src="images/slide-1.gif" alt="slide-1">
                  </div>
                  <div class="carousel-item  text-center" id="second"  data-interval="2000" >
                    <img src="images/slide-2.gif" alt="slide-2">
                  </div>
                  <div class="carousel-item  text-center" id="third"  data-interval="3000" >
                    <img src="images/slide-3.gif" alt="slide-3">
                  </div>
                  <div class="carousel-item text-center" id="four"  data-interval="5000" >
                    <img src="images/slide-4.gif" alt="slide-4">
                  </div>
                </div>

You can also change different slides.

How to use '-prune' option of 'find' in sh?

There are quite a few answers; some of them are a bit too much theory-heavy. I'll leave why I needed prune once so maybe the need-first/example kind of explanation is useful to someone :)

Problem

I had a folder with about 20 node directories, each having its node_modules directory as expected.

Once you get into any project, you see each ../node_modules/module. But you know how it is. Almost every module has dependencies, so what you are looking at is more like projectN/node_modules/moduleX/node_modules/moduleZ...

I didn't want to drown with a list with the dependency of the dependency of...

Knowing -d n / -depth n, it wouldn't have helped me, as the main/first node_modules directory I wanted of each project was at a different depth, like this:

Projects/MysuperProjectName/project/node_modules/...
Projects/Whatshisname/version3/project/node_modules/...
Projects/project/node_modules/...
Projects/MysuperProjectName/testProject/november2015Copy/project/node_modules/...
[...]

How can I get the first a list of paths ending at the first node_modules and move to the next project to get the same?

Enter -prune

When you add -prune, you'll still have a standard recursive search. Each "path" is analyzed, and every find gets spit out and find keeps digging down like a good chap. But it's the digging down for more node_modules what I didn't want.

So, the difference is that in any of those different paths, -prune will find to stop digging further down that particular avenue when it has found your item. In my case, the node_modules folder.

Using File.listFiles with FileNameExtensionFilter

Is there a specific reason you want to use FileNameExtensionFilter? I know this works..

private File[] getNewTextFiles() {
    return dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");
        }
    });
}

(Deep) copying an array using jQuery

I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.

http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/

Minimum and maximum value of z-index?

Z-Index only works for elements that have position: relative; or position: absolute; applied to them. If that's not the problem we'll need to see an example page to be more helpful.

EDIT: The good doctor has already put the fullest explanation but the quick version is that the minimum is 0 because it can't be a negative number and the maximum - well, you'll never really need to go above 10 for most designs.

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

Creating a UIImage from a UIColor to use as a background image for UIButton

I created a category around UIButton to be able to set the background color of the button and set the state. You might find this useful.

@implementation  UIButton (ButtonMagic)

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}

+ (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

This will be part of a set of helper categories I'm open sourcing this month.

Swift 2.2

extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return img
  }
}

Swift 3.0

extension UIImage {
    static func from(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
}

Use as

let img = UIImage.from(color: .black)

How can I output leading zeros in Ruby?

Can't you just use string formatting of the value before you concat the filename?

"%03d" % number

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Open modal windows with passing data to dialog

In case if someone interests to pass data to dialog:

app.controller('ModalCtrl', function($scope,  $modal) {
      
      $scope.name = 'theNameHasBeenPassed';

      $scope.showModal = function() {
        
        $scope.opts = {
        backdrop: true,
        backdropClick: true,
        dialogFade: false,
        keyboard: true,
        templateUrl : 'modalContent.html',
        controller : ModalInstanceCtrl,
        resolve: {} // empty storage
          };
          
        
        $scope.opts.resolve.item = function() {
            return angular.copy(
                                {name: $scope.name}
                          ); // pass name to resolve storage
        }
        
          var modalInstance = $modal.open($scope.opts);
          
          modalInstance.result.then(function(){
            //on ok button press 
          },function(){
            //on cancel button press
            console.log("Modal Closed");
          });
      };                   
})

var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
    
     $scope.item = item;
    
      $scope.ok = function () {
        $modalInstance.close();
      };
      
      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };
}

Demo Plunker

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

Adding maven nexus repo to my pom.xml

From Maven - Settings Reference

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>
  </servers>
  ...
</settings>

id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.

username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.

privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.

filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.

Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.

All you should need is the id, username and password

The id and URL should be defined in your pom.xml like this:

<repositories>
    ...
    <repository>
        <id>acme-nexus-releases</id>
        <name>acme nexus</name>
        <url>https://nexus.acme.net/content/repositories/releases</url>
    </repository>
    ...
</repositories>

If you need a username and password to your server, you should encrypt it. Maven Password Encryption

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

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

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

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

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

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

EDIT

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

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

e.g.

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

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

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

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

Laravel Password & Password_Confirmation Validation

You can use like this for check password contain at-least 1 Uppercase, 1 Lowercase, 1 Numeric and 1 special character :

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'password' => 'required|confirmed|min:6|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/']);

Set the table column width constant regardless of the amount of text in its cells?

What I do is:

  1. Set the td width:

    <td width="200" height="50"><!--blaBlaBla Contents here--></td>
    
  2. Set the td width with CSS:

    <td style="width:200px; height:50px;">
    
  3. Set the width again as max and min with CSS:

    <td style="max-width:200px; min-width:200px; max-height:50px; min-height:50px; width:200px; height:50px;">
    

It sounds little bit repetitive but it gives me the desired result. To achieve this with much ease, you may need put the CSS values in a class in your style-sheet:

.td_size {    
  width:200px; 
  height:50px;
  max-width:200px;
  min-width:200px; 
  max-height:50px; 
  min-height:50px;
  **overflow:hidden;** /*(Optional)This might be useful for some overflow contents*/   
}

then:

<td class="td_size">

Place the class attribute to any <td> you want.

Naming convention - underscore in C++ and C# variables

A naming convention like this is useful when you are reading code, particularly code that is not your own. A strong naming convention helps indicate where a particular member is defined, what kind of member it is, etc. Most development teams adopt a simple naming convention, and simply prefix member fields with an underscore (_fieldName). In the past, I have used the following naming convention for C# (which is based on Microsofts conventions for the .NET framework code, which can be seen with Reflector):

Instance Field: m_fieldName
Static Field: s_fieldName
Public/Protected/Internal Member: PascalCasedName()
Private Member: camelCasedName()

This helps people understand the structure, use, accessibility and location of members when reading unfamiliar code very rapidly.

Windows recursive grep command-line

findstr /spin /c:"string" [files]

The parameters have the following meanings:

  • s = recursive
  • p = skip non-printable characters
  • i = case insensitive
  • n = print line numbers

And the string to search for is the bit you put in quotes after /c:

How to represent multiple conditions in a shell if statement?

Using /bin/bash the following will work:

if [ "$option" = "Y" ] || [ "$option" = "y" ]; then
    echo "Entered $option"
fi

If using maven, usually you put log4j.properties under java or resources?

src/main/resources is the "standard placement" for this.

Update: The above answers the question, but its not the best solution. Check out the other answers and the comments on this ... you would probably not shipping your own logging properties with the jar but instead leave it to the client (for example app-server, stage environment, etc) to configure the desired logging. Thus, putting it in src/test/resources is my preferred solution.

Note: Speaking of leaving the concrete log config to the client/user, you should consider replacing log4j with slf4j in your app.

How do I declare a 2d array in C++ using new?

Here, I have two options. The first one shows the concept of an array of arrays or pointer of pointers. I prefer the second one because the addresses are contiguous, as you can see in the image.

enter image description here

#include <iostream>

using namespace std;


int main(){

    int **arr_01,**arr_02,i,j,rows=4,cols=5;

    //Implementation 1
    arr_01=new int*[rows];

    for(int i=0;i<rows;i++)
        arr_01[i]=new int[cols];

    for(i=0;i<rows;i++){
        for(j=0;j<cols;j++)
            cout << arr_01[i]+j << " " ;
        cout << endl;
    }


    for(int i=0;i<rows;i++)
        delete[] arr_01[i];
    delete[] arr_01;


    cout << endl;
    //Implementation 2
    arr_02=new int*[rows];
    arr_02[0]=new int[rows*cols];
    for(int i=1;i<rows;i++)
        arr_02[i]=arr_02[0]+cols*i;

    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++)
            cout << arr_02[i]+j << " " ;
        cout << endl;
    }

    delete[] arr_02[0];
    delete[] arr_02;


    return 0;
}

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

Formatting Decimal places in R

Something like that :

options(digits=2)

Definition of digits option :

digits: controls the number of digits to print when printing numeric values.

How to make IPython notebook matplotlib plot inline

I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:

%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt

You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

How can I measure the actual memory usage of an application or process?

#!/bin/ksh
#
# Returns total memory used by process $1 in kb.
#
# See /proc/NNNN/smaps if you want to do something
# more interesting.
#

IFS=$'\n'

for line in $(</proc/$1/smaps)
do
   [[ $line =~ ^Size:\s+(\S+) ]] && ((kb += ${.sh.match[1]}))
done

print $kb

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

Multiple "order by" in LINQ

There is at least one more way to do this using LINQ, although not the easiest. You can do it by using the OrberBy() method that uses an IComparer. First you need to implement an IComparer for the Movie class like this:

public class MovieComparer : IComparer<Movie>
{
    public int Compare(Movie x, Movie y)
    {
        if (x.CategoryId == y.CategoryId)
        {
            return x.Name.CompareTo(y.Name);
        }
        else
        {
            return x.CategoryId.CompareTo(y.CategoryId);
        }
    }
}

Then you can order the movies with the following syntax:

var movies = _db.Movies.OrderBy(item => item, new MovieComparer());

If you need to switch the ordering to descending for one of the items just switch the x and y inside the Compare() method of the MovieComparer accordingly.

Difference between text and varchar (character varying)

A good explanation from http://www.sqlines.com/postgresql/datatypes/text:

The only difference between TEXT and VARCHAR(n) is that you can limit the maximum length of a VARCHAR column, for example, VARCHAR(255) does not allow inserting a string more than 255 characters long.

Both TEXT and VARCHAR have the upper limit at 1 Gb, and there is no performance difference among them (according to the PostgreSQL documentation).

Mark error in form using Bootstrap

One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.

<span class="error text-danger">Some Errors related to something</span>

Output looks like something below:

Example of error text in modal

How to present UIActionSheet iOS Swift?

Code for adding alerts to actionsheet in swift4

   *That means when we click actionsheet values(like edit/ delete..so on) it shows 
   an alert option that is set with Yes or No option*


   class ViewController: UIViewController
   {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func action_sheet1(_ sender: Any) {




    let action_sheet1 = UIAlertController(title: "Hi Bro", message: "Please Select an Option: ", preferredStyle: .actionSheet)

    action_sheet1.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Approve button")



        let alert = UIAlertController(title: "Approve", message: "Would you like to approve the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))




    action_sheet1.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (alert: UIAlertAction!) -> Void in
        print("User click Edit button")

        let alert = UIAlertController(title: "Edit", message: "Would you like to edit the file ", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))




    action_sheet1.addAction(UIAlertAction(title: "Delete", style: .destructive , handler: { (alert: UIAlertAction!) -> Void in
        print("User click Delete button")



        let alert = UIAlertController(title: "Delete", message: "Would you like to delete the file permenently?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))





    action_sheet1.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:{ (alert: UIAlertAction!) -> Void in
         print("User click cancel button")


        let alert = UIAlertController(title: "Cancel", message: "Would you like to cancel?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)

        }))



        self.present(action_sheet1, animated: true, completion: {
        print("completion block")
    })
}


}

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

Does C# support multiple inheritance?

Multiple inheritance is not supported in C#.

But if you want to "inherit" behavior from two sources why not use the combination of:

  • Composition
  • Dependency Injection

There is a basic but important OOP principle that says: "Favor composition over inheritance".

You can create a class like this:

public class MySuperClass
{
    private IDependencyClass1 mDependency1;
    private IDependencyClass2 mDependency2;

    public MySuperClass(IDependencyClass1 dep1, IDependencyClass2 dep2)
    {
        mDependency1 = dep1;
        mDependency2 = dep2;
    }

    private void MySuperMethodThatDoesSomethingComplex()
    {
        string s = mDependency1.GetMessage();
        mDependency2.PrintMessage(s);
    }
}

As you can see the dependecies (actual implementations of the interfaces) are injected via the constructor. You class does not know how each class is implemented but it knows how to use them. Hence, a loose coupling between the classes involved here but the same power of usage.

Today's trends show that inheritance is kind of "out of fashion".

Jenkins Host key verification failed

Jenkins is a service account, it doesn't have a shell by design. It is generally accepted that service accounts. shouldn't be able to log in interactively.

To resolve "Jenkins Host key verification failed", do the following steps. I have used mercurial with jenkins.

1)Execute following commands on terminal

             $ sudo su -s /bin/bash jenkins

provide password

2)Generate public private key using the following command:

              ssh-keygen

you can see output as ::

Generating public/private rsa key pair. 
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 

3)Press Enter --> Do not give any passphrase--> press enter

             Key has been generated

4) go to --> cat /var/lib/jenkins/.ssh/id_rsa.pub

5) Copy key from id_rsa.pub

6)Exit from bash

7) ssh@yourrepository

8) vi .ssh/authorized_keys

9) Paste the key

10) exit

11)Manually login to mercurial server

Note: Pls do manually login otherwise jenkins will again give error "host verification failed"

12)once manually done, Now go to Jenkins and give build

Enjoy!!!

Good Luck

SQL sum with condition

Try moving ValueDate:

select sum(CASE  
             WHEN ValueDate > @startMonthDate THEN cash 
              ELSE 0 
           END) 
 from Table a
where a.branch = p.branch 
  and a.transID = p.transID

(reformatted for clarity)

You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

Tell Ruby Program to Wait some amount of time

Use sleep like so:

sleep 2

That'll sleep for 2 seconds.

Be careful to give an argument. If you just run sleep, the process will sleep forever. (This is useful when you want a thread to sleep until it's woken.)

c# foreach (property in object)... Is there a simple way of doing this?

Give this a try:

foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
   // do stuff here
}

Also please note that Type.GetProperties() has an overload which accepts a set of binding flags so you can filter out properties on a different criteria like accessibility level, see MSDN for more details: Type.GetProperties Method (BindingFlags) Last but not least don't forget to add the "system.Reflection" assembly reference.

For instance to resolve all public properties:

foreach (var propertyInfo in obj.GetType()
                                .GetProperties(
                                        BindingFlags.Public 
                                        | BindingFlags.Instance))
{
   // do stuff here
}

Please let me know whether this works as expected.

Should I use int or Int32

ECMA-334:2006 C# Language Specification (p18):

Each of the predefined types is shorthand for a system-provided type. For example, the keyword int refers to the struct System.Int32. As a matter of style, use of the keyword is favoured over use of the complete system type name.

Powershell script to locate specific file/file name?

I use this form for just this sort of thing:

gci . hosts -r | ? {!$_.PSIsContainer}

. maps to positional parameter Path and "hosts" maps to positional parameter Filter. I highly recommend using Filter over Include if the provider supports filtering (and the filesystem provider does). It is a good bit faster than Include.

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

If list index exists, do X

Could it be more useful for you to use the length of the list len(n) to inform your decision rather than checking n[i] for each possible length?

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

Gunicorn worker timeout error

If you are using GCP then you have to set workers per instance type.

Link to GCP best practices https://cloud.google.com/appengine/docs/standard/python3/runtime

Java Scanner class reading strings

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();

names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

or just read the line and parse the value as an Integer.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());

names = new String[nnames];
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

How to extract URL parameters from a URL with Ruby or Rails?

Just Improved with Levi answer above -

Rack::Utils.parse_query URI("http://example.com?par=hello&par2=bye").query

For a string like above url, it will return

{ "par" => "hello", "par2" => "bye" } 

Using Enum values as String literals

You can simply use:

""+ Modes.mode1

How to get the list of all printers in computer

Look at the static System.Drawing.Printing.PrinterSettings.InstalledPrinters property.

It is a list of the names of all installed printers on the system.

Node.js Best Practice Exception Handling

nodejs domains is the most up to date way of handling errors in nodejs. Domains can capture both error/other events as well as traditionally thrown objects. Domains also provide functionality for handling callbacks with an error passed as the first argument via the intercept method.

As with normal try/catch-style error handling, is is usually best to throw errors when they occur, and block out areas where you want to isolate errors from affecting the rest of the code. The way to "block out" these areas are to call domain.run with a function as a block of isolated code.

In synchronous code, the above is enough - when an error happens you either let it be thrown through, or you catch it and handle there, reverting any data you need to revert.

try {  
  //something
} catch(e) {
  // handle data reversion
  // probably log too
}

When the error happens in an asynchronous callback, you either need to be able to fully handle the rollback of data (shared state, external data like databases, etc). OR you have to set something to indicate that an exception has happened - where ever you care about that flag, you have to wait for the callback to complete.

var err = null;
var d = require('domain').create();
d.on('error', function(e) {
  err = e;
  // any additional error handling
}
d.run(function() { Fiber(function() {
  // do stuff
  var future = somethingAsynchronous();
  // more stuff

  future.wait(); // here we care about the error
  if(err != null) {
    // handle data reversion
    // probably log too
  }

})});

Some of that above code is ugly, but you can create patterns for yourself to make it prettier, eg:

var specialDomain = specialDomain(function() {
  // do stuff
  var future = somethingAsynchronous();
  // more stuff

  future.wait(); // here we care about the error
  if(specialDomain.error()) {
    // handle data reversion
    // probably log too
  } 
}, function() { // "catch"
  // any additional error handling
});

UPDATE (2013-09):

Above, I use a future that implies fibers semantics, which allow you to wait on futures in-line. This actually allows you to use traditional try-catch blocks for everything - which I find to be the best way to go. However, you can't always do this (ie in the browser)...

There are also futures that don't require fibers semantics (which then work with normal, browsery JavaScript). These can be called futures, promises, or deferreds (I'll just refer to futures from here on). Plain-old-JavaScript futures libraries allow errors to be propagated between futures. Only some of these libraries allow any thrown future to be correctly handled, so beware.

An example:

returnsAFuture().then(function() {
  console.log('1')
  return doSomething() // also returns a future

}).then(function() {
  console.log('2')
  throw Error("oops an error was thrown")

}).then(function() {
  console.log('3')

}).catch(function(exception) {
  console.log('handler')
  // handle the exception
}).done()

This mimics a normal try-catch, even though the pieces are asynchronous. It would print:

1
2
handler

Note that it doesn't print '3' because an exception was thrown that interrupts that flow.

Take a look at bluebird promises:

Note that I haven't found many other libraries other than these that properly handle thrown exceptions. jQuery's deferred, for example, don't - the "fail" handler would never get the exception thrown an a 'then' handler, which in my opinion is a deal breaker.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Spring Data JPA - "No Property Found for Type" Exception

this error happens if you try access un-exists property

my guess is that sorting is done by spring by property name and not by real column name. and the error indicates that, in "UserBoard" there is no property named "boardId".

bests,

Oak

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

Enumerations on PHP

What about class constants?

<?php

class YourClass
{
    const SOME_CONSTANT = 1;

    public function echoConstant()
    {
        echo self::SOME_CONSTANT;
    }
}

echo YourClass::SOME_CONSTANT;

$c = new YourClass;
$c->echoConstant();

Bootstrap Carousel : Remove auto slide

Please try the following:

<script>
    $(document).ready(function() {      
        $('.carousel').carousel('pause');
    });
</script>

How to run batch file from network share without "UNC path are not supported" message?

My situation is just a little different. I'm running a batch file on startup to distribute the latest version of internal business applications.

In this situation I'm using the Windows Registry Run Key with the following string

cmd /c copy \\serverName\SharedFolder\startup7.bat %USERPROFILE% & %USERPROFILE%\startup7.bat

This runs two commands on startup in the correct sequence. First copying the batch file locally to a directory the user has permission to. Then executing the same batch file. I can create a local directory c:\InternalApps and copy all of the files from the network.

This is probably too late to solve the original poster's question but it may help someone else.

What is IllegalStateException?

Usually, IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.

The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException to standard output.

We can't tell what's wrong just from that exception - and better code would have used the original SQLException as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.

Resize to fit image in div, and center horizontally and vertically

NOT SUPPORTED BY IE

More info here: Can I Use?

_x000D_
_x000D_
.container {_x000D_
  overflow: hidden;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
.container img {_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  min-height: 100%;_x000D_
}
_x000D_
<div class='container'>_x000D_
    <img src='http://i.imgur.com/H9lpVkZ.jpg' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

Get list of all input objects using JavaScript, without accessing a form object

querySelectorAll returns a NodeList which has its own forEach method:

document.querySelectorAll('input').forEach( input => {
  // ...
});

getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

Array.from(document.getElementsByTagName('input')).forEach( input => {
  // ...
});

How to use count and group by at the same select statement

This will do what you want (list of towns, with the number of users in each):

select town, count(town) 
from user
group by town

You can use most aggregate functions when using GROUP BY.

Update (following change to question and comments)

You can declare a variable for the number of users and set it to the number of users then select with that.

DECLARE @numOfUsers INT
SET @numOfUsers = SELECT COUNT(*) FROM user

SELECT DISTINCT town, @numOfUsers
FROM user

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

File inside jar is not visible for spring

I was having an issue recursively loading resources in my Spring app, and found that the issue was I should be using resource.getInputStream. Here's an example showing how to recursively read in all files in config/myfiles that are json files.

Example.java

private String myFilesResourceUrl = "config/myfiles/**/";
private String myFilesResourceExtension = "json";

ResourceLoader rl = new ResourceLoader();

// Recursively get resources that match. 
// Big note: If you decide to iterate over these, 
// use resource.GetResourceAsStream to load the contents
// or use the `readFileResource` of the ResourceLoader class.
Resource[] resources = rl.getResourcesInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

// Recursively get resource and their contents that match. 
// This loads all the files into memory, so maybe use the same approach 
// as this method, if need be.
Map<Resource,String> contents = rl.getResourceContentsInResourceFolder(myFilesResourceUrl, myFilesResourceExtension);

ResourceLoader.java

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StreamUtils;

public class ResourceLoader {
  public Resource[] getResourcesInResourceFolder(String folder, String extension) {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
      String resourceUrl = folder + "/*." + extension;
      Resource[] resources = resolver.getResources(resourceUrl);
      return resources;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public String readResource(Resource resource) throws IOException {
    try (InputStream stream = resource.getInputStream()) {
      return StreamUtils.copyToString(stream, Charset.defaultCharset());
    }
  }

  public Map<Resource, String> getResourceContentsInResourceFolder(
      String folder, String extension) {
    Resource[] resources = getResourcesInResourceFolder(folder, extension);

    HashMap<Resource, String> result = new HashMap<>();
    for (var resource : resources) {
      try {
        String contents = readResource(resource);
        result.put(resource, contents);
      } catch (IOException e) {
        throw new RuntimeException("Could not load resource=" + resource + ", e=" + e);
      }
    }
    return result;
  }
}

Default background color of SVG root element

Another workaround might be to use <div> of the same size to wrap the <svg>. After that, you will be able to apply "background-color", and "background-image" that will affect thesvg.

<div class="background">
  <svg></svg>
</div>

<style type="text/css">
.background{
  background-color: black; 
  /*background-image: */
}
</style>

error while loading shared libraries: libncurses.so.5:

If you are absolutely sure that libncurses, aka ncurses, is installed, as in you've done a successful 'ls' of the library, then perhaps you are running a 64 bit Linux operating system and only have the 64 bit libncurses installed, when the program that is running (adb) is 32 bit.

If so, a 32 bit program can't link to a 64 bit library (and won't located it anyway), so you might have to install libcurses, or ncurses (32 bit version). Likewise, if you are running a 64 bit adb, perhaps your ncurses is 32 bit (a possible but less likely scenario).

What is the difference between jQuery: text() and html() ?

Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,

Where to use:

  • use .html() to operate on containers having html elements.
  • use .text() to modify text of elements usually having separate open and closing tags

Where not to use:

  • .text() method cannot be used on form inputs or scripts.

    • .val() for input or textarea elements.
    • .html() for value of a script element.
  • Picking up html content from .text() will convert the html tags into html entities.

Difference:

  • .text() can be used in both XML and HTML documents.
  • .html() is only for html documents.

Check this example on jsfiddle to see the differences in action

Example

Unable to connect to any of the specified mysql hosts. C# MySQL

using System;
using System.Linq;
using MySql.Data.MySqlClient;

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

            // add here your connection details
            String connectionString = "Server=localhost;Database=database;Uid=username;Pwd=password;";
            try
            {
                MySqlConnection connection = new MySqlConnection(connectionString);
                connection.Open();

                Console.WriteLine("MySQL version: " + connection.ServerVersion);
                connection.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.ReadKey();
        }
    }
}

make sure your database server is running if its not running then its not able to make connection and bydefault mysql running on 3306 so don't need mention port if same in case of port number is different then we need to mention port

Bash script plugin for Eclipse?

I will reproduce a good tutorial here, because I lost this article and take some time to find it again!

Adding syntax highlighting for new languages to Eclipse with the Colorer library

Say you have an HRC file containing the syntax and lexical structure of some programming language Eclipse does not support (for example D / Iptables or any other script language).

Using the EclipseColorer plugin, you can easily add support for it.

Go to Help -> Install New Software and click Add.. In the Name field write Colorer and in the Location field write http://colorer.sf.net/eclipsecolorer/

Select the entry you’ve just added in the work with: combo box, wait for the component list to populate and click Select All

Click Next and follow the instructions

Once the plugin is installed, close Eclipse.

Copy your HRC file to [EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\types

[EclipseFolder] = /home/myusername/.eclipse

Use your favorite text editor to open

[EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\empty.hrc

Add the appropriate prototype element. For example, if your HRC file is d.hrc, empty.hrc will look like this:

<?xml version="1.0" encoding='Windows-1251'?>
 <!DOCTYPE hrc PUBLIC
 "-//Cail Lomecb//DTD Colorer HRC take5//EN"
 "http://colorer.sf.net/2003/hrc.dtd"
 >
 <hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd"
 ><annotation><documentation>
 'auto' is a place for include
 to colorer your own HRCs
</documentation></annotation>
    <prototype name="d" group="main" description="D">
         <location link="types/d.hrc"/>
        <filename>/\.(d)$/i</filename>
 </prototype>
</hrc>

Save the changes and close the text editor

Open Eclipse and go to Window -> Preferences -> General -> Editors -> File Associations

In the file types section, click Add.. and fill in the appropriate filetype (for example .d)

Click OK and click your newly added entry in the list

In the associated editors section, click Add.., select Colorer Editor and press OK

ok, the hard part is you must learn about HCR syntax.

You can look in

[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar

to learn how do it and explore many other hcr's files. At this moment I didn't find any documentation.

My gift is a basic and incomplete iptables syntax highlight. If you improve please share with me.

<?xml version="1.0" encoding="Windows-1251"?>
<!DOCTYPE hrc PUBLIC "-//Cail Lomecb//DTD Colorer HRC take5//EN" "http://colorer.sf.net/2003/hrc.dtd">
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd">
    <type name="iptables">
        <annotation>
            <develby> Mario Moura - moura.mario  gmail.com</develby>
            <documentation>Support iptables EQL language</documentation>
            <appinfo>
                  <prototype name="iptables" group="database" description="iptables">
                       <location link="iptables.hrc"/>
                       <filename>/\.epl$/i</filename>
                  </prototype>  
            </appinfo>
        </annotation>

        <region name="iptablesTable" parent="def:Keyword"/>
        <region name="iptablesChainFilter" parent="def:Symbol"/>
        <region name="iptablesChainNatMangle" parent="def:NumberDec"/>
        <region name="iptablesCustomDefaultChains" parent="def:Keyword"/>
        <region name="iptablesOptions" parent="def:String"/>
        <region name="iptablesParameters" parent="def:Operator"/>
        <region name="iptablesOtherOptions" parent="def:Comment"/>
        <region name="iptablesMatchExtensions" parent="def:ParameterStrong"/>
        <region name="iptablesTargetExtensions" parent="def:FunctionKeyword"/>
        <region name="pyComment" parent="def:Comment"/>
          <region name="pyOperator" parent="def:Operator"/>
          <region name="pyDelimiter" parent="def:Symbol"/>


        <scheme name="iptablesTable">
            <keywords ignorecase="no" region="iptablesTable">
                <word name="mangle"/>
                <word name="filter"/>
                <word name="nat"/>
                <word name="as"/>
                <word name="at"/>
                <word name="asc"/>
                <word name="avedev"/>
                <word name="avg"/>
                <word name="between"/>
                <word name="by"/>
            </keywords>
        </scheme>

        <scheme name="iptablesChainFilter">
            <keywords ignorecase="no" region="iptablesChainFilter">
                <word name="FORWARD"/>
                <word name="INPUT"/>
                <word name="OUTPUT"/>
            </keywords>
        </scheme>

        <scheme name="iptablesChainNatMangle">
            <keywords ignorecase="no" region="iptablesChainNatMangle">
                <word name="PREROUTING"/>
                <word name="POSTROUTING"/>
                <word name="OUTPUT"/>
            </keywords>
        </scheme>

        <scheme name="iptablesCustomDefaultChains">
            <keywords ignorecase="no" region="iptablesCustomDefaultChains">
                <word name="CHTTP"/>
                <word name="CHTTPS"/>
                <word name="CSSH"/>
                <word name="CDNS"/>
                <word name="CFTP"/>
                <word name="CGERAL"/>
                <word name="CICMP"/>
            </keywords>
        </scheme>


        <scheme name="iptablesOptions">
            <keywords ignorecase="no" region="iptablesOptions">
                <word name="-A"/>
                <word name="--append"/>
                <word name="-D"/>
                <word name="--delete"/>
                <word name="-I"/>
                <word name="--insert"/>
                <word name="-R"/>
                <word name="--replace"/>
                <word name="-L"/>
                <word name="--list"/>
                <word name="-F"/>
                <word name="--flush"/>
                <word name="-Z"/>
                <word name="--zero"/>
                <word name="-N"/>
                <word name="--new-chain"/>
                <word name="-X"/>
                <word name="--delete-chain"/>
                <word name="-P"/>
                <word name="--policy"/>
                <word name="-E"/>
                <word name="--rename-chain"/>
            </keywords>
        </scheme>

        <scheme name="iptablesParameters">
            <keywords ignorecase="no" region="iptablesParameters">
                <word name="-p"/>
                <word name="--protocol"/>
                <word name="-s"/>
                <word name="--source"/>
                <word name="-d"/>
                <word name="--destination"/>
                <word name="-j"/>
                <word name="--jump"/>
                <word name="-g"/>
                <word name="--goto"/>
                <word name="-i"/>
                <word name="--in-interface"/>
                <word name="-o"/>
                <word name="--out-interface"/>
                <word name="-f"/>
                <word name="--fragment"/>
                <word name="-c"/>
                <word name="--set-counters"/>
            </keywords>
        </scheme>

        <scheme name="iptablesOtherOptions">
            <keywords ignorecase="no" region="iptablesOtherOptions">
                <word name="-v"/>
                <word name="--verbose"/>
                <word name="-n"/>
                <word name="--numeric"/>
                <word name="-x"/>
                <word name="--exact"/>

                <word name="--line-numbers"/>
                <word name="--modprobe"/>
            </keywords>
        </scheme>

        <scheme name="iptablesMatchExtensions">
            <keywords ignorecase="no" region="iptablesMatchExtensions">
                <word name="account"/>
                <word name="addrtype"/>
                <word name="childlevel"/>
                <word name="comment"/>
                <word name="connbytes"/>
                <word name="connlimit"/>
                <word name="connmark"/>
                <word name="connrate"/>
                <word name="conntrack"/>
                <word name="dccp"/>
                <word name="dscp"/>
                <word name="dstlimit"/>
                <word name="ecn"/>
                <word name="esp"/>
                <word name="hashlimit"/>
                <word name="helper"/>
                <word name="icmp"/>
                <word name="ipv4options"/>
                <word name="length"/>
                <word name="limit"/>
                <word name="mac"/>
                <word name="mark"/>
                <word name="mport"/>
                <word name="multiport"/>
                <word name="nth"/>
                <word name="osf"/>
                <word name="owner"/>
                <word name="physdev"/>
                <word name="pkttype"/>
                <word name="policy"/>
                <word name="psd"/>
                <word name="quota"/>
                <word name="realm"/>
                <word name="recent"/>
                <word name="sctp"/>
                <word name="set"/>
                <word name="state"/>
                <word name="string"/>
                <word name="tcp"/>
                <word name="tcpmss"/>
                <word name="tos"/>
                <word name="u32"/>
                <word name="udp"/>                                                                              
            </keywords>
        </scheme>


    <scheme name="iptablesTargetExtensions">
            <keywords ignorecase="no" region="iptablesTargetExtensions">
                <word name="BALANCE"/>
                <word name="CLASSIFY"/>
                <word name="CLUSTERIP"/>
                <word name="CONNMARK"/>
                <word name="DNAT"/>
                <word name="DSCP"/>
                <word name="ECN"/>
                <word name="IPMARK"/>
                <word name="IPV4OPTSSTRIP"/>
                <word name="LOG"/>
                <word name="MARK"/>
                <word name="MASQUERADE"/>
                <word name="MIRROR"/>
                <word name="NETMAP"/>
                <word name="NFQUEUE"/>
                <word name="NOTRACK"/>
                <word name="REDIRECT"/>
                <word name="REJECT"/>
                <word name="SAME"/>
                <word name="SET"/>
                <word name="SNAT"/>
                <word name="TARPIT"/>
                <word name="TCPMSS"/>
                <word name="TOS"/>
                <word name="TRACE"/>
                <word name="TTL"/>
                <word name="ULOG"/>
                <word name="XOR"/>                                                                          
            </keywords>
        </scheme>



        <scheme name="iptables">
              <inherit scheme="iptablesTable"/>
              <inherit scheme="iptablesChainFilter"/>
              <inherit scheme="iptablesChainNatMangle"/>
              <inherit scheme="iptablesCustomDefaultChains"/>                                     
              <inherit scheme="iptablesOptions"/>
              <inherit scheme="iptablesParameters"/>
              <inherit scheme="iptablesOtherOptions"/>
              <inherit scheme="iptablesMatchExtensions"/>
              <inherit scheme="iptablesTargetExtensions"/>

   <!-- python operators : http://docs.python.org/ref/keywords.html -->
   <keywords region="pyOperator">
    <symb name="+"/>
    <symb name="-"/>
    <symb name="*"/>
    <symb name="**"/>
    <symb name="/"/>
    <symb name="//"/>
    <symb name="%"/>
    <symb name="&lt;&lt;"/>
    <symb name=">>"/>
    <symb name="&amp;"/>
    <symb name="|"/>
    <symb name="^"/>
    <symb name="~"/>
    <symb name="&lt;"/>
    <symb name=">"/>
    <symb name="&lt;="/>
    <symb name=">="/>
    <symb name="=="/>
    <symb name="!="/>
    <symb name="&lt;>"/>
   </keywords>


   <!-- basic python comment - consider it everything after # till the end of line -->
   <block start="/#/" end="/$/" region="pyComment" scheme="def:Comment"/>

   <block start="/(u|U)?(r|R)?(&quot;{3}|&apos;{3})/" end="/\y3/"
      region00="def:PairStart" region10="def:PairEnd"
      scheme="def:Comment" region="pyComment" />
      <!-- TODO: better scheme for multiline comments/docstrings -->
      <!-- scheme="StringCommon" region="pyString" /> -->


   <!-- python delimiters : http://docs.python.org/ref/delimiters.html -->
   <keywords region="pyDelimiter">
    <symb name="+"/>
    <symb name="("/>
    <symb name=")"/>
    <symb name="["/>
    <symb name="]"/>
    <symb name="{"/>
    <symb name="}"/>
    <symb name="@"/>
    <symb name=","/>
    <symb name=":"/>
    <symb name="."/>
    <symb name="`"/>
    <symb name="="/>
    <symb name=";"/>
    <symb name="+="/>
    <symb name="-="/>
    <symb name="*="/>
    <symb name="/="/>
    <symb name="//="/>
    <symb name="%="/>
    <symb name="&amp;="/>
    <symb name="|="/>
    <symb name="^="/>
    <symb name=">>="/>
    <symb name="&lt;&lt;="/>
    <symb name="**="/>
   </keywords>



        </scheme>
    </type>

After this you must save the file as iptables.hcr and add inside the jar:

[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar

Based in: https://ohadsc.wordpress.com/2012/05/26/adding-syntax-highlighting-for-new-languages-to-eclipse-with-the-colorer-library/

How to create JSON string in C#

Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?

How to select a single column with Entity Framework?

You can use LINQ's .Select() to do that. In your case it would go something like:

string Name = yourDbContext
  .MyTable
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList() instead, to execute the request. Something like this, to get the Name of everyone with age 30:

string[] Names = yourDbContext
  .MyTable
  .Where(u => u.Age == 30)
  .Select(u => u.Name)
  .ToList();

How to show one layout on top of the other programmatically in my case?

FrameLayout is not the better way to do this:

Use RelativeLayout instead. You can position the elements anywhere you like. The element that comes after, has the higher z-index than the previous one (i.e. it comes over the previous one).

Example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        app:srcCompat="@drawable/ic_information"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a text."
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="8dp"
        android:padding="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="#A000"
        android:textColor="@android:color/white"/>
</RelativeLayout>

enter image description here

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

How to get first N elements of a list in C#?

In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)

myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);

Best way to display data via JSON using jQuery

You can create a jQuery object from a JSON object:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});

How to find the index of an element in an int array?

Integer[] array = {1,2,3,4,5,6};

Arrays.asList(array).indexOf(4);

Note that this solution is threadsafe because it creates a new object of type List.

Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time

Java generating non-repeating random numbers

How about this?

LinkedHashSet<Integer> test = new LinkedHashSet<Integer>();
Random random = new Random();
do{
    test.add(random.nextInt(1000) + 1);
}while(test.size() != 1000);

The user can then iterate through the Set using a for loop.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

I encountered this issue and tried everything including File > Invalidate Caches but nothing worked. The reason this issue was happening for me was because I had external projects that were using a different AppCompat version to my main gradle file.

After I updated all gradle files to be the same version the compile error went away.

Angularjs checkbox checked by default on load and disables Select list when checked

You don't really need the directive, can achieve it by using the ng-init and ng-checked. below demo link shows how to set the initial value for checkbox in angularjs.

demo link:

<form>
    <div>
      Released<input type="checkbox" ng-model="Released" ng-bind-html="ACR.Released" ng-true-value="true" ng-false-value="false" ng-init='Released=true' ng-checked='true' /> 
      Inactivated<input type="checkbox" ng-model="Inactivated" ng-bind-html="Inactivated" ng-true-value="true" ng-false-value="false" ng-init='Inactivated=false' ng-checked='false' /> 
      Title Changed<input type="checkbox" ng-model="Title" ng-bind-html="Title" ng-true-value="true" ng-false-value="false" ng-init='Title=false' ng-checked='false' />
    </div>
    <br/>
    <div>Released value is  <b>{{Released}}</b></div>
    <br/>
    <div>Inactivated  value is  <b>{{Inactivated}}</b></div>
    <br/>
    <div>Title  value is  <b>{{Title}}</b></div>
    <br/>
  </form>

// Code goes here

  var app = angular.module("myApp", []);
        app.controller("myCtrl", function ($scope) {

         });    

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I also came across the same issue. I was trying to build the project with a clean install goal. I simply changed it to clean package -o in the run configuration. Then I re-built the project and it worked for me.

If/else else if in Jquery for a condition

Change the less-than operator to a greater-than-or-equal-to operator:

}elseif($("#seats").val() >= 99999){

How to check if a folder exists

Quite simple:

new File("/Path/To/File/or/Directory").exists();

And if you want to be certain it is a directory:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I use this way with Resource file (don't need Prompt anymore !)

@Html.TextBoxFor(m => m.Name, new 
{
     @class = "form-control",
     placeholder = @Html.DisplayName(@Resource.PleaseTypeName),
     autofocus = "autofocus",
     required = "required"
})

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Try this, it will convert True into 1 and False into 0:

data.frame$column.name.num  <- as.numeric(data.frame$column.name)

Then you can convert into factor if you want:

data.frame$column.name.num.factor <- as .factor(data.frame$column.name.num)

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I was also having the same problem. I tried the following and it's working for me now:
Please try the following steps:

Go to..

File > Settings > Appearance & Behavior > System Settings > HTTP Proxy [Under IDE Settings] Enable following option Auto-detect proxy settings

On Mac it's under:

Android Studio > Preferences > Appearance & Behaviour... etc

you can also use the test connection button and check with google.com to see if it works or not.

How to delete parent element using jQuery

I have stumbled upon this problem for one hour. After an hour, I tried debugging and this helped:

$('.list').on('click', 'span', (e) => {
  $(e.target).parent().remove();
});

HTML:

<ul class="list">
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
</ul>

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

receiving json and deserializing as List of object at spring mvc controller

Here is the code that works for me. The key is that you need a wrapper class.

public class Person {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

A PersonWrapper class

public class PersonWrapper {

    private List<Person> persons;

    /**
     * @return the persons
     */
    public List<Person> getPersons() {
        return persons;
    }

    /**
     * @param persons the persons to set
     */
    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

My Controller methods

@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
    @ResponseBody
    public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
        List<String> response = new ArrayList<String>();
        for (Person person: wrapper.getPersons()){
        personService.save(person);
         response.add("Saved person: " + person.toString());
    }
        return response;
    }

The request sent is json in POST

{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}

And the response is

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]

Use of Finalize/Dispose method in C#

Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:

Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).

The pattern I've put together (and written a code snippet for) follows:

#region IDisposable implementation

//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable

// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }

/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
    Dispose( true );

    // This object will be cleaned up by the Dispose method.
    // Therefore, you should call GC.SupressFinalize to
    // take this object off the finalization queue 
    // and prevent finalization code for this object
    // from executing a second time.

    // Always use SuppressFinalize() in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize( this );
}

/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> equals false, the method has been called by the 
/// runtime from inside the finalizer and you should not reference 
/// other objects. Only unmanaged resources can be disposed.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
    // TODO If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    try
    {
        if( !this.IsDisposed )
        {
            if( isDisposing )
            {
                // TODO Release all managed resources here

                $end$
            }

            // TODO Release all unmanaged resources here



            // TODO explicitly set root references to null to expressly tell the GarbageCollector
            // that the resources have been disposed of and its ok to release the memory allocated for them.


        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );

        this.IsDisposed = true;
    }
}

//TODO Uncomment this code if this class will contain members which are UNmanaged
// 
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
//  ~$className$()
//  {
//     Dispose( false );
//  }
#endregion IDisposable implementation

Here is the code for implementing IDisposable in a derived class. Note that you do not need to explicitly list inheritance from IDisposable in the definition of the derived class.

public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)


protected override void Dispose( bool isDisposing )
{
    try
    {
        if ( !this.IsDisposed )
        {
            if ( isDisposing )
            {
                // Release all managed resources here

            }
        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );
    }
}

I've posted this implementation on my blog at: How to Properly Implement the Dispose Pattern

Convert ASCII number to ASCII Character in C

If the number is stored in a string (which it would be if typed by a user), you can use atoi() to convert it to an integer.

An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.

char c = atoi("61");

Semi-transparent color layer over background-image?

I know this is a really old thread, but it shows up at the top in Google, so here's another option.

This one is pure CSS, and doesn't require any extra HTML.

box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);

There are a surprising number of uses for the box-shadow feature.

What does "#include <iostream>" do?

# indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.

So, #include is a preprocessor directive that tells the preprocessor to include header files in the program.

< > indicate the start and end of the file name to be included.

iostream is a header file that contains functions for input/output operations (cin and cout).

Now to sum it up C++ to English translation of the command, #include <iostream> is:

Dear preprocessor, please include all the contents of the header file iostream at the very beginning of this program before compiler starts the actual compilation of the code.

Reading an Excel file in python using pandas

import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)