Programs & Examples On #Isinrole

IsInRole is a method of the WindowsPrincipal class found in the System.Security.Principal namespace of Microsoft's .NET framework. It has several overloads and returns a boolean value that indicates if the principal object is member of a particular group.

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

Powershell script does not run via Scheduled Tasks

My fix to this problem was to ensure I used the full path for all files names in the ps1 file.

How to set a value of a variable inside a template code?

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of


Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

Loop through JSON object List

Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].

$.each(result.d,function(i) {
    // In case there are several values in the array 'd'
    $.each(this,function(j) {
        // Apparently doesn't work...
        // What about this?
        // Or this?

That should work. if not, then maybe you can give us a longer example of the JSON.

Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.

C# winforms combobox dynamic autocomplete

 using (var client = new UserServicesClient())
     var list = new AutoCompleteStringCollection();
     comboBoxName.AutoCompleteCustomSource = list;

How to determine if a string is a number with C++?

The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number.

bool is_number(const std::string& s)
    std::string::const_iterator it = s.begin();
    while (it != s.end() && std::isdigit(*it)) ++it;
    return !s.empty() && it == s.end();

Or if you want to do it the C++11 way:

bool is_number(const std::string& s)
    return !s.empty() && std::find_if(s.begin(), 
        s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();

As pointed out in the comments below, this only works for positive integers. If you need to detect negative integers or fractions, you should go with a more robust library-based solution. Although, adding support for negative integers is pretty trivial.

Create Elasticsearch curl query for not null and not empty("")

Elastic search Get all record where condition not empty.

const searchQuery = {
      body: {
        query: {
          query_string: {
            default_field: '*.*',
            query: 'feildName: ?*',
      index: 'IndexName'

fatal: Not a valid object name: 'master'

You need to commit at least one time on master before creating a new branch.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

I ran into this and added the following to my datetime property:

 [Column(TypeName = "datetime2")]
 public DateTime? NullableDateTimePropUtc { get; set; }

Difference Between One-to-Many, Many-to-One and Many-to-Many?

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: Each "child" Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)

  • Unidirectional: A Person can directly reference Skills via its Set
  • Bidirectional: A Skill has a Set of Person(s) which relate to it.

In a One-To-Many relationship, one object is the "parent" and one is the "child". The parent controls the existence of the child. In a Many-To-Many, the existence of either type is dependent on something outside the both of them (in the larger application context).

Your subject matter (domain) should dictate whether or not the relationship is One-To-Many or Many-To-Many -- however, I find that making the relationship unidirectional or bidirectional is an engineering decision that trades off memory, processing, performance, etc.

What can be confusing is that a Many-To-Many Bidirectional relationship does not need to be symmetric! That is, a bunch of People could point to a skill, but the skill need not relate back to just those people. Typically it would, but such symmetry is not a requirement. Take love, for example -- it is bi-directional ("I-Love", "Loves-Me"), but often asymmetric ("I love her, but she doesn't love me")!

All of these are well supported by Hibernate and JPA. Just remember that Hibernate or any other ORM doesn't give a hoot about maintaining symmetry when managing bi-directional many-to-many relationships...thats all up to the application.

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Can you Run Xcode in Linux?

You can run Xcode on Linux NATIVELY using Darling:

Darling is a translation layer that lets you run macOS software on Linux

Once installed you can install Xcode via command-line developer tool following this link.

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;

I know it been asked a long time ago, but I thought a concrete example might help.

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

Android getResources().getDrawable() deprecated API 22

Replace this line : getResources().getDrawable(R.drawable.your_drawable)

with ResourcesCompat.getDrawable(getResources(), R.drawable.your_drawable, null)


ResourcesCompat is also deprecated now. But you can use this:

ContextCompat.getDrawable(this, R.drawable.your_drawable) (Here this is the context)

for more details follow this link: ContextCompat

What's the meaning of System.out.println in Java?

System is the java class.

out is the instance and also static member of PrintStream.

println is the method of PrintStream.

Excel - extracting data based on another list

I have been hasseling with that as other folks have.

I used the criteria;


where matchingList is the list that i am using as a filter.

have a look at this

The trick i found is that normally you would have the column heading in the criteria matching the data column heading. this will not work for criteria that is a formula.

What I found was if I left the column heading blank for only the criteria that has the countif formula in the advanced filter works. If I have the column heading i.e. the column heading for column C2 in my formula example then the filter return no output.

Hope this helps

Set bootstrap modal body height by percentage

This worked for me

.modal-content {
    /* 80% of window height */
    height: 80%;

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;


How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Use putty. Put install directory path in environment values (PATH), and restart your PC if required.

Open cmd (command prompt) and type

C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/

It'll be copied to the system.

creating an array of structs in c++

You can't use an initialization-list for a struct after it's been initialized. You've already default-initialized the two Customer structs when you declared the array customerRecords. Therefore you're going to have either use member-access syntax to set the value of the non-static data members, initialize the structs using a list of initialization lists when you declare the array itself, or you can create a constructor for your struct and use the default operator= member function to initialize the array members.

So either of the following could work:

Customer customerRecords[2];
customerRecords[0].uid = 25;
customerRecords[0].name = "Bob Jones";
customerRecords[1].uid = 25;
customerRecords[1].namem = "Jim Smith";

Or if you defined a constructor for your struct like:

Customer::Customer(int id, string input_name): uid(id), name(input_name) {}

You could then do:

Customer customerRecords[2];
customerRecords[0] = Customer(25, "Bob Jones");
customerRecords[1] = Customer(26, "Jim Smith");

Or you could do the sequence of initialization lists that Tuomas used in his answer. The reason his initialization-list syntax works is because you're actually initializing the Customer structs at the time of the declaration of the array, rather than allowing the structs to be default-initialized which takes place whenever you declare an aggregate data-structure like an array.

ReactJS - How to use comments?

To summarize, JSX doesn't support comments, either html-like or js-like:

    /* This will be rendered as text */
    // as well as this
    <!-- While this will cause compilation failure -->

and the only way to add comments "in" JSX is actually to escape into JS and comment in there:

    {/* This won't be rendered */}
    {// just be sure that your closing bracket is out of comment

if you don't want to make some nonsense like

<div style={{display:'none'}}>
    actually, there are other stupid ways to add "comments"
    but cluttering your DOM is not a good idea

Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.

How to convert Json array to list of objects in c#

Did you check this line works perfectly & your string have value in it ?

string jsonString = sr.ReadToEnd();

if yes, try this code for last line:

ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

or if you have an array of json you can use list like this :

List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);

good luck

How to get the current TimeStamp?

I think you are looking for this function:

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

vba error handling in loop

There is another way of controlling error handling that works well for loops. Create a string variable called here and use the variable to determine how a single error handler handles the error.

The code template is:

On error goto errhandler

Dim here as String

here = "in loop"
For i = 1 to 20 
    some code
Next i

here = "after loop"
more code

exit sub

If here = "in loop" Then 
    resume afterloop
elseif here = "after loop" Then
    msgbox "An error has occurred" & err.desc
    resume exitproc
End if

ASP MVC href to a controller/view

You can also use this very simplified form:

@Html.ActionLink("Come back to Home", "Index", "Home")

Where :
Come back to Home is the text that will appear on the page
Index is the view name
Homeis the controller name

Adding devices to team provisioning profile

right click on the device, then select 'add device to provisioning profile'

Beamer: How to show images as step-by-step images

I found a solution to my problem, by using the visble-command.


   \textbf{Some text}

How to write a basic swap function in Java

In cases like that there is a quick and dirty solution using arrays with one element:

public void swap(int[] a, int[] b) {
  int temp = a[0];
  a[0] = b[0];
  b[0] = temp;

Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:

public void test() {
  final int[] a = int[]{ 42 };  
  new Thread(new Runnable(){ public void run(){ a[0] += 10; }}).start();
  while(a[0] == 42) {

Run react-native on android emulator


  • brew cask install android-platform-tools
  • adb reverse tcp:9090 tcp:9090
  • run the app

How to access Spring MVC model object in javascript file?

Here is an example of how i made a list object available for javascript:

var listForJavascript = [];
<c:forEach items="${MyListFromJava}" var="listItem">
  var arr = [];

  arr.push("<c:out value="${listItem.param1}" />");
  arr.push("<c:out value="${listItem.param2}" />");


Change Placeholder Text using jQuery

Moving your first line to the bottom does it for me:

$(function () {
    $('#serMemdd').change(function () {
        var k = $(this).val();
        if (k == 1) {
            $("#serMemtb").attr("placeholder", "Type a name (Lastname, Firstname)").placeholder();
        else if (k == 2) {
            $("#serMemtb").attr("placeholder", "Type an ID").placeholder();
        else if (k == 3) {
            $("#serMemtb").attr("placeholder", "Type a Location").placeholder();
    $('input[placeholder], textarea[placeholder]').placeholder();

How to handle-escape both single and double quotes in an SQL-Update statement

In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation

Get Last Part of URL PHP

Split it apart and get the last element:

$end = end(explode('/', $url));
# or:
$end = array_slice(explode('/', $url), -1)[0];

Edit: To support apache-style-canonical URLs, rtrim is handy:

$end = end(explode('/', rtrim($url, '/')));
# or:
$end = array_slice(explode('/', rtrim($url, '/')), -1)[0];

A different example which might me considered more readable is (Demo):

$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);

This example also takes into account to only work on the path of the URL.

Yet another edit (years after), canonicalization and easy UTF-8 alternative use included (via PCRE regular expression in PHP):


use function call_user_func as f;
use UnexpectedValueException as e;

$url = '';

$result = preg_match('(([^/]*)/*$)', $url, $m)

    ? $m[1]
    : f(function() use ($url) {throw new e("pattern on '$url'");})

var_dump($result); # string(7) "9393903"

Which is pretty rough but shows how to wrap this this within a preg_match call for finer-grained control via PCRE regular expression pattern. To add some sense to this bare-metal example, it should be wrapped inside a function of its' own (which would also make the aliasing superfluous). Just presented this way for brevity.

How to get .pem file from .key and .crt files?

this is the best option to create .pem file

openssl pkcs12 -in MyPushApp.p12 -out MyPushApp.pem -nodes -clcerts

Determine the type of an object?

You can do that using type():

>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>

Presenting a UIAlertController properly on an iPad using iOS 8

Just add the following code before presenting your action sheet:

if let popoverController = optionMenu.popoverPresentationController {
    popoverController.sourceView = self.view
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    popoverController.permittedArrowDirections = []

How do I discover memory usage of my application in Android?

There are a lot of answer above which will definitely help you but (after 2 days of afford and research on adb memory tools) I think i can help with my opinion too.

As Hackbod says : Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM. so there is no way you can get exact amount of memory per process.

But you can get close to it by some logic..and I will tell how..

There are some API like android.os.Debug.MemoryInfo and ActivityManager.getMemoryInfo() mentioned above which you already might have being read about and used but I will talk about other way

So firstly you need to be a root user to get it work. Get into console with root privilege by executing su in process and get its output and input stream. Then pass id\n (enter) in ouputstream and write it to process output, If will get an inputstream containing uid=0, you are root user.

Now here is the logic which you will use in above process

When you get ouputstream of process pass you command (procrank, dumpsys meminfo etc...) with \n instead of id and get its inputstream and read, store the stream in bytes[ ] ,char[ ] etc.. use raw data..and you are done!!!!!

permission :

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

Check if you are root user :

// su command to get root access
Process process = Runtime.getRuntime().exec("su");         
DataOutputStream dataOutputStream = 
                           new DataOutputStream(process.getOutputStream());
DataInputStream dataInputStream = 
                           new DataInputStream(process.getInputStream());
if (dataInputStream != null && dataOutputStream != null) {
   // write id to console with enter
   String Uid = dataInputStream.readLine();
   // read output and check if uid is there
   if (Uid.contains("uid=0")) {                           
      // you are root user

Execute your command with su

Process process = Runtime.getRuntime().exec("su");         
DataOutputStream dataOutputStream = 
                           new DataOutputStream(process.getOutputStream());
if (dataOutputStream != null) {
 // adb command
 BufferedInputStream bufferedInputStream = 
                     new BufferedInputStream(process.getInputStream());
 // this is important as it takes times to return to next line so wait
 // else you with get empty bytes in buffered stream 
 try {
 } catch (InterruptedException e) {                     
 // read buffered stream into byte,char etc.
 byte[] bff = new byte[bufferedInputStream.available()];;

logcat : result

You get a raw data in a single string from console instead of in some instance from any API,which is complex to store as you will need to separate it manually.

This is just a try, please suggest me if I missed something

The imported project "C:\Microsoft.CSharp.targets" was not found

For me the issue was that the path of the project contained %20 characters, because git added those instead of spaces when the repository was cloned. Another problem might be if the path to a package is too long.

How do I get DOUBLE_MAX?

Its in the standard float.h include file. You want DBL_MAX

Laravel 5 Clear Views Cache

There is now a php artisan view:clear command for this task since Laravel 5.1

How to use SVN, Branch? Tag? Trunk?

Just to add another set of answers:

  • I commit whenever I finish a piece of work. Sometimes it's a tiny bugfix that just changed one line and took me 2 minutes to do; other times it's two weeks worth of sweat. Also, as a rule of thumb, you don't commit anything that breaks the build. Thus if it has taken you a long time to do something, take the latest version before committing, and see if your changes break the build. Of course, if I go a long time without committing, it makes me uneasy because I don't want to loose that work. In TFS I use this nice thing as "shelvesets" for this. In SVN you'll have to work around in another way. Perhaps create your own branch or backup these files manually to another machine.
  • Branches are copies of your whole project. The best illustration for their use is perhaps the versioning of products. Imagine that you are working at a large project (say, the Linux kernel). After months of sweat you've finally arrived at version 1.0 that you release to the public. After that you start to work on version 2.0 of you product which is going to be way better. But in the mean time there are also a lot of people out there which are using version 1.0. And these people find bugs that you have to fix. Now, you can't fix the bug in the upcoming 2.0 version and ship that to the clients - it's not ready at all. Instead you have to pull out an old copy of 1.0 source, fix the bug there, and ship that to the people. This is what branches are for. When you released the 1.0 version you made a branch in SVN which made a copy of the source code at that point. This branch was named "1.0". You then continued work on the next version in your main source copy, but the 1.0 copy remained there as it was at the moment of the release. And you can continue fixing bugs there. Tags are just names attached to specific revisions for ease of use. You could say "Revision 2342 of the source code", but it's easier to refer to it as "First stable revision". :)
  • I usually put everything in the source control that relates directly to the programming. For example, since I'm making webpages, I also put images and CSS files in source control, not to mention config files etc. Project documentation does not go in there, however that is actually just a matter of preference.

How to load json into my angular.js ng-model?

I use following code, found somewhere in the internet don't remember the source though.

    var allText;
    var rawFile = new XMLHttpRequest();"GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
    return JSON.parse(allText);

How to get tf.exe (TFS command line client)?

You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.

2012 version

2013 version

2019 version

You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe) and also add some extra IDE features.

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:


You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with


login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:


Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql


Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Disable Required validation attribute under certain circumstances

I was having this problem when I creating a Edit View for my Model and I want to update just one field.

My solution for a simplest way is put the two field using :

 <%: Html.HiddenFor(model => model.ID) %>
 <%: Html.HiddenFor(model => model.Name)%>
 <%: Html.HiddenFor(model => model.Content)%>
 <%: Html.TextAreaFor(model => model.Comments)%>

Comments is the field that I only update in Edit View, that not have Required Attribute.

ASP.NET MVC 3 Entity

What is the difference between Trap and Interrupt?

A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

Here's what Oracle's documentation has to say:

By default the heap dump is created in a file called java_pid.hprof in the working directory of the VM, as in the example above. You can specify an alternative file name or directory with the -XX:HeapDumpPath= option. For example -XX:HeapDumpPath=/disk2/dumps will cause the heap dump to be generated in the /disk2/dumps directory.

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

Swift Open Link in Safari

since iOS 10 you should use:

guard let url = URL(string: linkUrlString) else {
if #available(iOS 10.0, *) {, options: [:], completionHandler: nil)
} else {

How to Maximize a firefox browser window using Selenium WebDriver with node.js

First instantiate a firefox driver

WebDriver driver = new FirefoxDriver();

then maximize it


Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

It is possible and quite simple:

for DateTime.MinValue

[System.ComponentModel.DefaultValue(typeof(DateTime), "")]

for any other value as last argument of DefaultValueAttribute specify string that represent desired DateTime value.

This value must be constant expression and is required to create object (DateTime) using TypeConverter.

Curl error: Operation timed out

Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

will need replace to PHP code

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

May be some body reply how this options connected with "Curl error: Operation timed out after .."

Adding header for HttpURLConnection

If you are using Java 8, use the code below.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate: will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

Java Enum Methods - return opposite direction enum

public enum Direction {

    public Direction getOppositeDirection(){
        return Direction.values()[(this.ordinal() + 2) % 4];

Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared. source

since NORTH gets 1, EAST gets 2, SOUTH gets 3, WEST gets 4; you can create a simple equation to get the opposite one:

(value + 2) % 4

Percentage width in a RelativeLayout

You cannot use percentages to define the dimensions of a View inside a RelativeLayout. The best ways to do it is to use LinearLayout and weights, or a custom Layout.

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

How to select Python version in PyCharm?

I think you are saying that you have python2 and python3 installed and have added a reference to each version under Pycharm > Settings > Project Interpreter

What I think you are asking is how do you have some projects run with Python 2 and some projects running with Python 3.

If so, you can look under Run > Edit Configurations

PyCharm Run > Edit Configurations

importing pyspark in python shell

dont run your py file as: python instead use: spark-submit

Spring Resttemplate exception handling

You should catch a HttpStatusCodeException exception:

try {;
} catch (HttpStatusCodeException exception) {
    int statusCode = exception.getStatusCode().value();

Set width of a "Position: fixed" div relative to parent div

Here is a little hack that we ran across while fixing some redraw issues on a large app.

Use -webkit-transform: translateZ(0); on the parent. Of course this is specific to Chrome.

-webkit-transform: translateZ(0);

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.

It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"

Starting a webserver can be as trivial as cding into the directory the files are in and running:

python -m SimpleHTTPServer

jQuery checkbox checked state changed event

Try this jQuery validation

$(document).ready(function() {_x000D_
  $('#myform').validate({ // initialize the plugin_x000D_
    rules: {_x000D_
      agree: {_x000D_
        required: true_x000D_
    submitHandler: function(form) {_x000D_
      alert('valid form submitted');_x000D_
      return false;_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<form id="myform" action="" method="post">_x000D_
  <div class="buttons">_x000D_
    <div class="pull-right">_x000D_
      <input type="checkbox" name="agree" /><br/>_x000D_
      <label>I have read and agree to the <a href="">Terms of services</a> </label>_x000D_
  <button type="submit">Agree</button>_x000D_

javascript /jQuery - For Loop

Use a regular for loop and format the index to be used in the selector.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());

How to sort an ArrayList?

In JAVA 8 its much easy now.

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");
List<String> alphaNumbersUpperCase =
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]

-- For reverse use this


How to implement a secure REST API with node.js

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

C dynamically growing array

These posts may be in the wrong order! This is #2 in a series of 3 posts. Sorry.

I've "taken a few liberties" with Lie Ryan's code, implementing a linked list so individual elements of his vector can be accessed via a linked list. This allows access, but admittedly it is time-consuming to access individual elements due to search overhead, i.e. walking down the list until you find the right element. I'll cure this by maintaining an address vector containing subscripts 0 through whatever paired with memory addresses. This is still not as efficient as a plain-and-simple array would be, but at least you don't have to "walk the list" searching for the proper item.

    // Based on code from
typedef struct STRUCT_SS_VECTOR
{   size_t size; // # of vector elements
    void** items; // makes up one vector element's component contents
    int subscript; // this element's subscript nmbr, 0 thru whatever
    struct STRUCT_SS_VECTOR* this_element; // linked list via this ptr
    struct STRUCT_SS_VECTOR* next_element; // and next ptr
} ss_vector;

ss_vector* vector; // ptr to vector of components

ss_vector* ss_init_vector(size_t item_size) // item_size is size of one array member
{   vector= malloc(sizeof(ss_vector)); 
    vector->this_element = vector; 
    vector->size = 0; // initialize count of vector component elements
    vector->items = calloc(1, item_size); // allocate & zero out memory for one linked list element
    //      If there's an array of element addresses/subscripts, install it now.
    return vector->this_element;

ss_vector* ss_vector_append(ss_vector* vec_element,                 int i) 
//                                                                          ^--ptr to this element  ^--element nmbr
{   ss_vector* local_vec_element=0;
    // If there is already a next element, recurse to end-of-linked-list
    {   local_vec_element= ss_vector_append(vec_element->next_element,i); // recurse to end of list
        return local_vec_element;
    // vec_element is NULL, so make a new element and add at end of list
    local_vec_element= calloc(1,sizeof(ss_vector)); // memory for one component
    local_vec_element->this_element=local_vec_element; // save the address
    local_vec_element->subscript=i; //vec_element->size; 
    local_vec_element->size=i; // increment # of vector components
    //      If there's an array of element addresses/subscripts, update it now.
    return local_vec_element;

void ss_vector_free_one_element(int i,gboolean Update_subscripts) 
{   // Walk the entire linked list to the specified element, patch up 
    //      the element ptrs before/next, then free its contents, then free it.
    //      Walk the rest of the list, updating subscripts, if requested.
    //      If there's an array of element addresses/subscripts, shift it along the way.
    ss_vector* vec_element;
    struct STRUCT_SS_VECTOR* this_one;
    struct STRUCT_SS_VECTOR* next_one;
    while((vec_element->this_element->subscript!=i)&&(vec_element->next_element!=(size_t) 0)) // skip
    {   this_one=vec_element->this_element; // trailing ptr
        next_one=vec_element->next_element; // will become current ptr
    // now at either target element or end-of-list
    {   printf("vector element not found\n");return;}
    // free this one
    this_one->next_element=next_one->next_element;// previous element points to element after current one
    printf("freeing element[%i] at %lu",next_one->subscript,(size_t)next_one);
    printf(" between %lu and %lu\n",(size_t)this_one,(size_t)next_one->next_element);
    free(next_one); // free the current element
    // renumber if requested
    {   i=0;
        while(vec_element!=(size_t) 0)
        {   vec_element->subscript=i;
    //      If there's an array of element addresses/subscripts, update it now.
/*  // Check: temporarily show the new list
    while(vec_element!=(size_t) 0)
    {   printf("   remaining element[%i] at %lu\n",vec_element->subscript,(size_t)vec_element->this_element);
    } */
} // void ss_vector_free_one_element()

void ss_vector_insert_one_element(ss_vector* vec_element,int place) 
{   // Walk the entire linked list to specified element "place", patch up 
    //      the element ptrs before/next, then calloc an element and store its contents at "place".
    //      Increment all the following subscripts.
    //      If there's an array of element addresses/subscripts, make a bigger one, 
    //      copy the old one, then shift appropriate members.
    // ***Not yet implemented***
} // void ss_vector_insert_one_element()

void ss_vector_free_all_elements(void) 
{   // Start at "vector".Walk the entire linked list, free each element's contents, 
    //      free that element, then move to the next one.
    //      If there's an array of element addresses/subscripts, free it.
    ss_vector* vec_element;
    struct STRUCT_SS_VECTOR* next_one;
    while(vec_element->next_element!=(size_t) 0)
    {   next_one=vec_element->next_element;
        // free(vec_element->items) // don't forget to free these
    // get rid of the last one.
    // free(vec_element->items)
    //      If there's an array of element addresses/subscripts, free it now.
printf("\nall vector elements & contents freed\n");
} // void ss_vector_free_all_elements()

// defining some sort of struct, can be anything really
typedef struct APPLE_STRUCT
{   int id; // one of the data in the component
    int other_id; // etc
    struct APPLE_STRUCT* next_element;
} apple; // description of component

apple* init_apple(int id) // make a single component
{   apple* a; // ptr to component
    a = malloc(sizeof(apple)); // memory for one component
    a->id = id; // populate with data
    // don't mess with aa->last_rec here
    return a; // return pointer to component

int return_id_value(int i,apple* aa) // given ptr to component, return single data item
{   printf("was inserted as apple[%i].id = %i     ",i,aa->id);

ss_vector* return_address_given_subscript(ss_vector* vec_element,int i) 
// always make the first call to this subroutine with global vbl "vector"
{   ss_vector* local_vec_element=0;
    // If there is a next element, recurse toward end-of-linked-list
    {   if((vec_element->this_element->subscript==i))
        {   return vec_element->this_element;}
        local_vec_element= return_address_given_subscript(vec_element->next_element,i); // recurse to end of list
        return local_vec_element;
    {   if((vec_element->this_element->subscript==i)) // last element
        {   return vec_element->this_element;}
        // otherwise, none match
        printf("reached end of list without match\n");
        return (size_t) 0;
} // return_address_given_subscript()

int Test(void)  // was "main" in the original example
{   ss_vector* local_vector;
    local_vector=ss_init_vector(sizeof(apple)); // element "0"
    for (int i = 1; i < 10; i++) // inserting items "1" thru whatever
    {   local_vector=ss_vector_append(vector,i);}   
    // test search function
    printf("\n NEXT, test search for address given subscript\n");
    printf("finished return_address_given_subscript(5) with vector at %lu\n",(size_t)local_vector);
    printf("finished return_address_given_subscript(0) with vector at %lu\n",(size_t)local_vector);
    printf("finished return_address_given_subscript(9) with vector at %lu\n",(size_t)local_vector);
    // test single-element removal
    printf("\nNEXT, test single element removal\n");
    ss_vector_free_one_element(5,FALSE); // without renumbering subscripts
    ss_vector_free_one_element(3,TRUE);// WITH renumbering subscripts
    // ---end of program---
    // don't forget to free everything
    return 0;

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():

func.temp = 1


class TempClass:
    a = 1
    def temp_function(self):


will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

Parse JSON in C#

Thank you all for your help. This is my final version, and it works thanks to your combined help ! I am only showing the changes i made, all the rest is taken from Joe Chung's work

public class GoogleSearchResults
        public ResponseData responseData { get; set; }

        public string responseDetails { get; set; }

        public int responseStatus { get; set; }


    public class ResponseData
        public List<Results> results { get; set; }

How do I use raw_input in Python 3

As others have indicated, the raw_input function has been renamed to input in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.

From your description, I think you're using Windows, you've saved a .py file and then you're double-clicking on it to run it. The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was. To solve this, your book recommends adding a raw_input / input statement to wait until the user presses enter. However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong. You might find it easier to use a command-prompt or IDLE.

Use a command-prompt

When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window. The menu that pops up should contain an entry "Open command window here". (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

    C:\Users\Weeble\My Python Program>_

To run your program, type the following (substituting your script name):


...and press enter. (If you get an error that "python" is not a recognized command, see ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.


IDLE is a simple program editor that comes installed with Python. Among other features it can run your programs in a window. Right-click on your .py file and choose "Edit in IDLE". When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu. Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.

Converting milliseconds to minutes and seconds with Javascript

this code will do a better job if you want to show hours, and centiseconds or miliseconds after seconds like 1:02:32.21 and if used in a cell phone the timer will show correct timing even after screen lock.

<div id="timer" style="font-family:monospace;">00:00<small>.00</small></div>_x000D_
var d = new Date();_x000D_
var n = d.getTime();_x000D_
var startTime = n;_x000D_
var tm=0;_x000D_
function updateTimer(){_x000D_
  d = new Date();_x000D_
  n = d.getTime();_x000D_
  var currentTime = n;  _x000D_
  tm = (currentTime-startTime);_x000D_
  //tm +=1; _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm*10;_x000D_
  var hours = Math.floor(tm / 1000 / 60 / 60);_x000D_
  var minutes = Math.floor(tm / 60000) % 60;_x000D_
  var seconds =  ((tm / 1000) % 60);_x000D_
  // saca los decimales ej 2 d{0,2}_x000D_
  var seconds = seconds.toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
  var miliseconds = ("00" + tm).slice(-3);_x000D_
  var centiseconds;_x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm/10;_x000D_
  centiseconds = miliseconds/10;_x000D_
  centiseconds = (centiseconds).toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
  minutes = (minutes < 10 ? '0' : '') + minutes;_x000D_
  seconds = (seconds < 10 ? '0' : '') + seconds;_x000D_
  centiseconds = (centiseconds < 10 ? '0' : '') + centiseconds;_x000D_
  hours = hours + (hours > 0 ? ':' : '');_x000D_
  if (hours==0){_x000D_
  document.getElementById("timer").innerHTML = hours + minutes + ':' + seconds + '<small>.' + centiseconds + '</small>';_x000D_
var timerInterval = setInterval(updateTimer, 10);_x000D_
// clearInterval(timerInterval);_x000D_

What is Java String interning?

String interning is an optimization technique by the compiler. If you have two identical string literals in one compilation unit then the code generated ensures that there is only one string object created for all the instance of that literal(characters enclosed in double quotes) within the assembly.

I am from C# background, so i can explain by giving a example from that:

object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;

output of the following comparisons:

Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true    
Console.WriteLine(obj == str2); // false !?

Note1:Objects are compared by reference.

Note2:typeof(int).Name is evaluated by reflection method so it does not gets evaluated at compile time. Here these comparisons are made at compile time.

Analysis of the Results: 1) true because they both contain same literal and so the code generated will have only one object referencing "Int32". See Note 1.

2) true because the content of both the value is checked which is same.

3) FALSE because str2 and obj does not have the same literal. See Note 2.

git push rejected: error: failed to push some refs

Just do

git pull origin [branch]

and then you should be able to push.

If you have commits on your own and didn't push it the branch yet, try

git pull --rebase origin [branch]

and then you should be able to push.

Read more about handling branches with Git.

how can the textbox width be reduced?

rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        this.handleClick = this.handleClick.bind(this);
    handleClick() {
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

    render() {
        return (
               profileCollapsed={this.state.profileCollapsed} />

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Disable autocomplete via CSS

As it stands, there is no 'autocomplete off' attribute in CSS. However, html has an easy code for this:

<input type="text" id="foo" value="bar" autocomplete="off" />

If you're looking for a site-wide effector, an easy one would be to simply have a js function to run through all 'input' s and add this tag, or look for the corresponding css class / id.

The autocomplete attribute works fine in Chrome and Firefox (!), but see also Is there a W3C valid way to disable autocomplete in a HTML form?

Auto refresh code in HTML using meta tags

The quotes you use are the issue:

<meta http-equiv=”refresh” content=”5" >

You should use the "

<meta http-equiv="refresh" content="5">

Get Root Directory Path of a PHP project

For PHP >= 5.3.0 try

PHP magic constants.


And make your path relative.

For PHP < 5.3.0 try


bootstrap 3 - how do I place the brand in the center of the navbar?

Another option is to use nav-justified..

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
  <div class="navbar-collapse collapse">
    <ul class="nav nav-justified">
      <li><a href="#" class="navbar-brand">Brand</a></li>


.navbar-brand {


Alternate example

Easiest way to convert int to string in C++

Not that I know of, in pure C++. But a little modification of what you mentioned

string s = string(itoa(a));

should work, and it's pretty short.

What is DOM Event delegation?

Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements.

JavaScript Example :

Let's say that we have a parent UL element with several child elements:

<ul id="parent-list">
  <li id="post-1">Item 1</li>
  <li id="post-2">Item 2</li>
  <li id="post-3">Item 3</li>
  <li id="post-4">Item 4</li>
  <li id="post-5">Item 5</li>
  <li id="post-6">Item 6</li>

Let's also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

Simple: when the event bubbles up to the UL element, you check the event object's target property to gain a reference to the actual clicked node. Here's a very basic JavaScript snippet which illustrates event delegation:

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
  // is the clicked element!
  // If it was a list item
  if( && == "LI") {
    // List item found!  Output the ID!
    console.log("List item ","post-"), " was clicked!");

Start by adding a click event listener to the parent element. When the event listener is triggered, check the event element to ensure it's the type of element to react to. If it is an LI element, boom: we have what we need! If it's not an element that we want, the event can be ignored. This example is pretty simple -- UL and LI is a straight-forward comparison. Let's try something more difficult. Let's have a parent DIV with many children but all we care about is an A tag with the classA CSS class:

// Get the parent DIV, add click listener...
document.getElementById("myDiv").addEventListener("click",function(e) {
// was the clicked element
  if( && == "A") {
    // Get the CSS classes
    var classes =" ");
    // Search for the CSS class!
    if(classes) {
        // For every CSS class the element has...
        for(var x = 0; x < classes.length; x++) {
            // If it has the CSS class we want...
            if(classes[x] == "classA") {
                // Bingo!
                console.log("Anchor element clicked!");
                // Now do something here....

npm notice created a lockfile as package-lock.json. You should commit this file

It should also be noted that one key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the top level package. It shares a format with npm-shrinkwrap.json(5), which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.

If both package-lock.json and npm-shrinkwrap.json are present in the root of a package, package-lock.json will be completely ignored.

Loop through childNodes

Try with for loop. It gives error in forEach because it is a collection of nodes nodelist.

Or this should convert node-list to array

function toArray(obj) {
  var array = [];
  for (var i = 0; i < obj.length; i++) { 
    array[i] = obj[i];
return array;

Or you can use this

var array =;

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Can you load the GUIDs into a scratch table then do a

... WHERE var IN SELECT guid FROM #scratchtable

Check if number is decimal

A total cludge.. but hey it works !

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero

How do I use a PriorityQueue?

As an alternative to using Comparator, you can also have the class you're using in your PriorityQueue implement Comparable (and correspondingly override the compareTo method).

Note that it's generally best to only use Comparable instead of Comparator if that ordering is the intuitive ordering of the object - if, for example, you have a use case to sort Person objects by age, it's probably best to just use Comparator instead.

import java.lang.Comparable;
import java.util.PriorityQueue;

class Test
    public static void main(String[] args)
        PriorityQueue<MyClass> queue = new PriorityQueue<MyClass>();
        queue.add(new MyClass(2, "short"));
        queue.add(new MyClass(2, "very long indeed"));
        queue.add(new MyClass(1, "medium"));
        queue.add(new MyClass(1, "very long indeed"));
        queue.add(new MyClass(2, "medium"));
        queue.add(new MyClass(1, "short"));
        while (queue.size() != 0)
class MyClass implements Comparable<MyClass>
    int sortFirst;
    String sortByLength;

    public MyClass(int sortFirst, String sortByLength)
        this.sortFirst = sortFirst;
        this.sortByLength = sortByLength;

    public int compareTo(MyClass other)
        if (sortFirst != other.sortFirst)
            return, other.sortFirst);
            return, other.sortByLength.length());

    public String toString()
        return sortFirst + ", " + sortByLength;


1, short
1, medium
1, very long indeed
2, short
2, medium
2, very long indeed

How do I declare a global variable in VBA?

If this function is in a module/class, you could just write them outside of the function, so it has Global Scope. Global Scope means the variable can be accessed by another function in the same module/class (if you use dim as declaration statement, use public if you want the variables can be accessed by all function in all modules) :

Dim iRaw As Integer
Dim iColumn As Integer

Function find_results_idle()
    iRaw = 1
    iColumn = 1
End Function

Function this_can_access_global()
    iRaw = 2
    iColumn = 2
End Function

PHP import Excel into database (xls & xlsx)

If you save the excel file as a CSV file then you can import it into a mysql database using tools such as PHPMyAdmin

Im not sure if this would help in your situation, but a csv file either manually or programatically would be a lot easier to parse into a database than an excel file I would have thought.

EDIT: I would however suggest looking at the other answers rather than mine since @diEcho answer seems more appropriate.

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

Changing text of UIButton programmatically swift

Just a clarification for those new to Swift and iOS programming. Below line of code:

button.setTitle("myTitle", forState: UIControlState.Normal)

only applies to IBOutlets, not IBActions.

So, if your app is using a button as a function to execute some code, say playing music, and you want to change the title from Play to Pause based on a toggle variable, you need to also create an IBOutlet for that button.

If you try to use button.setTitle against an IBAction you will get an error. Its obvious once you know it, but for the noobs (we all were) this is a helpful tip.

How to force a component's re-rendering in Angular 2?

Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).

Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template, ng-container and ViewContainerRef in following way:

  <ng-container #outlet >

<ng-template #content>

Then in component having reference to both #outlet and #content we can clear outlets' content and insert another instance of child component:

@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;

private rerender() {

Additionally initial content should be inserted on AfterContentInit hook:

ngAfterContentInit() {

Full working solution can be found here .

adb uninstall failed

Try disable "Instant run" from settings window

Why did Servlet.service() for servlet jsp throw this exception?

I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

To give a more concrete example... Inside a method, I had something like:

Foo[] foos = new Foo[20];
// fill up the "foos" array...
return Arrays.asList(foos); // this returns type List<Foo>

Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

I actually wondered, as I wrote the above method, whether that would happen.

The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList<Foo>(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

How to get the first line of a file in a bash script?

This suffices and stores the first line of filename in the variable $line:

read -r line < filename

I also like awk for this:

awk 'NR==1 {print; exit}' file

To store the line itself, use the var=$(command) syntax. In this case, line=$(awk 'NR==1 {print; exit}' file).

Or even sed:

sed -n '1p' file

With the equivalent line=$(sed -n '1p' file).

See a sample when we feed the read with seq 10, that is, a sequence of numbers from 1 to 10:

$ read -r line < <(seq 10) 
$ echo "$line"

$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"

Multiplication on command line terminal

The classical solution is:

 expr 5 \* 5

expr will only work with integer operands. Another nice option is:

 echo 5 5\*p | dc

dc can be made to work with non-integer operands.

.NET 4.0 has a new GAC, why?

It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to The new in-process side-by-side feature should not change this.

My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.

Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

Programmatically go back to previous ViewController in Swift

I did it like this

func showAlert() {
    let alert = UIAlertController(title: "Thanks!", message: "We'll get back to you as soon as posible.", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in

    self.present(alert, animated: true)

func dismissView() {
    navigationController?.popViewController(animated: true)
    dismiss(animated: true, completion: nil)

How do I get the MAX row with a GROUP BY in LINQ query?

The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:

from x in db.Serials 
group x by x.Serial_Number into g 
orderby g.Key 
select g.OrderByDescending(z => z.uid)

... this will avoid the "select new"

AngularJS directive does not update on scope variable changes

You need to tell Angular that your directive uses a scope variable:

You need to bind some property of the scope to your directive:

return {
    restrict: 'E',
    scope: {
      whatever: '='

and then $watch it:

  $scope.$watch('whatever', function(value) {
    // do something with the new value

Refer to the Angular documentation on directives for more information.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In your yaml file, add command and args lines:

      - name: api
        image: localhost:5000/image-name 
        command: [ "sleep" ]
        args: [ "infinity" ]

Works for me.

Material UI and Grid system

Below is made by purely MUI Grid system,

MUI - Grid Layout

With the code below,

// MuiGrid.js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
    backgroundColor: "#b5b5b5",
    margin: "10px"

export default function FullWidthGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container spacing={0}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>xs=12</Paper>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>

↓ CodeSandbox ↓

Edit MUI-Grid system

How to make program go back to the top of the code instead of closing

Python has control flow statements instead of goto statements. One implementation of control flow is Python's while loop. You can give it a boolean condition (boolean values are either True or False in Python), and the loop will execute repeatedly until that condition becomes false. If you want to loop forever, all you have to do is start an infinite loop.

Be careful if you decide to run the following example code. Press Control+C in your shell while it is running if you ever want to kill the process. Note that the process must be in the foreground for this to work.

while True:
    # do stuff here

The line # do stuff here is just a comment. It doesn't execute anything. pass is just a placeholder in python that basically says "Hi, I'm a line of code, but skip me because I don't do anything."

Now let's say you want to repeatedly ask the user for input forever and ever, and only exit the program if the user inputs the character 'q' for quit.

You could do something like this:

while True:
    cmd = raw_input('Do you want to quit? Enter \'q\'!')
    if cmd == 'q':

cmd will just store whatever the user inputs (the user will be prompted to type something and hit enter). If cmd stores just the letter 'q', the code will forcefully break out of its enclosing loop. The break statement lets you escape any kind of loop. Even an infinite one! It is extremely useful to learn if you ever want to program user applications which often run on infinite loops. If the user does not type exactly the letter 'q', the user will just be prompted repeatedly and infinitely until the process is forcefully killed or the user decides that he's had enough of this annoying program and just wants to quit.

Java: String - add character n-times

You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":

String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));

How can I color Python logging output?

This is an Enum containing the colour codes:

class TerminalColour:
    Terminal colour formatting codes
    MAGENTA = '\033[95m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    GREY = '\033[0m'  # normal
    WHITE = '\033[1m'  # bright white
    UNDERLINE = '\033[4m'

This may be applied to the names of each log level. Be aware that this is a monstrous hack.

logging.addLevelName(logging.INFO, "{}{}{}".format(TerminalColour.WHITE, logging.getLevelName(logging.INFO), TerminalColour.GREY))
logging.addLevelName(logging.WARNING, "{}{}{}".format(TerminalColour.YELLOW, logging.getLevelName(logging.WARNING), TerminalColour.GREY))
logging.addLevelName(logging.ERROR, "{}{}{}".format(TerminalColour.RED, logging.getLevelName(logging.ERROR), TerminalColour.GREY))
logging.addLevelName(logging.CRITICAL, "{}{}{}".format(TerminalColour.MAGENTA, logging.getLevelName(logging.CRITICAL), .GREY))

Note that your log formatter must include the name of the log level


for example:

    LOGGING = {
        'verbose': {
            'format': '%(asctime)s %(levelname)s %(name)s:%(lineno)s %(module)s %(process)d %(thread)d %(message)s'
        'simple': {
            'format': '[%(asctime)s] %(levelname)s %(name)s %(message)s'

How to custom switch button?

you can use the following code to change color and text :


Create a xml named colors.xml in res/values folder:

<?xml version="1.0" encoding="utf-8"?>
    <color name="red">#ff0000</color>
    <color name="green">#00ff00</color>

In drawable folder, create a xml file my_btn_toggle.xml:

  <selector xmlns:android="">
        <item android:state_checked="false" android:drawable="@color/red"  />
        <item android:state_checked="true" android:drawable="@color/green"  />

and in xml section defining your toggle button add:


to change the color of textOn and textOffuse


String parsing in Java with delimiter tab "\t" using split

I just had the same question and noticed the answer in some kind of tutorial. In general you need to use the second form of the split method, using the

split(regex, limit)

Here is the full tutorial

If you set some negative number for the limit parameter you will get empty strings in the array where the actual values are missing. To use this your initial string should have two copies of the delimiter i.e. you should have \t\t where the values are missing.

Hope this helps :)

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:


Print specific part of webpage

In printPageArea() function, pass the specific div ID which you want to print. I've found this JavaScript code from

function printPageArea(areaID){
    var printContent = document.getElementById(areaID);
    var WinPrint ='', '', 'width=900,height=650');

The complete code and tutorial can be found from here - How to Print Page Area using JavaScript.

What does (function($) {})(jQuery); mean?

A little help:

// an anonymous function_x000D_
(function () { console.log('allo') });_x000D_
// a self invoked anonymous function_x000D_
(function () { console.log('allo') })();_x000D_
// a self invoked anonymous function with a parameter called "$"_x000D_
var jQuery = 'I\'m not jQuery.';_x000D_
(function ($) { console.log($) })(jQuery);

Homebrew refusing to link OpenSSL

The solution might be updating some tools.

Here's my scenario from 2020 with Ruby and Python:

I needed to install Python 3 on Mac and things escalated. In the end, updating homebrew, node and python lead to the problem with openssl. I did not have openssl 1.0 anymore, so I couldn't "brew switch" to it.
So what was still trying to use that old 1.0 version?

It tuned out it was Ruby 2.5.5.
So I just installed Ruby 2.5.8 and removed the old one.

Other things you can try if this is not enough: Use rbenv and pyenv. Clean up gems and formulas. Update homebrew, node, yarn. Upgrade bundler. Make sure your .bash_profile (or equivalent) is set up according to each tool's instructions. Reopen the terminal.

Align text in JLabel to the right

JLabel label = new JLabel("fax", SwingConstants.RIGHT);

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()

    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret

End Sub


 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

Efficient SQL test query or validation query that will work across all (or most) databases

Just found out the hard way that it is


for MaxDB as well.

How to get a DOM Element from a JQuery Selector

You can access the raw DOM element with:


or more simply:


There isn't actually a lot you need this for however (in my experience). Take your checkbox example:

$(":checkbox").click(function() {
  if ($(this).is(":checked")) {
    // do stuff

is more "jquery'ish" and (imho) more concise. What if you wanted to number them?

$(":checkbox").each(function(i, elem) {
  $(elem).data("index", i);
$(":checkbox").click(function() {
  if ($(this).is(":checked") && $(this).data("index") == 0) {
    // do stuff

Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

Why should you use strncpy instead of strcpy?

That depends on our requirement. For windows users

We use strncpy whenever we don't want to copy entire string or we want to copy only n number of characters. But strcpy copies the entire string including terminating null character.

These links will help you more to know about strcpy and strncpy and where we can use.

about strcpy

about strncpy

How do I navigate to another page when PHP script is done?

if ($done)
    header("Location: /url/to/the/other/page");

What does @@variable mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited.

This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels

Online SQL Query Syntax Checker

A lot of people, including me, use to test SQL.

How can I find all of the distinct file extensions in a folder hierarchy?

No need for the pipe to sort, awk can do it all:

find . -type f | awk -F. '!a[$NF]++{print $NF}'

How to get query string parameter from MVC Razor markup?

I think a more elegant solution is to use the controller and the ViewData dictionary:

public ActionResult Action(int IFRAME)
        ViewData["IsIframe"] = IFRAME == 1;
        return View();

    string classToUse = (bool)ViewData["IsIframe"] ? "iframe-page" : "";
   <div id="wrap" class='@classToUse'></div>

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)


Powershell: Get FQDN Hostname

A cleaner format FQDN remotely


Sequelize.js delete query?

Here's a ES6 using Await / Async example:

    async deleteProduct(id) {

        if (!id) {
            return {msg: 'No Id specified..', payload: 1};

        try {
            return !!await products.destroy({
                where: {
                    id: id
        } catch (e) {
            return false;


Please note that I'm using the !! Bang Bang Operator on the result of the await which will change the result into a Boolean.

How to set background color of a button in Java GUI?



To use RGB values:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }

Get text of label with jquery

Try using the html() function.


You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.

Using grep to help subset a data frame in R

You may also use the stringr package

My.Data %>% filter(str_detect(x, '^G45'))

You may not use '^' (starts with) in this case, to obtain the results you need

Best way to strip punctuation from a string

I usually use something like this:

>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
...     s= s.replace(c,"")
>>> s
'string With Punctuation'

align right in a table cell with CSS


text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.



<td class='alnright'>text to be aligned to right</td>

    .alnright { text-align: right; }

How to insert element as a first child?

Required here

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

added by

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

Why do I get the "Unhandled exception type IOException"?

Try again with this code snippet:


class IO {
    public static void main(String[] args) {    
        try {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(;    
            String userInput;    
            while ((userInput = stdIn.readLine()) != null) {
        } catch(IOException ie) {

Using try-catch-finally is better than using throws. Finding errors and debugging are easier when you use try-catch-finally.

An invalid XML character (Unicode: 0xc) was found

public String stripNonValidXMLCharacters(String in) {
    StringBuffer out = new StringBuffer(); // Used to hold the output.
    char current; // Used to reference the current character.

    if (in == null || ("".equals(in))) return ""; // vacancy test.
    for (int i = 0; i < in.length(); i++) {
        current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
        if ((current == 0x9) ||
            (current == 0xA) ||
            (current == 0xD) ||
            ((current >= 0x20) && (current <= 0xD7FF)) ||
            ((current >= 0xE000) && (current <= 0xFFFD)) ||
            ((current >= 0x10000) && (current <= 0x10FFFF)))
    return out.toString();

Boolean checking in the 'if' condition

The first one. But just another point, the following would also make your code more readable:

if (!status) {
    // do false logic
} else {
    // do true logic

Note that there are extra spaces between if and the (, and also before the else statement.


As noted by @Mudassir, if there is NO other shared code in the method using the logic, then the better style would be:

if (!status) {
    // do false logic

// do true logic

Start service in Android

Intent serviceIntent = new Intent(this,YourActivity.class);


add service in manifist

<service android:enabled="true" android:name="YourActivity.class" />

for running service on oreo and greater devices use for ground service and show notification to user

or use geofencing service for location update in background reference

Save each sheet in a workbook to separate CSV files

Please look into Von Pookie's answer, all credits to him/her.

 Sub asdf()
Dim ws As Worksheet, newWb As Workbook

Application.ScreenUpdating = False
For Each ws In Sheets(Array("EID Upload", "Wages with Locals Upload", "Wages without Local Upload"))
   Set newWb = ActiveWorkbook
   With newWb
      .SaveAs ws.Name, xlCSV
      .Close (False)
   End With
Next ws
Application.ScreenUpdating = True

End Sub

Hide Text with CSS, Best Practice?

If you're willing to accomodate this in your markup (as you are in your question with the holding the text), I'd go with whatever jQuery UI went with in their CSS helpers:

.ui-helper-hidden-accessible { 
    position: absolute !important; 
    clip: rect(1px 1px 1px 1px); 
    clip: rect(1px,1px,1px,1px); 

The image replacement techniques are good if you absolutely refuse to add extra markup for the text to be hidden in the container for the image.

Find all zero-byte files in directory and subdirectories

As addition to the answers above:

If you would like to delete those files

find $dir -size 0 -type f -delete

How to filter empty or NULL names in a QuerySet?

You can simply do this:


It's really just that simple. filter is used to match and exclude is to match everything but what it specifies. This would evaluate into SQL as NOT alias='' AND alias IS NOT NULL.

Warning: The method assertEquals from the type Assert is deprecated

You're using junit.framework.Assert instead of org.junit.Assert.

jQuery/JavaScript to replace broken images

You can use GitHub's own fetch for this:

or for Backend, a Node.js version:

  .then(function(res) {
    if (res.status == '200') {
      return image;
    } else {
      return placeholder;

Edit: This method is going to replace XHR and supposedly already has been in Chrome. To anyone reading this in the future, you may not need the aforementioned library included.

Create table with jQuery - append

Following is done for multiple file uploads using jquery:

File input button:

 <input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/> 

Displaying File name and File size in a table:

<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>

Javascript for getting the file name and file size:

function getFileSizeandName(input)
    var select = $('#uploadTable');
    var totalsizeOfUploadFiles = "";
    for(var i =0; i<input.files.length; i++)
        var filesizeInBytes = input.files[i].size; // file size in bytes
        var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
        var filename = input.files[i].name;
        totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
        //alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");               

How to create/make rounded corner buttons in WPF?

You can use attached properties for setting button border radius (also the same will work for textboxes).

Create class for attached property

public class CornerRadiusSetter
    public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);

    public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);

    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
            typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));

    public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
        Control control = sender as Control;

        if (control == null) return;

        control.Loaded -= Control_Loaded;
        control.Loaded += Control_Loaded;

    private static void Control_Loaded(object sender, EventArgs e)
        Control control = sender as Control;

        if (control == null || control.Template == null) return;


        Border border = control.Template.FindName("border", control) as Border;

        if (border == null) return;

        border.CornerRadius = GetCornerRadius(control);

Then you can use attached property syntax for multiple buttons without style duplicates:

<Button local:CornerRadiusSetter.CornerRadius="10">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="5, 0, 0, 5">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="3, 20, 8, 15">Click me!</Button>

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.


CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:


Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            html,body { width: 100%; height: 100%; }
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">

Classes vs. Functions

It depends on the scenario. If you only want to compute the age of a person, then use a function since you want to implement a single specific behaviour.

But if you want to create an object, that contains the date of birth of a person (and possibly other data), allows to modify it, then computing the age could be one of many operations related to the person and it would be sensible to use a class instead.

Classes provide a way to merge together some data and related operations. If you have only one operation on the data then using a function and passing the data as argument you will obtain an equivalent behaviour, with less complex code.

Note that a class of the kind:

class A(object):
    def __init__(self, ...):
    def a_single_method(self, ...):
        #do stuff

isn't really a class, it is only a (complicated)function. A legitimate class should always have at least two methods(without counting __init__).

View tabular file such as CSV from command line

You can install csvtool (on Ubuntu) via

sudo apt-get install csvtool

and then run:

csvtool readable filename | view -

This will make it nice and pretty inside of a read-only vim instance, even if you have some cells with very long values.

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like and

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

'mat-form-field' is not a known element - Angular 5 & Material2

When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts

Please import below:

import { MatInputModule } from '@angular/material';

Maven build debug in Eclipse

Easiest way I find is to:

  1. Right click project

  2. Debug as -> Maven build ...

  3. In the goals field put -Dmaven.surefire.debug test

  4. In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)

Set your breakpoints down and run this configuration and it should hit the breakpoint.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

If you want n bits specific then you could first create a bitmask and then AND it with your number to take the desired bits.

Simple function to create mask from bit a to bit b.

unsigned createMask(unsigned a, unsigned b)
   unsigned r = 0;
   for (unsigned i=a; i<=b; i++)
       r |= 1 << i;

   return r;

You should check that a<=b.

If you want bits 12 to 16 call the function and then simply & (logical AND) r with your number N

r = createMask(12,16);
unsigned result = r & N;

If you want you can shift the result. Hope this helps

how to do file upload using jquery serialization

You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.

    url: "ajax.php", 
    type: "POST",             
    data: new FormData('form'),
    contentType: false,       
    cache: false,             
    success: function(data) {

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How can I make my layout scroll both horizontally and vertically?

its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.


            //xml code

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:


Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
    // error handling, most likely you have to terminate the program here

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

sql: check if entry in table A exists in table B

Or if "NOT EXISTS" are not implemented

WHERE (SELECT count(*)  FROM   A WHERE  A.ID = B.ID) < 1

Two submit buttons in one form

There’s a new HTML5 approach to this, the formaction attribute:

<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>

Apparently this does not work in IE9 and earlier, but for other browsers you should be fine (see: HTML <button> formaction Attribute).

Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.

Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.

Edit: As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.

What is the difference between Views and Materialized Views in Oracle?


They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.

The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.

Materialized views

They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.

In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.

Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.

Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.

Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.

jQuery Mobile Page refresh mechanism

Please take a good look here:

$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )

$ isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?

Important: Create vs. refresh: An important distinction

Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.

For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.

$.mobile.refresh() doesn't exist i guess

So what are you using for your results? A listview? Then you can update it by doing:



Otherwise you can do:

$('#result').live("pageinit", function(){ // or pageshow
    // your dom manipulations here

Why would we call cin.clear() and cin.ignore() after reading input?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

load csv into 2D matrix with numpy for plotting

Pure numpy

numpy.loadtxt(open("test.csv", "rb"), delimiter=",", skiprows=1)

Check out the loadtxt documentation.

You can also use python's csv module:

import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:

result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")

Added Hint:

You could also use and get the associated numpy array which can be faster.

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
Can't detect type of array [Ljava.lang.Short

and you are using

not {

precondition multiple times, then you are facing an old bug:

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
    pg_class t,
    pg_class i,
    pg_index ix
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

How to install MySQLdb package? (ImportError: No module named setuptools)


$ su
$ yum install MySQL-python

and it will be installed (MySQLdb).

SQL Server FOR EACH Loop



-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date 
Declare @EndYear as int 

-- Setting the value in strat Date
select @StartYear = Value from   rat.Configuration where Name = 'REPORT_START_YEAR'; 

-- Setting the End date 
select @EndYear = Value from   rat.Configuration where Name = 'REPORT_END_YEAR'; 

-- Creating Tem table 
    with [Years] as
        --Selecting the Year
        select @StartYear [Year] 
        --doing Union 
        union all
         -- doing the loop in Years table 
         select Year+1 Year from [Years] where Year < @EndYear
    --Selecting the Year table 

How to select different app.config for several build configurations

SlowCheetah and FastKoala from the VisualStudio Gallery seem to be very good tools that help out with this problem.

However, if you want to avoid addins or use the principles they implement more extensively throughout your build/integration processes then adding this to your msbuild *proj files is a shorthand fix.

Note: this is more or less a rework of the No. 2 of @oleksii's answer.

This works for .exe and .dll projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />

This works for web projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />

Note that this step happens even before the build proper begins. The transformation of the config file happens in the project folder. So that the transformed web.config is available when you are debugging (a drawback of SlowCheetah).

Do remember that if you create the App_Config folder (or whatever you choose to call it), the various intermediate config files should have a Build Action = None, and Copy to Output Directory = Do not copy.

This combines both options into one block. The appropriate one is executed based on conditions. The TransformXml task is defined first though:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Condition="Exists('App_Config\app.Base.config')" Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
    <TransformXml Condition="Exists('App_Config\Web.Base.config')" Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
FROM partitioned WHERE seq = 1

How do I get the number of elements in a list?

And for completeness (primarily educational), it is possible without using the len() function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.

def count(list):
    item_count = 0
    for item in list[:]:
        item_count += 1
    return item_count


(The colon in list[:] is implicit and is therefore also optional.)

The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.

Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:

class MyList(object):
    def __init__(self):
        self._data = []
        self.length = 0 # length tracker that takes up memory but makes length op O(1) time

        # the implicit iterator in a list class
    def __iter__(self):
        for elem in self._data:
            yield elem

    def add(self, elem):
        self.length += 1

    def remove(self, elem):
        self.length -= 1

mylist = MyList()
print(mylist.length) # 3
print(mylist.length) # 2

Traits vs. interfaces

I think traits are useful to create classes that contain methods that can be used as methods of several different classes.

For example:

trait ToolKit
    public $errors = array();

    public function error($msg)
        $this->errors[] = $msg;
        return false;

You can have and use this "error" method in any class that uses this trait.

class Something
    use Toolkit;

    public function do_something($zipcode)
        if (preg_match('/^[0-9]{5}$/', $zipcode) !== 1)
            return $this->error('Invalid zipcode.');
        // do something here

While with interfaces you can only declare the method signature, but not its functions' code. Also, to use an interface you need to follow a hierarchy, using implements. This is not the case with traits.

It is completely different!

git ignore exception

To exclude everything in a directory, but some sub-directories, do the following:



Proper usage of Java -D command-line parameters

You're giving parameters to your program instead to Java. Use

java -Dtest="true" -jar myApplication.jar 


Consider using


to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like

System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")

is right (providing default true). A shorter possibility is


but not using double negation doesn't make it less hard to misunderstand.

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

I ran into a problem with this as well as my JUnit assertEquals were failing comparing Dates to Hibernate emitted 'java.util.Date' types (which as described in the question are really Timestamps). It turns out that by changing the mapping to 'date' rather than 'java.util.Date' Hibernate generates java.util.Date members. I am using an XML mapping file with Hibernate version 4.1.12.

This version emits 'java.util.Timestamp':

<property name="date" column="DAY" type="java.util.Date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />

This version emits 'java.util.Date':

<property name="date" column="DAY" type="date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />

Note, however, if Hibernate is used to generate the DDL, then these will generate different SQL types (Date for 'date' and Timestamp for 'java.util.Date').

Running python script inside ipython

How to run a script in Ipython

import os

That should do it

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long and long int are identical. So are long long and long long int. In both cases, the int is optional.

As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that long long is at least as wide as long.

The controlling parts of the standard (C++11, but this has been around for a long time) are, for one, 3.9.1 Fundamental types, section 2 (a later section gives similar rules for the unsigned integral types):

There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.

There's also a table 9 in Simple type specifiers, which shows the "mappings" of the specifiers to actual types (showing that the int is optional), a section of which is shown below:

Specifier(s)         Type
-------------    -------------
long long int    long long int
long long        long long int
long int         long int
long             long int

Note the distinction there between the specifier and the type. The specifier is how you tell the compiler what the type is but you can use different specifiers to end up at the same type.

Hence long on its own is neither a type nor a modifier as your question posits, it's simply a specifier for the long int type. Ditto for long long being a specifier for the long long int type.

Although the C++ standard itself doesn't specify the minimum ranges of integral types, it does cite C99, in 1.2 Normative references, as applying. Hence the minimal ranges as set out in C99 Sizes of integer types <limits.h> are applicable.

In terms of long double, that's actually a floating point value rather than an integer. Similarly to the integral types, it's required to have at least as much precision as a double and to provide a superset of values over that type (meaning at least those values, not necessarily more values).

javascript get child by id

In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

function test(el){
  el.querySelector("#child").style.display = "none";

For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

Is there a kind of Firebug or JavaScript console debug for Android?

I have recently written a tool for showing console logs in a movable/resizable "window" (actually a div). It provides similar functionality to Firebug's console but you can see it over your page on a tablet. Tablet/Smartphone/Phablet Debug Console

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

What is a Windows Handle?

A handle is like a primary key value of a record in a database.

edit 1: well, why the downvote, a primary key uniquely identifies a database record, and a handle in the Windows system uniquely identifies a window, an opened file, etc, That's what I'm saying.

How to escape a single quote inside awk

For small scripts an optional way to make it readable is to use a variable like this:

awk -v fmt="'%s'\n" '{printf fmt, $1}'

I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

All above answer is correct but in my case There is no lib folder available in my app directory and I am trying to call below line in app gradle file

 compile fileTree(include: ['*.jar'], dir: 'libs')

So make sure what ever dependency you declare in gradle file in available for app

Enter export password to generate a P12 certificate

MacOS High Sierra is very crazy to update openssl command suddenly.

Possible in last month:

$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts
MAC verified OK

But now:

$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts -password pass:
MAC verified OK

How to split and modify a string in NodeJS?

Use split and map function:

var str = "123, 124, 234,252";
var arr = str.split(",");
arr = (val) { return +val + 1; });

Notice +val - string is casted to a number.

Or shorter:

var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });

edit 2015.07.29

Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:

var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(function (val) {_x000D_
  return Number(val) + 1;_x000D_

edit 2017.03.09

ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:

var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(val => Number(val) + 1);_x000D_

XPath - Difference between node() and text()

Select the text of all items under produce:


Select all the manager nodes in all departments:


Convert a python UTC datetime to a local datetime using only python standard library?

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

How to select the Date Picker In Selenium WebDriver

Do not inject javascript. That is a bad practice.

I would model the DatePicker as an element like textbox / select as shown below.

For the detailed answer - check here-

public class DatePicker {

    private static final String dateFormat = "dd MMM yyyy";

    @FindBy(css = "a.ui-datepicker-prev")
    private WebElement prev;

    @FindBy(css = "a.ui-datepicker-next")
    private WebElement next;

    @FindBy(css = "div.ui-datepicker-title")
    private WebElement curDate;

    @FindBy(css = "a.ui-state-default")
    private List < WebElement > dates;

    public void setDate(String date) {

        long diff = this.getDateDifferenceInMonths(date);
        int day = this.getDay(date);

        WebElement arrow = diff >= 0 ? next : prev;
        diff = Math.abs(diff);

        //click the arrows
        for (int i = 0; i < diff; i++)

        //select the date
            .filter(ele - > Integer.parseInt(ele.getText()) == day)
            .ifPresent(ele - >;


    private int getDay(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return dpToDate.getDayOfMonth();

    private long getDateDifferenceInMonths(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpCurDate = LocalDate.parse("01 " + this.getCurrentMonthFromDatePicker(), dtf);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return YearMonth.from(dpCurDate).until(dpToDate, ChronoUnit.MONTHS);

    private String getCurrentMonthFromDatePicker() {
        return this.curDate.getText();


is there a 'block until condition becomes true' function in java?

Similar to EboMike's answer you can use a mechanism similar to wait/notify/notifyAll but geared up for using a Lock.

For example,

public void doSomething() throws InterruptedException {
    try {
        condition.await(); // releases lock and waits until doSomethingElse is called
    } finally {

public void doSomethingElse() {
    try {
    } finally {

Where you'll wait for some condition which is notified by another thread (in this case calling doSomethingElse), at that point, the first thread will continue...

Using Locks over intrinsic synchronisation has lots of advantages but I just prefer having an explicit Condition object to represent the condition (you can have more than one which is a nice touch for things like producer-consumer).

Also, I can't help but notice how you deal with the interrupted exception in your example. You probably shouldn't consume the exception like this, instead reset the interrupt status flag using Thread.currentThread().interrupt.

This because if the exception is thrown, the interrupt status flag will have been reset (it's saying "I no longer remember being interrupted, I won't be able to tell anyone else that I have been if they ask") and another process may rely on this question. The example being that something else has implemented an interruption policy based on this... phew. A further example might be that your interruption policy, rather that while(true) might have been implemented as while(!Thread.currentThread().isInterrupted() (which will also make your code be more... socially considerate).

So, in summary, using Condition is rougly equivalent to using wait/notify/notifyAll when you want to use a Lock, logging is evil and swallowing InterruptedException is naughty ;)

How do you create a Spring MVC project in Eclipse?

Download Spring STS (SpringSource Tool Suite) and choose Spring Template Project from the Dashboard. This is the easiest way to get a preconfigured spring mvc project, ready to go.

How to pass table value parameters to stored procedure from .net code

Use this code to create suitable parameter from your type:

private SqlParameter GenerateTypedParameter(string name, object typedParameter)
    DataTable dt = new DataTable();

    var properties = typedParameter.GetType().GetProperties().ToList();
    properties.ForEach(p =>
        dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
    var row = dt.NewRow();
    properties.ForEach(p => { row[p.Name] = (p.GetValue(typedParameter) ?? DBNull.Value); });

    return new SqlParameter
        Direction = ParameterDirection.Input,
        ParameterName = name,
        Value = dt,
        SqlDbType = SqlDbType.Structured

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store
GET           /users/{user}               show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}


You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation

Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
        // GET request to index

    public function getShow($id)
        // get request to 'users/show/{id}'

    public function postStore()
        // POST request to 'users/store'


Implicit Controller documentation

It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

How to execute an SSIS package from .NET?

So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.

Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.

Below is a blog for more details..

Happy coding.. :)

Thanks, Ayan

How do I center an anchor element in CSS?

Two options, that have different uses:


<a class="example" href="">example</a>


.example { text-align: center; }


.example { display:block; width:100px; margin:0 auto;}

How to limit text width

You can apply css like this:

div {
   word-wrap: break-word;
   width: 100px;

Usually browser does not break words, but word-wrap: break-word; will force it to break words too.


More info about word-wrap

How to import functions from different js file in a Vue+webpack+vue-loader project

After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?

BUT there was an import that was screwing the rest of it up:

Use require in .vue files

  var mylib = require('./mylib');
  export default {

Exports in mylib

 exports.myfunc = () => {....}

Avoid import

The actual issue in my case (which I didn't think was relevant!) was that mylib.js was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack but anyway I had:

import models from './model/models'
import axios from 'axios'

This works so long as I'm not using mylib in a .vue component. However as soon as I use mylib there, the error described in this issue arises.

I changed to:

let models = require('./model/models');
let axios = require('axios');

And all works as expected.