Programs & Examples On #Hungarian notation

Hungarian notation is a language-independent naming convention in which an identifier's prefix indicates its type. Examples include iCustomerId, sFirstName, etc.

What does `m_` variable prefix mean?

To complete the current answers and as the question is not language specific, some C-project use the prefix m_ to define global variables that are specific to a file - and g_ for global variables that have a scoped larger than the file they are defined.
In this case global variables defined with prefix m_ should be defined as static.

See EDK2 (a UEFI Open-Source implementation) coding convention for an example of project using this convention.

Why shouldn't I use "Hungarian Notation"?

I've always thought that a prefix or two in the right place wouldn't hurt. I think if I can impart something useful, like "Hey this is an interface, don't count on specific behaviour" right there, as in IEnumerable, I oughtta do it. Comment can clutter things up much more than just a one or two character symbol.

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

Can't use modulus on doubles?

Use fmod() from <cmath>. If you do not want to include the C header file:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

Assign pandas dataframe column dtypes

Since 0.17, you have to use the explicit conversions:

pd.to_datetime, pd.to_timedelta and pd.to_numeric

(As mentioned below, no more "magic", convert_objects has been deprecated in 0.17)

df = pd.DataFrame({'x': {0: 'a', 1: 'b'}, 'y': {0: '1', 1: '2'}, 'z': {0: '2018-05-01', 1: '2018-05-02'}})

df.dtypes

x    object
y    object
z    object
dtype: object

df

   x  y           z
0  a  1  2018-05-01
1  b  2  2018-05-02

You can apply these to each column you want to convert:

df["y"] = pd.to_numeric(df["y"])
df["z"] = pd.to_datetime(df["z"])    
df

   x  y          z
0  a  1 2018-05-01
1  b  2 2018-05-02

df.dtypes

x            object
y             int64
z    datetime64[ns]
dtype: object

and confirm the dtype is updated.


OLD/DEPRECATED ANSWER for pandas 0.12 - 0.16: You can use convert_objects to infer better dtypes:

In [21]: df
Out[21]: 
   x  y
0  a  1
1  b  2

In [22]: df.dtypes
Out[22]: 
x    object
y    object
dtype: object

In [23]: df.convert_objects(convert_numeric=True)
Out[23]: 
   x  y
0  a  1
1  b  2

In [24]: df.convert_objects(convert_numeric=True).dtypes
Out[24]: 
x    object
y     int64
dtype: object

Magic! (Sad to see it deprecated.)

SQLDataReader Row Count

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

How do I get the last character of a string using an Excel function?

No need to apologize for asking a question! Try using the RIGHT function. It returns the last n characters of a string.

=RIGHT(A1, 1)

How do you run a .bat file from PHP?

For anyone who needs to run a program in the background "without PHP waiting for it to finish" do this:

 pclose(popen("start /B ".$cmd, "r")); 

where $cmd is the string command for the program that you need to run (e.g. $cmd can equal notepad.exe or node Path\to\server.js).

Source: https://www.php.net/manual/en/function.exec.php (see Arno van den Brink's note in the section titled "User Contributed Notes").

Requested registry access is not allowed

I was trying the verb = "runas", but I still was getting UnauthorizedAccessException when trying to update registry value. Turned out it was due to not opening the subkey with writeable set to true.

Registry.OpenSubKey("KeyName", true);

Cannot write to Registry Key, getting UnauthorizedAccessException

Initial size for the ArrayList

Right now there are no elements in your list so you cannot add to index 5 of the list when it does not exist. You are confusing the capacity of the list with its current size.

Just call:

arr.add(10)

to add the Integer to your ArrayList

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

ASP.NET 2.0 - How to use app_offline.htm

I ran into an issue very similar to the original question that took me a little while to resolve.

Just incase anyone else is working on an MVC application and finds their way into this thread, make sure that you have a wildcard mapping to the appropriate .Net aspnet_isapi.dll defined. As soon as I did this, my app_offline.htm started behaving as expected.


IIS 6 Configuration Steps

On IIS Application Properties, select virtual Directory tab.

Under Application Settings, click the Configuration button.

Under Wildcard application maps, click the Insert button.

Enter C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll, click OK.

How should I declare default values for instance variables in Python?

Using class members to give default values works very well just so long as you are careful only to do it with immutable values. If you try to do it with a list or a dict that would be pretty deadly. It also works where the instance attribute is a reference to a class just so long as the default value is None.

I've seen this technique used very successfully in repoze which is a framework that runs on top of Zope. The advantage here is not just that when your class is persisted to the database only the non-default attributes need to be saved, but also when you need to add a new field into the schema all the existing objects see the new field with its default value without any need to actually change the stored data.

I find it also works well in more general coding, but it's a style thing. Use whatever you are happiest with.

How to delete a record in Django models?

if you want to delete one instance then write the code

entry= Account.objects.get(id= 5)
entry.delete()

if you want to delete all instance then write the code

entries= Account.objects.all()
entries.delete()

How do I conditionally add attributes to React components?

In React you can conditionally render Components, but also their attributes, like props, className, id, and more.

In React it's very good practice to use the ternary operator which can help you conditionally render Components.

An example also shows how to conditionally render Component and its style attribute.

Here is a simple example:

_x000D_
_x000D_
class App extends React.Component {_x000D_
  state = {_x000D_
    isTrue: true_x000D_
  };_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {this.state.isTrue ? (_x000D_
          <button style={{ color: this.state.isTrue ? "red" : "blue" }}>_x000D_
            I am rendered if TRUE_x000D_
          </button>_x000D_
        ) : (_x000D_
          <button>I am rendered if FALSE</button>_x000D_
        )}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Regex match text between tags

/<b>(.*?)<\/b>/g

Regular expression visualization

Add g (global) flag after:

/<b>(.*?)<\/b>/g.exec(str)
             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.

The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.

tl;dr: There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors> section from the WCF service's web.config file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.

EDIT:

Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null!) or the URL is incorrect.

"401 Unauthorized" on a directory

You need to check the folder permissions on your server and check that the account that you are using to run your application has access to that folder.

How do I uninstall a package installed using npm link?

The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global flag needs to be provided.

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

sudo npm rm --global foo

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

npm ls --global foo

How to remove trailing whitespaces with sed?

Thanks to codaddict for suggesting the -i option.

The following command solves the problem on Snow Leopard

sed -i '' -e's/[ \t]*$//' "$1"

Preloading @font-face fonts?

There are a few techniques for "preloading" here: http://paulirish.com/2009/fighting-the-font-face-fout/

Mostly tricking the browser into downloading the file as fast as possible..

You can also deliver it as a data-uri, which helps a lot. and also you could hide the page content and show it when its ready.

Angularjs -> ng-click and ng-show to show a div

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
            //This will hide the DIV by default.
            $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Show Hide DIV" ng-click="ShowHide()" />
        <br />
        <br />
        <div ng-show = "IsVisible">My DIV</div>
    </div>
</body>
</html>

EXAMPLE : - http://jsfiddle.net/mafais/4WK7R/380/

Convert List into Comma-Separated String

You can use String.Join method to combine items:

var str = String.Join(",", lst);

How to get the anchor from the URL using jQuery?

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

jQuery UI DatePicker to show month year only

Marked answer work!! but Not in my case there's more then one datepicker and only want to implement on particular datepicker

So I use instance of dp and find datepicker Div and add hide class

Here's Code

<style>
    .hide-day-calender .ui-datepicker-calendar{
        display:none;
    }
</style>

<script>
        $('#dpMonthYear').datepicker({ 
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function (dateText, inst) { 
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            },
            beforeShow: function (elem,dp) {
                $(dp.dpDiv).addClass('hide-day-calender'); //here a change
            }
        });
</script>

Note: You can not target .ui-datepicker-calendar and set css, because it will constantly rendering while selection/changes

How to recover a dropped stash in Git?

You can list all unreachable commits by writing this command in terminal -

git fsck --unreachable

Check unreachable commit hash -

git show hash

Finally apply if you find the stashed item -

git stash apply hash

pip broke. how to fix DistributionNotFound error?

I replaced 0.8.1 in 0.8.2 in /usr/local/bin/pip and everything worked again.

__requires__ = 'pip==0.8.2'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==0.8.2', 'console_scripts', 'pip')()
    )

I installed pip through easy_install which probably caused me this headache. I think this is how you should do it nowadays..

$ sudo apt-get install python-pip python-dev build-essential 
$ sudo pip install --upgrade pip 
$ sudo pip install --upgrade virtualenv

Delete keychain items when an app is uninstalled

For users looking for a Swift 3.0 version of @amro's answer:

let userDefaults = UserDefaults.standard

if !userDefaults.bool(forKey: "hasRunBefore") {
     // Remove Keychain items here

     // Update the flag indicator
     userDefaults.set(true, forKey: "hasRunBefore")
}

*note that synchronize() function is deprecated

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

I'm hoping you are having the same problem that I had... my issue was simple: Make a fixed textarea with locked percentages inside the container (I'm new to CSS/JS/HTML, so bear with me, if I don't get the lingo correct) so that no matter the device it's displaying on, the box filling the container (the table cell) takes up the correct amount of space. Here's how I solved it:

<table width=100%>
    <tr class="idbbs">
        B.S.:
    </tr></br>
    <tr>
        <textarea id="bsinpt"></textarea>
    </tr>
</table>

Then CSS Looks like this...

#bsinpt
{
    color: gainsboro;
    float: none;
    background: black;
    text-align: left;
    font-family: "Helvetica", "Tahoma", "Verdana", "Arial Black", sans-serif;
    font-size: 100%;
  position: absolute;
  min-height: 60%;
  min-width: 88%;
  max-height: 60%;
  max-width: 88%;
  resize: none;
    border-top-color: lightsteelblue;
    border-top-width: 1px;
    border-left-color: lightsteelblue;
    border-left-width: 1px;
    border-right-color: lightsteelblue;
    border-right-width: 1px;
    border-bottom-color: lightsteelblue;
    border-bottom-width: 1px;
}

Sorry for the sloppy code block here, but I had to show you what's important and I don't know how to insert quoted CSS code on this website. In any case, to ensure you see what I'm talking about, the important CSS is less indented here...

What I then did (as shown here) is very specifically tweak the percentages until I found the ones that worked perfectly to fit display, no matter what device screen is used.

Granted, I think the "resize: none;" is overkill, but better safe than sorry and now the consumers will not have anyway to resize the box, nor will it matter what device they are viewing it from.

It works great.

Android Image View Pinch Zooming

Add bellow line in build.gradle:

compile 'com.commit451:PhotoView:1.2.4'

or

compile 'com.github.chrisbanes:PhotoView:1.3.0'

In Java file:

PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();

Call to undefined method mysqli_stmt::get_result

With PHP version 7.2 I just used nd_mysqli instead of mysqli and it worked as expected.

Steps to enable it into godaddy hosting server-

  1. Login to cpanel.
  2. Click on "Select PHP version".
  3. As provided the snapshot of the latest configurations uncheck "mysqli" and enable "nd_mysqli".

enter image description here

Can I make 'git diff' only the line numbers AND changed file names?

The cleanest output, i.e. file names/paths only, comes with

git diff-tree --no-commit-id --name-only -r

HTH

Show diff between commits

Let's say you have one more commit at the bottom (oldest), then this becomes pretty easy:

commit dj374
made changes

commit y4746
made changes

commit k73ud
made changes

commit oldestCommit
made changes

Now, using below will easily server the purpose.

git diff k73ud oldestCommit

Get first key in a (possibly) associative array?

A one-liner:

$array = array('key1'=>'value1','key2'=>'value2','key3'=>'key3');
echo key( array_slice( $array, 0, 1, true ) );

# echos 'key1'

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

How to run DOS/CMD/Command Prompt commands from VB.NET?

You could try this method:

Public Class MyUtilities
    Shared Sub RunCommandCom(command as String, arguments as String, permanent as Boolean) 
        Dim p as Process = new Process() 
        Dim pi as ProcessStartInfo = new ProcessStartInfo() 
        pi.Arguments = " " + if(permanent = true, "/K" , "/C") + " " + command + " " + arguments 
        pi.FileName = "cmd.exe" 
        p.StartInfo = pi 
        p.Start() 
    End Sub
End Class

call, for example, in this way:

MyUtilities.RunCommandCom("DIR", "/W", true)

EDIT: For the multiple command on one line the key are the & | && and || command connectors

  • A & B → execute command A, then execute command B.
  • A | B → execute command A, and redirect all it's output into the input of command B.
  • A && B → execute command A, evaluate the errorlevel after running Command A, and if the exit code (errorlevel) is 0, only then execute command B.
  • A || B → execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute command B.

What are some resources for getting started in operating system development?

Check out the Managed Operating System Alliance (MOSA) Project at www.mosa-project.org. They are designing an AOT/JIT compiler and fully managed operating system in C#. Some of the developers are from the inactive SharpOS project.

Eclipse/Maven error: "No compiler is provided in this environment"

I had a problem with Eclipse Neon where the workspace default did not actually change even though I added the correct location under Preferences->Java->Installed JREs. This was in a new workspace I created to work on a code branch; it was originally set to the JRE location rather than the JDK. Yet even after changing the preferences, I could build with the command line, yet building in Eclipse produced the no compiler error. Please see

Maven Package Compilation Error

for my answer on which Eclipse configuration file(s) had to be manually edited to make Eclipse recognize the correct workspace default. I still have no idea why the preferences setting did not carry through to the new workspace's configuration.

Node.js for() loop returning the same values at each loop

  for(var i = 0; i < BoardMessages.length;i++){
        (function(j){
            console.log("Loading message %d".green, j);
            htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
        })(i);
  }

That should work; however, you should never create a function in a loop. Therefore,

  for(var i = 0; i < BoardMessages.length;i++){
        composeMessage(BoardMessages[i]);
  }

  function composeMessage(message){
      console.log("Loading message %d".green, message);
      htmlMessageboardString += MessageToHTMLString(message);
  }

Android Activity as a dialog

Some times you can get the Exception which is given below

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

So for resolving you can use simple solution

add theme of you activity in manifest as dialog for appCompact.

android:theme="@style/Theme.AppCompat.Dialog"

It can be helpful for somebody.

Why do we use $rootScope.$broadcast in AngularJS?

What does $rootScope.$broadcast do?

It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)

Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .

refer for examples :- http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Node.js - get raw request body using Express

This is a variation on hexacyanide's answer above. This middleware also handles the 'data' event but does not wait for the data to be consumed before calling 'next'. This way both this middleware and bodyParser may coexist, consuming the stream in parallel.

app.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf8');

  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });

  next();
});
app.use(express.bodyParser());

Sending command line arguments to npm script

If you want to pass arguments to the middle of an npm script, as opposed to just having them appended to the end, then inline environment variables seem to work nicely:

"scripts": {
  "dev": "BABEL_ARGS=-w npm run build && cd lib/server && nodemon index.js",
  "start": "npm run build && node lib/server/index.js",
  "build": "mkdir -p lib && babel $BABEL_ARGS -s inline --stage 0 src -d lib",
},

Here, npm run dev passes the -w watch flag to babel, but npm run start just runs a regular build once.

How to delete the top 1000 rows from a table using Sql Server 2008?

SET ROWCOUNT 1000;

DELETE FROM [MyTable] WHERE .....

How to retrieve current workspace using Jenkins Pipeline Groovy script?

There is no variable included for that yet, so you have to use shell-out-read-file method:

sh 'pwd > workspace'
workspace = readFile('workspace').trim()

Or (if running on master node):

workspace = pwd()

How can I have linebreaks in my long LaTeX equations?

I used the \begin{matrix}

\begin{equation}
\begin{matrix}
    line_1 \\ 
    line_2 \\ 
    line_3
\end{matrix}
\end{equation}

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

Checkout another branch when there are uncommitted changes on the current branch

In case you don't want this changes to be committed at all do git reset --hard.

Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.

What killed my process and why?

This looks like a good article on the subject: Taming the OOM killer.

The gist is that Linux overcommits memory. When a process asks for more space, Linux will give it that space, even if it is claimed by another process, under the assumption that nobody actually uses all of the memory they ask for. The process will get exclusive use of the memory it has allocated when it actually uses it, not when it asks for it. This makes allocation quick, and might allow you to "cheat" and allocate more memory than you really have. However, once processes start using this memory, Linux might realize that it has been too generous in allocating memory it doesn't have, and will have to kill off a process to free some up. The process to be killed is based on a score taking into account runtime (long-running processes are safer), memory usage (greedy processes are less safe), and a few other factors, including a value you can adjust to make a process less likely to be killed. It's all described in the article in a lot more detail.

Edit: And here is another article that explains pretty well how a process is chosen (annotated with some kernel code examples). The great thing about this is that it includes some commentary on the reasoning behind the various badness() rules.

Find a string between 2 known values

    public string between2finer(string line, string delimiterFirst, string delimiterLast)
    {
        string[] splitterFirst = new string[] { delimiterFirst };
        string[] splitterLast = new string[] { delimiterLast };
        string[] splitRes;
        string buildBuffer;
        splitRes = line.Split(splitterFirst, 100000, System.StringSplitOptions.RemoveEmptyEntries);
        buildBuffer = splitRes[1];
        splitRes = buildBuffer.Split(splitterLast, 100000, System.StringSplitOptions.RemoveEmptyEntries);
        return splitRes[0];
    }


    private void button1_Click(object sender, EventArgs e)
    {
        string manyLines = "Received: from exim by isp2.ihc.ru with local (Exim 4.77) \nX-Failed-Recipients: [email protected]\nFrom: Mail Delivery System <[email protected]>";
        MessageBox.Show(between2finer(manyLines, "X-Failed-Recipients: ", "\n"));
    }

Create a OpenSSL certificate on Windows

Consider using certificate depot web app to easily create private key and certificate based on it: http://www.cert-depot.com/

It can also create a PFX for you.

Disclaimer: I am the creator of certificate depot.

Copy rows from one Datatable to another DataTable?

For those who want single command SQL query for that:

INSERT INTO TABLE002 
(COL001_MEM_ID, COL002_MEM_NAME, COL002_MEM_ADD, COL002_CREATE_USER_C, COL002_CREATE_S)
SELECT COL001_MEM_ID, COL001_MEM_NAME, COL001_MEM_ADD, COL001_CREATE_USER_C, COL001_CREATE_S
FROM TABLE001;

This query will copy data from TABLE001 to TABLE002 and we assume that both columns had different column names.

Column names are mapped one-to-one like:

COL001_MEM_ID -> COL001_MEM_ID

COL001_MEM_NAME -> COL002_MEM_NAME

COL001_MEM_ADD -> COL002_MEM_ADD

COL001_CREATE_USER_C -> COL002_CREATE_USER_C

COL002_CREATE_S -> COL002_CREATE_S

You can also specify where clause, if you need some condition.

Android ImageView's onClickListener does not work

For inner classes to pass the reference of activity, I usually create a reference of activity in onCreate() and make it as a member. As inner classes have access to members of parent class you can get hold of your activity and thus its context:

class MyClass extends Activity{
    private Activity thisActivity;
    @Override
protected void onCreate(Bundle savedInstanceState) {
            thisActivity = this;
    }
}

Hope that helps.

Laravel Blade html image

you can Using asset() you can directly access to the image folder.

<img src="{{asset('img/stuvi-logo.png')}}" alt="logo" class="img-size-50 mr-3 img-circle">

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

Deck of cards JAVA

I think the solution is just as simple as this:

Card temp = deck[cardAindex];
deck[cardAIndex]=deck[cardBIndex]; 
deck[cardBIndex]=temp;

MySQL Query GROUP BY day / month / year

If you want to get a monthly statistics with row counts per month of each year ordered by latest month, then try this:

SELECT count(id),
      YEAR(record_date),
      MONTH(record_date) 
FROM `table` 
GROUP BY YEAR(record_date),
        MONTH(record_date) 
ORDER BY YEAR(record_date) DESC,
        MONTH(record_date) DESC

Change the value in app.config file dynamically

Expanding on Adis H's example to include the null case (got bit on this one)

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["HostName"] != null)
                config.AppSettings.Settings["HostName"].Value = hostName;
            else                
                config.AppSettings.Settings.Add("HostName", hostName);                
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

Add padding on view programmatically

To answer your second question:

view.setPadding(0,padding,0,0);

like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);

Hope that helps!

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

How to call a parent class function from derived class function?

Call the parent method with the parent scope resolution operator.

Parent::method()

class Primate {
public:
    void whatAmI(){
        cout << "I am of Primate order";
    }
};

class Human : public Primate{
public:
    void whatAmI(){
        cout << "I am of Human species";
    }
    void whatIsMyOrder(){
        Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
    }
};

Is there an arraylist in Javascript?

Just use array.push(something);. Javascript arrays are like ArrayLists in this respect - they can be treated like they have a flexible length (unlike java arrays).

Load a bitmap image into Windows Forms using open file dialog

PictureBox.Image is a property, not a method. You can set it like this:

PictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);

Check if a class is derived from a generic class

(Reposted due to a massive rewrite)

JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.

TIP:

If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:

typeof(Test).IsSubclassOf(typeof(GenericClassBase))

IsSubclassOf()

My testing indicates that IsSubclassOf() does not work on parameterless generic types such as

typeof(GenericClass<>)

whereas it will work with

typeof(GenericClass<SomeType>)

Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:

typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))

The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.


Thoughts on the "is" operator

At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.

The "is" operator will test the entire inheritance chain, including interfaces.

So, given an instance of any object, the following method will do the trick:

bool IsTypeof<T>(object t)
{
    return (t is T);
}

This is sort of redundant, but I figured I would go ahead and visualize it for everybody.

Given

var t = new Test();

The following lines of code would return true:

bool test1 = IsTypeof<GenericInterface<SomeType>>(t);

bool test2 = IsTypeof<GenericClass<SomeType>>(t);

bool test3 = IsTypeof<Test>(t);

On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:

bool IsTypeofGenericClass<SomeType>(object t)
{
    return (t is GenericClass<SomeType>);
}

Then you would test like this:

bool test1 = IsTypeofGenericClass<SomeType>(t);

In c, in bool, true == 1 and false == 0?

More accurately anything that is not 0 is true.

So 1 is true, but so is 2, 3 ... etc.

How to compare variables to undefined, if I don’t know whether they exist?

if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...

Add centered text to the middle of a <hr/>-like line

You can use the CSS flex property

HTML

<div class="hrtext">
  <div class="hrbefore">
    <hr>
  </div>
  <div class="hrcontent">
    <h2>TABLE OF CONTENT</h2>
  </div>
  <div class="hrafter">
    <hr>
  </div>
</div>

CSS

.hrtext{
    display:flex;
    align-items:center;
}
.hrbefore,.hrafter{
    flex:auto;
}
.hrcontent{
    text-align:center;
}

How to do this in Laravel, subquery where in

Have a look at the advanced wheres documentation for Fluent: http://laravel.com/docs/queries#advanced-wheres

Here's an example of what you're trying to achieve:

DB::table('users')
    ->whereIn('id', function($query)
    {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

This will produce:

select * from users where id in (
    select 1 from orders where orders.user_id = users.id
)

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Convert nullable bool? to bool

The easiest way is to use the null coalescing operator: ??

bool? x = ...;
if (x ?? true) { 

}

The ?? with nullable values works by examining the provided nullable expression. If the nullable expression has a value the it's value will be used else it will use the expression on the right of ??

Cannot use object of type stdClass as array?

As the Php Manual say,

print_r — Prints human-readable information about a variable

When we use json_decode();, we get an object of type stdClass as return type. The arguments, which are to be passed inside of print_r() should either be an array or a string. Hence, we cannot pass an object inside of print_r(). I found 2 ways to deal with this.

  1. Cast the object to array.
    This can be achieved as follows.

    $a = (array)$object;
    
  2. By accessing the key of the Object
    As mentioned earlier, when you use json_decode(); function, it returns an Object of stdClass. you can access the elements of the object with the help of -> Operator.

    $value = $object->key;
    

One, can also use multiple keys to extract the sub elements incase if the object has nested arrays.

$value = $object->key1->key2->key3...;

Their are other options to print_r() as well, like var_dump(); and var_export();

P.S : Also, If you set the second parameter of the json_decode(); to true, it will automatically convert the object to an array();
Here are some references:
http://php.net/manual/en/function.print-r.php
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.var-export.php

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Java out.println() how is this possible?

@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

Why SpringMVC Request method 'GET' not supported?

if You are using browser it default always works on get, u can work with postman tool,otherwise u can change it to getmapping.hope this will works

Find package name for Android apps to use Intent to launch Market app from web

Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >

Find (and kill) process locking port 3000 on Mac

Find:

sudo lsof -i :3000

Kill:

kill -9 <PID>

Converting from byte to int in java

Your array is of byte primitives, but you're trying to call a method on them.

You don't need to do anything explicit to convert a byte to an int, just:

int i=rno[0];

...since it's not a downcast.

Note that the default behavior of byte-to-int conversion is to preserve the sign of the value (remember byte is a signed type in Java). So for instance:

byte b1 = -100;
int i1 = b1;
System.out.println(i1); // -100

If you were thinking of the byte as unsigned (156) rather than signed (-100), as of Java 8 there's Byte.toUnsignedInt:

byte b2 = -100; // Or `= (byte)156;`
int = Byte.toUnsignedInt(b2);
System.out.println(i2); // 156

Prior to Java 8, to get the equivalent value in the int you'd need to mask off the sign bits:

byte b2 = -100; // Or `= (byte)156;`
int i2 = (b2 & 0xFF);
System.out.println(i2); // 156

Just for completeness #1: If you did want to use the various methods of Byte for some reason (you don't need to here), you could use a boxing conversion:

Byte b = rno[0]; // Boxing conversion converts `byte` to `Byte`
int i = b.intValue();

Or the Byte constructor:

Byte b = new Byte(rno[0]);
int i = b.intValue();

But again, you don't need that here.


Just for completeness #2: If it were a downcast (e.g., if you were trying to convert an int to a byte), all you need is a cast:

int i;
byte b;

i = 5;
b = (byte)i;

This assures the compiler that you know it's a downcast, so you don't get the "Possible loss of precision" error.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

NavigationBar bar, tint, and title text color in iOS 8

In Swift5 and Xcode 10

self.navigationItem.title = "your name"
let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes

A terminal command for a rooted Android to remount /System as read/write

You can run the mount command without parameter in order to get partition information before constructing your mount command. Here is an example of the mount command without parameter outputed from my HTC Hero.

$ mount
mount
rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock3 /system yaffs2 rw 0 0
/dev/block/mtdblock5 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock4 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:1 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=
1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,s
hortname=mixed,utf8,errors=remount-ro 0 0

In vb.net, how to get the column names from a datatable

Look at

For Each c as DataColumn in dt.Columns
  '... = c.ColumnName
Next

or:

dt.GetDataTableSchema(...)

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

Uploading an Excel sheet and importing the data into SQL Server database

A proposed solution will be:   


protected void Button1_Click(object sender, EventArgs e)
{
        try
        {
            CreateXMLFile();



        SqlConnection con = new SqlConnection(constring);
        con.Open();

        SqlCommand cmd = new SqlCommand("bulk_in", con);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@account_det", sw_XmlString.ToString ());

       int i= cmd.ExecuteNonQuery();
            if(i>0)
            {
                Label1.Text = "File Upload successfully";
            }
            else
            {
                Label1.Text = "File Upload unsuccessfully";
                return;

            }


        con.Close();
            }
        catch(SqlException ex)
        {
            Label1.Text = ex.Message.ToString();
        }




    }
     public void CreateXMLFile()
        {

          try
            {
                M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                fileExtn = Path.GetExtension(M_Filepath);
                strGuid = System.Guid.NewGuid().ToString();
                fNameArray = M_Filepath.Split('.');
                fName = fNameArray[0];

                xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
                 fileName =  xlRptName.Trim()  + fileExtn.Trim() ;



                 FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);



                strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
                if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
                {
                    Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
                }
               FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
               lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
               if (strFileName == "DEMO.XLS")
                {

                    strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";

                } 

                if (strFileName == "DEMO.XLSX")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";

                }

                strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";



                OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);

                mydata.TableMappings.Add("Table", "arul");
                mydata.Fill(dsExcl);
                dsExcl.DataSetName = "DocumentElement";
                intRowCnt = dsExcl.Tables[0].Rows.Count;
                intColCnt = dsExcl.Tables[0].Rows.Count;

                if(intRowCnt <1)
                {

                    Label1.Text = "No records in Excel File";
                    return;
                }
                if  (dsExcl==null)
                {

                }
                else
                    if(dsExcl.Tables[0].Rows.Count >= 1000 )
                    {

                        Label1.Text = "Excel data must be in less than 1000  ";
                    }


                for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
                {

                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Name should not be empty";
                        return;

                    }
                    else
                    {
                        strValid = "";
                    }



                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Mobile_num should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }

                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Account_number should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }





                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Amount should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }



                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "date_a2 should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }
                }


            }
         catch 
            {

            }

         try
         {
             if(dsExcl.Tables[0].Rows.Count >0)
             {

                 dr = dsExcl.Tables[0].Rows[0];
             }
             dsExcl.Tables[0].TableName = "arul";
             dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);

         }
         catch
         {

         }
}`enter code here`

Read a variable in bash with a default value

I found this question, looking for a way to present something like:

Something interesting happened.  Proceed [Y/n/q]:

Using the above examples I deduced this:-

echo -n "Something interesting happened.  "
DEFAULT="y"
read -e -p "Proceed [Y/n/q]:" PROCEED
# adopt the default, if 'enter' given
PROCEED="${PROCEED:-${DEFAULT}}"
# change to lower case to simplify following if
PROCEED="${PROCEED,,}"
# condition for specific letter
if [ "${PROCEED}" == "q" ] ; then
  echo "Quitting"
  exit
# condition for non specific letter (ie anything other than q/y)
# if you want to have the active 'y' code in the last section
elif [ "${PROCEED}" != "y" ] ; then
  echo "Not Proceeding"
else
  echo "Proceeding"
  # do proceeding code in here
fi

Hope that helps someone to not have to think out the logic, if they encounter the same problem

how to overlap two div in css?

See demo here you need to introduce an additiona calss for second div

.overlap{
    top: -30px;
position: relative;
left: 30px;
}

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

final keyword in method parameters

Strings are immutable, so actully you can't change the String afterwards (you can only make the variable that held the String object point to a different String object).

However, that is not the reason why you can bind any variable to a final parameter. All the compiler checks is that the parameter is not reassigned within the method. This is good for documentation purposes, arguably good style, and may even help optimize the byte code for speed (although this seems not to do very much in practice).

But even if you do reassign a parameter within a method, the caller doesn't notice that, because java does all parameter passing by value. After the sequence

  a = someObject();
  process(a);

the fields of a may have changed, but a is still the same object it was before. In pass-by-reference languages this may not be true.

How to use JavaScript regex over multiple lines?

I have tested it (Chrome) and it working for me( both [^] and [^\0]), by changing the dot (.) by either [^\0] or [^] , because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).

_x000D_
_x000D_
var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";_x000D_
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );_x000D_
alert(arr);     //Working
_x000D_
_x000D_
_x000D_

class method generates "TypeError: ... got multiple values for keyword argument ..."

I want to add one more answer :

It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.

there is difference between parameter and argument you can read in detail about here Arguments and Parameter in python

def hello(a,b=1, *args):
   print(a, b, *args)


hello(1, 2, 3, 4,a=12)

since we have three parameters :

a is positional parameter

b=1 is keyword and default parameter

*args is variable length parameter

so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :

one is positional value: a=1

second is keyworded value which is a=12

Solution

We have to change hello(1, 2, 3, 4,a=12) to hello(1, 2, 3, 4,12) so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)

additional information

if we want that *args should get 2,3,4 and a should get 1 and b should get 12

then we can do like this
def hello(a,*args,b=1): pass hello(1, 2, 3, 4,b=12)

Something more :

def hello(a,*c,b=1,**kwargs):
    print(b)
    print(c)
    print(a)
    print(kwargs)

hello(1,2,1,2,8,9,c=12)

output :

1

(2, 1, 2, 8, 9)

1

{'c': 12}

How to fix Subversion lock error

I get this too. I go to the directory (not in Eclipse) where the files are, go into the .svn dir and delete the file called lock.

Flip back to Eclipse and continue.

There is a similar question here Problems committing file to SVN repository

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

You have to pass the route parameters to the route method, for example:

<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>

It's because, both routes have a {nickname} in the route declaration. I've used $nickname for example but make sure you change the $nickname to appropriate value/variable, for example, it could be something like the following:

<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>

Removing specific rows from a dataframe

Here's a solution to your problem using dplyr's filter function.

Although you can pass your data frame as the first argument to any dplyr function, I've used its %>% operator, which pipes your data frame to one or more dplyr functions (just filter in this case).

Once you are somewhat familiar with dplyr, the cheat sheet is very handy.

> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
   sub day
1    1   1
2    1   2
3    1   3
4    1   4
5    2   1
6    2   2
7    2   3
8    2   4
9    3   1
10   3   2
11   3   3
12   3   4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
   sub day
1    1   1
2    1   3
3    1   4
4    2   1
5    2   2
6    2   3
7    2   4
8    3   1
9    3   2
10   3   3

Jenkins pipeline how to change to another folder

You can use the dir step, example:

dir("folder") {
    sh "pwd"
}

The folder can be relative or absolute path.

Python ImportError: No module named wx

For Windows and MacOS, Simply install it with pip

pip install -U wxPython

Reference: Official site

PackagesNotFoundError: The following packages are not available from current channels:

Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control.

Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.

"Exception has been thrown by the target of an invocation" error (mscorlib)

I'd suggest checking for an inner exception. If there isn't one, check your logs for the exception that occurred immediately prior to this one.

This isn't a web-specific exception, I've also encountered it in desktop-app development. In short, what's happening is that the thread receiving this exception is running some asynchronous code (via Invoke(), e.g.) and that code that's being run asynchronously is exploding with an exception. This target invocation exception is the aftermath of that failure.

If you haven't already, place some sort of exception logging wrapper around the asynchronous callbacks that are being invoked when you trigger this error. Event handlers, for instance. That ought to help you track down the problem.

Good luck!

How to use absolute path in twig functions

Daniel's answer seems to work fine for now, but please note that generating absolute urls using twig's asset function is now deprecated:

DEPRECATED - Generating absolute URLs with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0. Please use absolute_url() instead.

Here's the official announcement: http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes

You have to use the absolute_url twig function:

{# Symfony 2.6 #}
{{ asset('logo.png', absolute = true) }}

{# Symfony 2.7 #}
{{ absolute_url(asset('logo.png')) }}

It is interesting to note that it also works with path function:

{{ absolute_url(path('index')) }}

How to browse localhost on Android device?

I use my local ip for that i.e. 192.168.0.1 and it works.

How to randomize (shuffle) a JavaScript array?

I have written a shuffle function on my own . The difference here is it will never repeat a value (checks in the code for this) :-

function shuffleArray(array) {
 var newArray = [];
 for (var i = 0; i < array.length; i++) {
     newArray.push(-1);
 }

 for (var j = 0; j < array.length; j++) {
    var id = Math.floor((Math.random() * array.length));
    while (newArray[id] !== -1) {
        id = Math.floor((Math.random() * array.length));
    }

    newArray.splice(id, 1, array[j]);
 }
 return newArray; }

Git vs Team Foundation Server

For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...

How to show imageView full screen on imageView click?

It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)

    public class UIutils {

private Activity mActivity;

    public UIutils(Activity activity){
        mActivity = activity;
    }

public void showPhoto(Uri photoUri){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoUri, "image/*");
        mActivity.startActivity(intent);
    }
}

Then to use it just do this:

imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));

I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

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

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

How to filter for multiple criteria in Excel?

The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.

http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm

Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.

  1. E1 : Letters
  2. E2 : =m
  3. E3 : =h
  4. E4 : =j

I put the data starting on row 5:

  1. A5 : Letters
  2. A6 :
  3. A7 :
  4. ...

Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.

That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.

Get absolute path of initially run script

Here's a useful PHP function I wrote for this precisely. As the original question clarifies, it returns the path from which the initial script was executed - not the file we are currently in.

/**
 * Get the file path/dir from which a script/function was initially executed
 * 
 * @param bool $include_filename include/exclude filename in the return string
 * @return string
 */ 
function get_function_origin_path($include_filename = true) {
    $bt = debug_backtrace();
    array_shift($bt);
    if ( array_key_exists(0, $bt) && array_key_exists('file', $bt[0]) ) {
        $file_path = $bt[0]['file'];
        if ( $include_filename === false ) {
            $file_path = str_replace(basename($file_path), '', $file_path);
        }
    } else {
        $file_path = null;
    }
    return $file_path;
}

Is it possible to have a default parameter for a mysql stored procedure?

No, this is not supported in MySQL stored routine syntax.

Feel free to submit a feature request at bugs.mysql.com.

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

Open web in new tab Selenium + Python

Opening the new empty tab within same window in chrome browser is not possible up to my knowledge but you can open the new tab with web-link.

So far I surfed net and I got good working content on this question. Please try to follow the steps without missing.

import selenium.webdriver as webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get('https://www.google.com?q=python#q=python')
first_link = driver.find_element_by_class_name('l')

# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack 
first_link.send_keys(Keys.CONTROL + Keys.RETURN)

# Switch tab to the new tab, which we will assume is the next one on the right
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

driver.quit()

I think this is better solution so far.

Credits: https://gist.github.com/lrhache/7686903

Example JavaScript code to parse CSV data

Here's my simple vanilla JavaScript code:

let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))

function splitQuotes(line) {
  if(line.indexOf('"') < 0) 
    return line.split(',')

  let result = [], cell = '', quote = false;
  for(let i = 0; i < line.length; i++) {
    char = line[i]
    if(char == '"' && line[i+1] == '"') {
      cell += char
      i++
    } else if(char == '"') {
      quote = !quote;
    } else if(!quote && char == ',') {
      result.push(cell)
      cell = ''
    } else {
      cell += char
    }
    if ( i == line.length-1 && cell) {
      result.push(cell)
    }
  }
  return result
}

Add string in a certain position in Python

As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you'd have to use .join() using an empty string.

>>> hash = '355879ACB6'
>>> hashlist = list(hash)
>>> hashlist.insert(4, '-')
>>> ''.join(hashlist)
'3558-79ACB6'

I am not sure how this compares as far as performance, but I do feel it's easier on the eyes than the other solutions. ;-)

How to insert a new line in strings in Android

I use <br> in a CDATA tag. As an example, my strings.xml file contains an item like this:

<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>

and prints

My name is John
Nice to meet you

What is the Sign Off feature in Git for?

git 2.7.1 (February 2016) clarifies that in commit b2c150d (05 Jan 2016) by David A. Wheeler (david-a-wheeler).
(Merged by Junio C Hamano -- gitster -- in commit 7aae9ba, 05 Feb 2016)

git commit man page now includes:

-s::
--signoff::

Add Signed-off-by line by the committer at the end of the commit log message.
The meaning of a signoff depends on the project, but it typically certifies that committer has the rights to submit this work under the same license and agrees to a Developer Certificate of Origin (see https://developercertificate.org for more information).


Expand documentation describing --signoff

Modify various document (man page) files to explain in more detail what --signoff means.

This was inspired by "lwn article 'Bottomley: A modest proposal on the DCO'" (Developer Certificate of Origin) where paulj noted:

The issue I have with DCO is that there adding a "-s" argument to git commit doesn't really mean you have even heard of the DCO (the git commit man page makes no mention of the DCO anywhere), never mind actually seen it.

So how can the presence of "signed-off-by" in any way imply the sender is agreeing to and committing to the DCO? Combined with fact I've seen replies on lists to patches without SOBs that say nothing more than "Resend this with signed-off-by so I can commit it".

Extending git's documentation will make it easier to argue that developers understood --signoff when they use it.


Note that this signoff is now (for Git 2.15.x/2.16, Q1 2018) available for git pull as well.

See commit 3a4d2c7 (12 Oct 2017) by W. Trevor King (wking).
(Merged by Junio C Hamano -- gitster -- in commit fb4cd88, 06 Nov 2017)

pull: pass --signoff/--no-signoff to "git merge"

merge can take --signoff, but without pull passing --signoff down, it is inconvenient to use; allow 'pull' to take the option and pass it through.

How to prevent user from typing in text field without disabling the field?

just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.

    <asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
    </asp:TextBox>

What should main() return in C and C++?

Note that the C and C++ standards define two kinds of implementations: freestanding and hosted.

  • C90 hosted environment

Allowed forms 1:

    int main (void)
    int main (int argc, char *argv[])

    main (void)
    main (int argc, char *argv[])
    /*... etc, similar forms with implicit int */

Comments:

The former two are explicitly stated as the allowed forms, the others are implicitly allowed because C90 allowed "implicit int" for return type and function parameters. No other form is allowed.

  • C90 freestanding environment

Any form or name of main is allowed 2.

  • C99 hosted environment

Allowed forms 3:

    int main (void)
    int main (int argc, char *argv[])
    /* or in some other implementation-defined manner. */

Comments:

C99 removed "implicit int" so main() is no longer valid.

A strange, ambiguous sentence "or in some other implementation-defined manner" has been introduced. This can either be interpreted as "the parameters to int main() may vary" or as "main can have any implementation-defined form".

Some compilers have chosen to interpret the standard in the latter way. Arguably, one cannot easily state that they are not conforming by citing the standard in itself, since it is is ambiguous.

However, to allow completely wild forms of main() was probably(?) not the intention of this new sentence. The C99 rationale (not normative) implies that the sentence refers to additional parameters to int main 4.

Yet the section for hosted environment program termination then goes on arguing about the case where main does not return int 5. Although that section is not normative for how main should be declared, it definitely implies that main might be declared in a completely implementation-defined way even on hosted systems.

  • C99 freestanding environment

Any form or name of main is allowed 6.

  • C11 hosted environment

Allowed forms 7:

    int main (void)
    int main (int argc, char *argv[])
    /* or in some other implementation-defined manner. */
  • C11 freestanding environment

Any form or name of main is allowed 8.


Note that int main() was never listed as a valid form for any hosted implementation of C in any of the above versions. In C, unlike C++, () and (void) have different meanings. The former is an obsolescent feature which may be removed from the language. See C11 future language directions:

6.11.6 Function declarators

The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.


  • C++03 hosted environment

Allowed forms 9:

    int main ()
    int main (int argc, char *argv[])

Comments:

Note the empty parenthesis in the first form. C++ and C are different in this case, because in C++ this means that the function takes no parameters. But in C it means that it may take any parameter.

  • C++03 freestanding environment

The name of the function called at startup is implementation-defined. If it is named main() it must follow the stated forms 10:

    // implementation-defined name, or 
    int main ()
    int main (int argc, char *argv[])
  • C++11 hosted environment

Allowed forms 11:

    int main ()
    int main (int argc, char *argv[])

Comments:

The text of the standard has been changed but it has the same meaning.

  • C++11 freestanding environment

The name of the function called at startup is implementation-defined. If it is named main() it must follow the stated forms 12:

    // implementation-defined name, or 
    int main ()
    int main (int argc, char *argv[])

References

  1. ANSI X3.159-1989 2.1.2.2 Hosted environment. "Program startup"

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
  1. ANSI X3.159-1989 2.1.2.1 Freestanding environment:

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.

  1. ISO 9899:1999 5.1.2.2 Hosted environment -> 5.1.2.2.1 Program startup

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }

or equivalent;9) or in some other implementation-defined manner.

  1. Rationale for International Standard — Programming Languages — C, Revision 5.10. 5.1.2.2 Hosted environment --> 5.1.2.2.1 Program startup

The behavior of the arguments to main, and of the interaction of exit, main and atexit (see §7.20.4.2) has been codified to curb some unwanted variety in the representation of argv strings, and in the meaning of values returned by main.

The specification of argc and argv as arguments to main recognizes extensive prior practice. argv[argc] is required to be a null pointer to provide a redundant check for the end of the list, also on the basis of common practice.

main is the only function that may portably be declared either with zero or two arguments. (The number of other functions’ arguments must match exactly between invocation and definition.) This special case simply recognizes the widespread practice of leaving off the arguments to main when the program does not access the program argument strings. While many implementations support more than two arguments to main, such practice is neither blessed nor forbidden by the Standard; a program that defines main with three arguments is not strictly conforming (see §J.5.1.).

  1. ISO 9899:1999 5.1.2.2 Hosted environment --> 5.1.2.2.3 Program termination

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

  1. ISO 9899:1999 5.1.2.1 Freestanding environment

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.

  1. ISO 9899:2011 5.1.2.2 Hosted environment -> 5.1.2.2.1 Program startup

This section is identical to the C99 one cited above.

  1. ISO 9899:1999 5.1.2.1 Freestanding environment

This section is identical to the C99 one cited above.

  1. ISO 14882:2003 3.6.1 Main function

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

    int main() { /* ... */ }

and

    int main(int argc, char* argv[]) { /* ... */ }
  1. ISO 14882:2003 3.6.1 Main function

It is implementation-defined whether a program in a freestanding environment is required to define a main function.

  1. ISO 14882:2011 3.6.1 Main function

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both

— a function of () returning int and

— a function of (int, pointer to pointer to char) returning int

as the type of main (8.3.5).

  1. ISO 14882:2011 3.6.1 Main function

This section is identical to the C++03 one cited above.

SQL query for today's date minus two months

SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

For those who couldn't get choose007's answer up and running

If clickListener is not working properly at all times in chose007's solution, try to implement View.onTouchListener instead of clickListener. Handle touch event using any of the action ACTION_UP or ACTION_DOWN. For some reason, maps infoWindow causes some weird behaviour when dispatching to clickListeners.

infoWindow.findViewById(R.id.my_view).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
          int action = MotionEventCompat.getActionMasked(event);
          switch (action){
                case MotionEvent.ACTION_UP:
                    Log.d(TAG,"a view in info window clicked" );
                    break;
                }
                return true;
          }

Edit : This is how I did it step by step

First inflate your own infowindow (global variable) somewhere in your activity/fragment. Mine is within fragment. Also insure that root view in your infowindow layout is linearlayout (for some reason relativelayout was taking full width of screen in infowindow)

infoWindow = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.info_window, null);
/* Other global variables used in below code*/
private HashMap<Marker,YourData> mMarkerYourDataHashMap = new HashMap<>();
private GoogleMap mMap;
private MapWrapperLayout mapWrapperLayout;

Then in onMapReady callback of google maps android api (follow this if you donot know what onMapReady is Maps > Documentation - Getting Started )

   @Override
    public void onMapReady(GoogleMap googleMap) {
       /*mMap is global GoogleMap variable in activity/fragment*/
        mMap = googleMap;
       /*Some function to set map UI settings*/ 
        setYourMapSettings();

MapWrapperLayout initialization http://stackoverflow.com/questions/14123243/google-maps-android-api-v2- interactive-infowindow-like-in-original-android-go/15040761#15040761 39 - default marker height 20 - offset between the default InfoWindow bottom edge and it's content bottom edge */

        mapWrapperLayout.init(mMap, Utils.getPixelsFromDp(mContext, 39 + 20));

        /*handle marker clicks separately - not necessary*/
       mMap.setOnMarkerClickListener(this);

       mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    return null;
                }

            @Override
            public View getInfoContents(Marker marker) {
                YourData data = mMarkerYourDataHashMap.get(marker);
                setInfoWindow(marker,data);
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });
    }

SetInfoWindow method

private void setInfoWindow (final Marker marker, YourData data)
            throws NullPointerException{
        if (data.getVehicleNumber()!=null) {
            ((TextView) infoWindow.findViewById(R.id.VehicelNo))
                    .setText(data.getDeviceId().toString());
        }
        if (data.getSpeed()!=null) {
            ((TextView) infoWindow.findViewById(R.id.txtSpeed))
                    .setText(data.getSpeed());
        }

        //handle dispatched touch event for view click
        infoWindow.findViewById(R.id.any_view).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = MotionEventCompat.getActionMasked(event);
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        Log.d(TAG,"any_view clicked" );
                        break;
                }
                return true;
            }
        });

Handle marker click separately

    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.d(TAG,"on Marker Click called");
        marker.showInfoWindow();
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(marker.getPosition())      // Sets the center of the map to Mountain View
                .zoom(10)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),1000,null);
        return true;
    }

Sending JSON object to Web API

I believe you need quotes around the model:

JSON.stringify({ "model": source })

HTML Table cellspacing or padding just top / bottom

Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top, padding-bottom, padding-left, and padding-right; or padding: [top] [right] [bottom] [left];).

How to get the Facebook user id using the access token

You just have to hit another Graph API:

https://graph.facebook.com/me?access_token={access-token}

It will give your e-mail Id and user Id (for Facebook) also.

VBA shorthand for x=x+1?

Sadly there are no operation-assignment operators in VBA.

(Addition-assignment += are available in VB.Net)

Pointless workaround;

Sub Inc(ByRef i As Integer)
   i = i + 1  
End Sub
...
Static value As Integer
inc value
inc value

How to change position of Toast in Android?

The method to change the color, position and background color of toast is:

Toast toast=Toast.makeText(getApplicationContext(),"This is advanced toast",Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
View view=toast.getView();
TextView  view1=(TextView)view.findViewById(android.R.id.message);
view1.setTextColor(Color.YELLOW);
view.setBackgroundResource(R.color.colorPrimary);
toast.show();

For line by line explanation: https://www.youtube.com/watch?v=5bzhGd1HZOc

Java - Create a new String instance with specified length and filled with specific character. Best solution?

char[] chars = new char[10];
Arrays.fill(chars, '*');
String text = new String(chars);

Split string into array of character strings

split("(?!^)") does not work correctly if the string contains surrogate pairs. You should use split("(?<=.)").

String[] splitted = "?ab".split("(?<=.)");
System.out.println(Arrays.toString(splitted));

output:

[?, a, b, , , ]

A method to count occurrences in a list

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

Base64 Java encode and decode a string

You can use following approach:

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));

// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));

Hope this answers your doubt.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

In my case, this error ocurred while i was using the

implementation 'com.android.support:appcompat-v7:+'
implementation 'com.android.support:design:+'

libraries together with googles

implementation 'com.google.android.material:material-components:+'

library. If this is the case in your project, i highly recommend to fully remove the google material components library from your project.

How can I remove file extension from a website address?

same as Igor but should work without line 2:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Conditional WHERE clause in SQL Server

Try this

SELECT 
    DateAppr,
    TimeAppr,
    TAT,
    LaserLTR,
    Permit,
    LtrPrinter,
    JobName,
    JobNumber,
    JobDesc,
    ActQty,
    (ActQty-LtrPrinted) AS L,
    (ActQty-QtyInserted) AS M,
    ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
FROM 
    [test].[dbo].[MM]
WHERE 
    DateDropped = 0
    AND (
    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
    OR 
    (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
    )

You can read more about conditional WHERE here.

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.

For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:

sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now   # to exit the container

Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.

htaccess "order" Deny, Allow, Deny

Not answering OPs question directly, but for the people finding this question in search of clarity on what's the difference between allow,deny and deny,allow:

Read the comma as a "but".

  • allow but deny: whitelist with exceptions.
    everything is denied, except items on the allow list, except items on the deny list
  • deny but allow: blacklist with exceptions.
    everything is allowed, except items on the deny list, except items on the allow list

allow only one country access, but exclude proxies within this country

OP needed a whitelist with exceptions, therefore allow,deny instead of deny,allow

Convert base64 string to ArrayBuffer

I would strongly suggest using an npm package implementing correctly the base64 specification.

The best one I know is rfc4648

The problem is that btoa and atob use binary strings instead of Uint8Array and trying to convert to and from it is cumbersome. Also there is a lot of bad packages in npm for that. I lose a lot of time before finding that one.

The creators of that specific package did a simple thing: they took the specification of Base64 (which is here by the way) and implemented it correctly from the beginning to the end. (Including other formats in the specification that are also useful like Base64-url, Base32, etc ...) That doesn't seem a lot but apparently that was too much to ask to the bunch of other libraries.

So yeah, I know I'm doing a bit of proselytism but if you want to avoid losing your time too just use rfc4648.

How can I add a volume to an existing Docker container?

Jérôme Petazzoni has a pretty interesting blog post on how to Attach a volume to a container while it is running. This isn't something that's built into Docker out of the box, but possible to accomplish.

As he also points out

This will not work on filesystems which are not based on block devices.

It will only work if /proc/mounts correctly lists the block device node (which, as we saw above, is not necessarily true).

Also, I only tested this on my local environment; I didn’t even try on a cloud instance or anything like that

YMMV

How to get the mobile number of current sim card in real device?

Well, all could be temporary hacks, but there is no way to get mobile number of a user. It is against ethical policy.

For eg, one of the answers above suggests getting all accounts and extracting from there. And it doesn't work anymore! All of these are hacks only.

Only way to get user's mobile number is going through operator. If you have a tie-up with mobile operators like Aitel, Vodafone, etc, you can get user's mobile number in header of request from mobile handset when connected via mobile network internet.

Not sure if any manufacturer tie ups to get specific permissions can help - not explored this area, but nothing documented atleast.

Operator overloading in Java

Or, you can make Java Groovy and just overload these functions to achieve what you want

//plus() => for the + operator
//multiply() => for the * operator
//leftShift() = for the << operator
// ... and so on ...

class Fish {
    def leftShift(Fish fish) {
        print "You just << (left shifted) some fish "
    }
}


def fish = new Fish()
def fish2 = new Fish()

fish << fish2

Who doesnt want to be/use groovy? :D

No you cannot use the compiled groovy JARs in Java the same way. It still is a compiler error for Java.

Multithreading in Bash

Sure, just add & after the command:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

Constructor overloading in Java - best practice

It really depends on the kind of classes as not all classes are created equal.

As general guideline I would suggest 2 options:

  • For value & immutable classes (Exception, Integer, DTOs and such) use single primary constructor as suggested in above answer
  • For everything else (session beans, services, mutable objects, JPA & JAXB entities and so on) use default constructor only with sensible defaults on all the properties so it can be used without additional configuration

What is Ad Hoc Query?

Ad-hoc Statments are just T-SQL Statements that it has a Where Clause , and that Where clause can actualy have a literal like :

Select * from member where member_no=285;

or a variable :

declare @mno INT=285;
Select * from member where member_no=@mno

How to retrieve the dimensions of a view?

Use the View's post method like this

post(new Runnable() {   
    @Override
    public void run() {
        Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
        }
    });

How to center div vertically inside of absolutely positioned parent div

use this :

.Absolute-Center {
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
}

refer this link: https://www.smashingmagazine.com/2013/08/absolute-horizontal-vertical-centering-css/

"A referral was returned from the server" exception when accessing AD from C#

Probably the path you supplied was not correct. Check that.

I would recomment the article Howto: (Almost) Everything In Active Directory via C# which really helped me in the past in dealing with AD.

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Well considering there's no overhead difference between a varchar(30) and a varchar(100) if you're only storing 20 characters in each, err on the side of caution and just make it 50.

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

The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.

class Foo
{ 
public:
  Foo();
  Foo(const Foo& rhs) { /* copy construction from rhs*/ }
  Foo& operator=(const Foo& rhs) {};
};

// ...

Foo orig;
Foo copy = orig;  // clones orig if implemented correctly

Sometimes it is beneficial to provide an explicit clone() method, especially for polymorphic classes.

class Interface
{
public:
  virtual Interface* clone() const = 0;
};

class Foo : public Interface
{
public:
  Interface* clone() const { return new Foo(*this); }
};

class Bar : public Interface
{
public:
  Interface* clone() const { return new Bar(*this); }
};


Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();

EDIT: Since Stack has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack's members from the so-called "right hand side" (rhs). However, you still need to ensure that any base classes are given the opportunity to initialize their members.

You do this by calling the base class:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}

Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};

Sql Server : How to use an aggregate function like MAX in a WHERE clause

SELECT rest.field1
FROM mastertable as m
INNER JOIN table1 at t1 on t1.field1 = m.field
INNER JOIN table2 at t2 on t2.field = t1.field
WHERE t1.field3 = (SELECT MAX(field3) FROM table1)

What does the restrict keyword mean in C++?

Nothing. It was added to the C99 standard.

Difference between File.separator and slash in paths

You use File.separator because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the ":" character as a file separator, and so dutifully the JVM obeys their wishes.

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

window.open with target "_blank" in Chrome

As Dennis says, you can't control how the browser chooses to handle target=_blank.

If you're wondering about the inconsistent behavior, probably it's pop-up blocking. Many browsers will forbid new windows from being opened apropos of nothing, but will allow new windows to be spawned as the eventual result of a mouse-click event.

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

Artisan, creating tables in database

Migration files must match the pattern *_*.php, or else they won't be found. Since users.php does not match this pattern (it has no underscore), this file will not be found by the migrator.

Ideally, you should be creating your migration files using artisan:

php artisan make:migration create_users_table

This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.

You can also use the --create or --table switches to add a little bit more boilerplate to help get you started:

php artisan make:migration create_users_table --create=users

The documentation on migrations can be found here.

possible EventEmitter memory leak detected

Replace .on() with once(). Using once() removes event listeners when the event is handled by the same function.

If this doesn't fix it, then reinstall restler with this in your package.json "restler": "git://github.com/danwrong/restler.git#9d455ff14c57ddbe263dbbcd0289d76413bfe07d"

This has to do with restler 0.10 misbehaving with node. you can see the issue closed on git here: https://github.com/danwrong/restler/issues/112 However, npm has yet to update this, so that is why you have to refer to the git head.

Can I remove the URL from my print css, so the web address doesn't print?

In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).

In your code, replace <html> with <html moznomarginboxes mozdisallowselectionprint>.

In others browsers, I don't know, but you can view http://www.mintprintables.com/print-tips/header-footer-windows/

SQL Server Management Studio missing

Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.

This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:

enter image description here

PDOException SQLSTATE[HY000] [2002] No such file or directory

I had the same problem using Docker and MySQL service name db in docker_compose.yml file:

I added the following in the .env file:

DB_HOST=db

you should also assure that your host is discoverable from the php app.

It was because PHP didn't figure out which host to use to connect.

Datatable to html Table

Since I didn't see this in any of the other answers, and since it's more efficient (in lines of code and in speed), here's a solution in VB.NET using a stringbuilder and lambda functions with String.Join instead of For loops for the columns.

Dim sb As New StringBuilder
sb.Append("<table>")
sb.Append("<tr>" & String.Join("", dt.Columns.OfType(Of DataColumn)().Select(Function(x) "<th>" & x.ColumnName & "</th>").ToArray()) & "</tr>")
For Each row As DataRow In dt.Rows
    sb.Append("<tr>" & String.Join("", row.ItemArray.Select(Function(f) "<td>" & f.ToString() & "</td>")) & "</tr>")
Next
sb.Append("</table>")

You can add your own styles to this pretty easily.

PHP Get name of current directory

echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only

Return the characters after Nth character in a string

Mid(strYourString, 4) (i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.

Javascript (+) sign concatenates instead of giving sum of variables

Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.

Use parseInt(i) than the value of "i" will be casted to Integer.

Than the "+" operator will work like addition.

In your case do this :-

divID = "question-" + parseInt(i)+1;

Converting a double to an int in Javascript without rounding

A trick to truncate that avoids a function call entirely is

var number = 2.9
var truncated = number - number % 1;
console.log(truncated); // 2 

To round a floating-point number to the nearest integer, use the addition/subtraction trick. This works for numbers with absolute value < 2 ^ 51.

var number = 2.9
var rounded = number + 6755399441055744.0 - 6755399441055744.0;  // (2^52 + 2^51)
console.log(rounded); // 3 

Note:

Halfway values are rounded to the nearest even using "round half to even" as the tie-breaking rule. Thus, for example, +23.5 becomes +24, as does +24.5. This variant of the round-to-nearest mode is also called bankers' rounding.

The magic number 6755399441055744.0 is explained in the stackoverflow post "A fast method to round a double to a 32-bit int explained".

_x000D_
_x000D_
// Round to whole integers using arithmetic operators
let trunc = (v) => v - v % 1;
let ceil  = (v) => trunc(v % 1 > 0 ? v + 1 : v);
let floor = (v) => trunc(v % 1 < 0 ? v - 1 : v);
let round = (v) => trunc(v < 0 ? v - 0.5 : v + 0.5);

let roundHalfEven = (v) => v + 6755399441055744.0 - 6755399441055744.0; // (2^52 + 2^51)

console.log("number  floor   ceil  round  trunc");
var array = [1.5, 1.4, 1.0, -1.0, -1.4, -1.5];
array.forEach(x => {
    let f = x => (x).toString().padStart(6," ");
    console.log(`${f(x)} ${f(floor(x))} ${f(ceil(x))} ${f(round(x))} ${f(trunc(x))}`);  
});
_x000D_
_x000D_
_x000D_

Getting the last n elements of a vector. Is there a better way than using the length() function?

Here is a function to do it and seems reasonably fast.

endv<-function(vec,val) 
{
if(val>length(vec))
{
stop("Length of value greater than length of vector")
}else
{
vec[((length(vec)-val)+1):length(vec)]
}
}

USAGE:

test<-c(0,1,1,0,0,1,1,NA,1,1)
endv(test,5)
endv(LETTERS,5)

BENCHMARK:

                                                    test replications elapsed relative
1                                 expression(tail(x, 5))       100000    5.24    6.469
2 expression(x[seq.int(to = length(x), length.out = 5)])       100000    0.98    1.210
3                       expression(x[length(x) - (4:0)])       100000    0.81    1.000
4                                 expression(endv(x, 5))       100000    1.37    1.691

How to include quotes in a string

Escape them with backslashes.

"I want to learn \"C#\""

update to python 3.7 using anaconda

conda create -n py37 -c anaconda anaconda=5.3

seems to be working.

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

Simplest way to read json from a URL in java

The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/

Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode

How to set default values in Rails?

A potentially even better/cleaner potential way than the answers proposed is to overwrite the accessor, like this:

def status
  self['name_of_var'] || 'desired_default_value'
end

See "Overwriting default accessors" in the ActiveRecord::Base documentation and more from StackOverflow on using self.

Console.WriteLine does not show up in Output window

Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab

What's the best three-way merge tool?

I love Ediff. It comes built-in with GNU Emacs.

To do a three-way diff, use ediff-files3 (for selecting three files) or ediff-buffer3 (for selecting three already-open buffers). You'll get a screen looking like this:

three-way diff in emacs

Note the word-difference higlighting.

You can hit n or p to go to the next/previous diffs, while ab will copy the region from buffer a (the leftmost one) to buffer b (the middle one), and similarly for other two-letter combinations of a, b, c; rb will restore the region in buffer b. Hit ? for a quick help menu, or read the fine manual on diff3 merging in Emacs.

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Nginx not running with no error message

I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?

Check with your WHM and make sure that port is open for the IP address of your site,

How to make responsive table

Pure css way to make a table fully responsive, no JavaScript is needed. Checke demo here Responsive Tables

<!DOCTYPE>
  <html>
  <head>
  <title>Responsive Table</title>
  <style> 
  /* only for demo purpose. you can remove it */
 .container{border: 1px solid #ccc; background-color: #ff0000; 
  margin: 10px auto;width: 98%; height:auto;padding:5px; text-align: center;}

 /* required */
.tablewrapper{width: 95%; overflow-y: hidden; overflow-x: auto; 
 background-color:green;  height: auto; padding: 5px;}

 /* only for demo purpose just for stlying. you can remove it */
 table { font-family: arial; font-size: 13px; padding: 2px 3px}
 table.responsive{ background-color:#1a99e6; border-collapse: collapse; 
 border-color: #fff}

tr:nth-child(1) td:nth-of-type(1){
 background:#333; color: #fff}
 tr:nth-child(1) td{
 background:#333; color: #fff; font-weight: bold;}
 table tr td:nth-child(2) {
 background:yellow;
}
 tr:nth-child(1) td:nth-of-type(2){color: #333}
 tr:nth-child(odd){ background:#ccc;}
 tr:nth-child(even){background:#fff;}
</style>
</head>
<body>

<div class="container">
<div class="tablewrapper">
<table  class="responsive" width="98%" cellpadding="4" cellspacing="1" border="1">
 <tr> 
 <td>Name</td> 
 <td>Email</td> 
 <td>Phone</td> 
 <td>Address</td> 
 <td>Contact</td> 
 <td>Mobile</td> 
 <td>Office</td> 
 <td>Home</td> 
 <td>Residency</td> 
 <td>Height</td>
 <td>Weight</td>
 <td>Color</td> 
 <td>Desease</td> 
 <td>Extra</td>
 <td>DOB</td>
 <td>Nick Name</td> 
</tr>
<tr>  
<td>RN Kushwaha</td>
<td>[email protected]</td>
<td>--</td>  
<td>Varanasi</td>
<td>-</td> 
<td>999999999</td> 
<td>022-111111</td> 
<td>-</td>
<td>India</td> 
<td>165cm</td> 
<td>58kg</td> 
<td>bright</td> 
<td>--</td> 
<td>--</td> 
<td>03/07/1986</td> 
<td>Aryan</td> 
</tr>
</table>
</div>
</div>
</body>
</html>

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

jQuery $(this) keyword

$(this) returns a cached version of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.

How to truncate a foreign key constrained table?

Getting the old foreign key check state and sql mode are best way to truncate / Drop the table as Mysql Workbench do while synchronizing model to database.

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;`
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

DROP TABLE TABLE_NAME;
TRUNCATE TABLE_NAME;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

IEnumerable vs List - What to Use? How do they work?

IEnumerable describes behavior, while List is an implementation of that behavior. When you use IEnumerable, you give the compiler a chance to defer work until later, possibly optimizing along the way. If you use ToList() you force the compiler to reify the results right away.

Whenever I'm "stacking" LINQ expressions, I use IEnumerable, because by only specifying the behavior I give LINQ a chance to defer evaluation and possibly optimize the program. Remember how LINQ doesn't generate the SQL to query the database until you enumerate it? Consider this:

public IEnumerable<Animals> AllSpotted()
{
    return from a in Zoo.Animals
           where a.coat.HasSpots == true
           select a;
}

public IEnumerable<Animals> Feline(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Felidae"
           select a;
}

public IEnumerable<Animals> Canine(IEnumerable<Animals> sample)
{
    return from a in sample
           where a.race.Family == "Canidae"
           select a;
}

Now you have a method that selects an initial sample ("AllSpotted"), plus some filters. So now you can do this:

var Leopards = Feline(AllSpotted());
var Hyenas = Canine(AllSpotted());

So is it faster to use List over IEnumerable? Only if you want to prevent a query from being executed more than once. But is it better overall? Well in the above, Leopards and Hyenas get converted into single SQL queries each, and the database only returns the rows that are relevant. But if we had returned a List from AllSpotted(), then it may run slower because the database could return far more data than is actually needed, and we waste cycles doing the filtering in the client.

In a program, it may be better to defer converting your query to a list until the very end, so if I'm going to enumerate through Leopards and Hyenas more than once, I'd do this:

List<Animals> Leopards = Feline(AllSpotted()).ToList();
List<Animals> Hyenas = Canine(AllSpotted()).ToList();

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

How to express a NOT IN query with ActiveRecord/Rails?

Rails 4+:

Article.where.not(title: ['Rails 3', 'Rails 5']) 

Rails 3:

Topic.where('id NOT IN (?)', Array.wrap(actions))

Where actions is an array with: [1,2,3,4,5]

Property getters and setters

Update for Swift 5.1

As of Swift 5.1 you can now get your variable without using get keyword. For example:

var helloWorld: String {
"Hello World"
}

execute function after complete page load

Try this jQuery:

$(function() {
 // Handler for .ready() called.
});

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

For AF_UNIX you can use call unlink (path); after close() socket in "server" app

Placing a textview on top of imageview in android

Try this:

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

<ImageView
    android:id="@+id/ImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src=//source of image />

<TextView
    android:id="@+id/ImageViewText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/ImageView"
    android:layout_alignTop="@id/ImageView"
    android:layout_alignRight="@id/ImageView"
    android:layout_alignBottom="@id/ImageView"
    android:text=//u r text here
    android:gravity="center"
    />

Hope this could help you.

View content of H2 or HSQLDB in-memory database

This is a Play 2 controller to initialize the H2 TCP and Web servers:

package controllers;

import org.h2.tools.Server;
import play.mvc.Controller;
import play.mvc.Result;

import java.sql.SQLException;

/**
 * Play 2 controller to initialize H2 TCP Server and H2 Web Console Server.
 *
 * Once it's initialized, you can connect with a JDBC client with
 * the URL `jdbc:h2:tcp://127.0.1.1:9092/mem:DBNAME`,
 * or can be accessed with the web console at `http://localhost:8082`,
 * and the URL JDBC `jdbc:h2:mem:DBNAME`.
 *
 * @author Mariano Ruiz <[email protected]>
 */
public class H2ServerController extends Controller {

    private static Server h2Server = null;
    private static Server h2WebServer = null;

    public static synchronized Result debugH2() throws SQLException {
        if (h2Server == null) {
            h2Server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
            h2Server.start();
            h2WebServer = Server.createWebServer("-web","-webAllowOthers","-webPort","8082");
            h2WebServer.start();
            return ok("H2 TCP/Web servers initialized");
        } else {
            return ok("H2 TCP/Web servers already initialized");
        }
    }
}

Setting PayPal return URL and making it auto return?

I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!

Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:

input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"

where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!

Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.

Comments please??

How to embed images in email

the third way is to base64 encode the image and place it in a data: url

example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACR0lEQVRYha1XvU4bQRD+bF/JjzEnpUDwCPROywPgB4h0PUWkFEkLposUIYyEU4N5AEpewnkDCiQcjBQpWLiLjk3DrnZnZ3buTv4ae25mZ+Z2Zr7daxljDGpg++Mv978Y5Nhc6+Di5tk9u7/bR3cjY9eOJnMUh3mg5y0roBjk+PF1F+1WCwCCJKTgpz9/ozjMg+ftVQQ/PtrB508f1OAcau8ADW5xfLRTOzgAZMPxTNy+YpDj6vaPGtxPgvpL7QwAtKXts8GqBveT8P1p5YF5x8nlo+n1p6bXn5ov3x9M+fZmjDGRXBXWH5X/Lv4FdqCLaLAmwX1/VKYJtIwJeYDO+dm3PSePJnO8vJbJhqN62hOUJ8QpoD1Au5kmIentr9TobAK04RyJEOazzjV9KokogVRwjvm6652kniYRJUBrTkft5bUEAGyuddzz7noHALBYls5O09skaE+4HdAYruobUz1FVI6qcy7xRFW95A915pzjiTp6zj7za6fB1lay1/Ssfa8/jRiLw/n1k9tizl7TS/aZ3xDakdqUByR/gDcF0qJV8QAXHACy+7v9wGA4ngWLVskDo8kcg4Ot8FpGa8PV0I7MyeWjq53f7Zrer3nyOLYJpJJowgN+g9IExNNQ4vLFskwyJtVrd8JoB7g3b4rz66dIpv7UHqg611xw/0om8QT7XXBx84zheCbKGui2U9n3p/YAlSVyqRqc+kt+mCyWJTSeoMGjOQciOQDXA6kjVTsL6JhpYHtA+wihPaGOWgLqnVACPQua4j8NK7bPLP4+qQAAAABJRU5ErkJggg==" width="32" height="32">

Shorthand for if-else statement

You can use an object as a map:

  var hasName = ({
        "true"  : "Y",
        "false" : "N"
  })[name];

This also scales nicely for many options

  var hasName = ({
        "true"          : "Y",
        "false"         : "N",
        "fileNotFound"  : "O"
  })[name];

(Bonus point for people getting the reference)

Note: you should use actual booleans instead of the string value "true" for your variables indicating truth values.

Adding image inside table cell in HTML

Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.

Python safe method to get value of nested dictionary

You could also use python reduce:

def deep_get(dictionary, *keys):
    return reduce(lambda d, key: d.get(key) if d else None, keys, dictionary)

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

VMware Workstation and Device/Credential Guard are not compatible

For those who might be encountering this issue with recent changes to your computer involving Hyper-V, you'll need to disable it while using VMWare or VirtualBox. They don't work together. Windows Sandbox and WSL 2 need the Hyper-V Hypervisor on, which currently breaks VMWare. Basically, you'll need to run the following commands to enable/disable Hyper-V services on next reboot.

To disable Hyper-V and get VMWare working, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype off

To re-enable Hyper-V and break VMWare for now, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype auto

You'll need to reboot after that. I've written a PowerShell script that will toggle this for you and confirm it with dialog boxes. It even self-elevates to Administrator using this technique so that you can just right click and run the script to quickly change your Hyper-V mode. It could easily be modified to reboot for you as well, but I personally didn't want that to happen. Save this as hypervisor.ps1 and make sure you've run Set-ExecutionPolicy RemoteSigned so that you can run PowerShell scripts.

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
    $newProcess.Arguments = "-windowstyle hidden & '" + $script:MyInvocation.MyCommand.Path + "'"

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

Add-Type -AssemblyName System.Windows.Forms


$state = bcdedit /enum | Select-String -Pattern 'hypervisorlaunchtype\s*(\w+)\s*'


if ($state.matches.groups[1].ToString() -eq "Off"){

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Enable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype auto
        [System.Windows.Forms.MessageBox]::Show("Enabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

} else {

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Disable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype off
        [System.Windows.Forms.MessageBox]::Show("Disabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

}

Is there an Eclipse plugin to run system shell in the Console?

In Eclipse 3.7, I found a terminal view plugin that I installed through Eclipse Marketplace. Details are as follow:

Local Terminal (Incubation) http://market.eclipsesource.com/yoxos/node/org.eclipse.tm.terminal.local.feature.group

A terminal emulation for local shells and external tools. Requires CDT Core 7.0 or later. Works on Linux, Solaris and Mac. Includes Source.

Side note, this terminal does not execute .bash_profile or .bashrc so you can do

source ~/.bash_profile

and (if this isn't sourced by `.bash_profile)

source ~/.bashrc

Update:

This is actually was base for Terminal plug-in for Eclipse fork. Quote from http://alexruiz.developerblogs.com/?p=2428

Uwe Stieber July 23, 2013 at 12:57 am

Alex, why not aiming for rejoining your work with the original TM Terminal? I’ve checked and haven’t found any bugzilla asking for missing features or pointing out bugs. There had been changes to the original Terminal control, so I’m not sure if all of your original reasons to clone it are still true.

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

GCC -fPIC option

Adding further...

Every process has same virtual address space (If randomization of virtual address is stopped by using a flag in linux OS) (For more details Disable and re-enable address space layout randomization only for myself)

So if its one exe with no shared linking (Hypothetical scenario), then we can always give same virtual address to same asm instruction without any harm.

But when we want to link shared object to the exe, then we are not sure of the start address assigned to shared object as it will depend upon the order the shared objects were linked.That being said, asm instruction inside .so will always have different virtual address depending upon the process its linking to.

So one process can give start address to .so as 0x45678910 in its own virtual space and other process at the same time can give start address of 0x12131415 and if they do not use relative addressing, .so will not work at all.

So they always have to use the relative addressing mode and hence fpic option.

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Which regular expression operator means 'Don't' match this character?

[^] ( within [ ] ) is negation in regular expression whereas ^ is "begining of string"

[^a-z] matches any single character that is not from "a" to "z"

^[a-z] means string starts with from "a" to "z"

Reference