Programs & Examples On #Iis 7

IIS (Internet Information Services) Version 7 – is a web server application and a set of feature extension modules created by Microsoft for use with Microsoft Windows. Released with Window Server 2008 and Windows Vista.

How do I set the default page of my application in IIS7?

Karan has posted the answer but that didn't work for me. So, I am posting what worked for me. If that didn't work then user can try this

<configuration> 
    <system.webServer> 
        <defaultDocument enabled="true"> 
            <files> 
                <add value="myFile.aspx" /> 
            </files> 
        </defaultDocument> 
    </system.webServer>
</configuration> 

X-Frame-Options Allow-From multiple domains

X-Frame-Options is deprecated. From MDN:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

The modern alternative is the Content-Security-Policy header, which along many other policies can white-list what URLs are allowed to host your page in a frame, using the frame-ancestors directive.
frame-ancestors supports multiple domains and even wildcards, for example:

Content-Security-Policy: frame-ancestors 'self' example.com *.example.net ;

Unfortunately, for now, Internet Explorer does not fully support Content-Security-Policy.

UPDATE: MDN has removed their deprecation comment. Here's a similar comment from W3C's Content Security Policy Level

The frame-ancestors directive obsoletes the X-Frame-Options header. If a resource has both policies, the frame-ancestors policy SHOULD be enforced and the X-Frame-Options policy SHOULD be ignored.

ASP.NET Web API application gives 404 when deployed at IIS 7

While the marked answer gets it working, all you really need to add to the webconfig is:

    <handlers>
      <!-- Your other remove tags-->
      <remove name="UrlRoutingModule-4.0"/>
      <!-- Your other add tags-->
      <add name="UrlRoutingModule-4.0" path="*" verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>
    </handlers>

Note that none of those have a particular order, though you want your removes before your adds.

The reason that we end up getting a 404 is because the Url Routing Module only kicks in for the root of the website in IIS. By adding the module to this application's config, we're having the module to run under this application's path (your subdirectory path), and the routing module kicks in.

Add IIS 7 AppPool Identities as SQL Server Logons

Look at: http://www.iis.net/learn/manage/configuring-security/application-pool-identities

USE master
GO
sp_grantlogin 'IIS APPPOOL\<AppPoolName>'

USE <yourdb>
GO
sp_grantdbaccess 'IIS APPPOOL\<AppPoolName>', '<AppPoolName>'
sp_addrolemember 'aspnet_Membership_FullAccess', '<AppPoolName>'
sp_addrolemember 'aspnet_Roles_FullAccess', '<AppPoolName>'

Request is not available in this context

You can get around the problem without switching to classic mode and still use Application_Start

public class Global : HttpApplication
{
   private static HttpRequest initialRequest;

   static Global()
   {
      initialRequest = HttpContext.Current.Request;       
   }

   void Application_Start(object sender, EventArgs e)
   {
      //access the initial request here
   }

For some reason, the static type is created with a request in its HTTPContext, allowing you to store it and reuse it immediately in the Application_Start event

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

Avoid web.config inheritance in child web application using inheritInChildApplications

We're getting errors about duplicate configuration directives on the one of our apps. After investigation it looks like it's because of this issue.

In brief, our root website is ASP.NET 3.5 (which is 2.0 with specific libraries added), and we have a subapplication that is ASP.NET 4.0.

web.config inheritance causes the ASP.NET 4.0 sub-application to inherit the web.config file of the parent ASP.NET 3.5 application.

However, the ASP.NET 4.0 application's global (or "root") web.config, which resides at C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config and C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config (depending on your bitness), already contains these config sections.

The ASP.NET 4.0 app then tries to merge together the root ASP.NET 4.0 web.config, and the parent web.config (the one for an ASP.NET 3.5 app), and runs into duplicates in the node.

The only solution I've been able to find is to remove the config sections from the parent web.config, and then either

  1. Determine that you didn't need them in your root application, or if you do
  2. Upgrade the parent app to ASP.NET 4.0 (so it gains access to the root web.config's configSections)

Accessing a local website from another computer inside the local network in IIS 7

Control Panel >> Windows Firewall >> Turn windows firewall on or off >> Turn off.

Advanced settings >> Domain profile >> Windows firewall properties >> Firewall status >> Off.

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

"405 method not allowed" in IIS7.5 for "PUT" method

For Windows server 2012 -> Go to Server manager -> Remove Roles and Features -> Server Roles -> Web Server (IIS) -> Web Server -> Common HTTP Features -> Uncheck WebDAV Publishing and remove it -> Restart server.

Receiving login prompt using integrated windows authentication

In my case the authorization settings were not set up properly.

I had to

  1. open the .NET Authorization Rules in IIS Manager

    open the .NET Authorization Rules in IIS Manager
  2. and remove the Deny Rule

    remove the Deny Rule

Maximum value of maxRequestLength?

These two settings worked for me to upload 1GB mp4 videos.

<system.web>
    <httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="2147483648" />
        </requestFiltering>
    </security>
</system.webServer>

500.21 Bad module "ManagedPipelineHandler" in its module list

I had this issue in Windows 10 when I needed IIS instead of IIS Express. New Web Project failed with OP's error. Fix was

Control Panel > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application Development Features

tick ASP.NET 4.7 (in my case)

IIS 500.19 with 0x80070005 The requested page cannot be accessed because the related configuration data for the page is invalid error

Ehm. I had moved my site/files to a different folder. Without changing the path in the IIS website.

You may all laugh now.

Config Error: This configuration section cannot be used at this path

Received this same issue after installing IIS 7 on Vista Home Premium. To correct error I changed the following values located in the applicationHost.config file located in Windows\system32\inetsrv.

Change all of the following values located in section -->

<div mce_keep="true"><section name="handlers" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"</div>
<div mce_keep="true"><section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" /> change this value from "Deny" to "Allow"</div>

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Integrated application pool mode

When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.

There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.

Classic application pool mode

When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.

This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.

Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.

Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?

Original source: Introduction to IIS Architecture

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

When I had this problem, I installed 'Remote Tools for Visual Studio 2015' from MSDN. I attached my local VS to the server to debug.

I appreciate that some folks may not have the ability to either install on or access other servers, but I thought I'd throw it out there as an option.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

It could be that you have your own MSBUILD proj file and are using the <AspNetCompiler> task. In which case you should add the ToolPath for .NET4.

<AspNetCompiler
    VirtualPath="/MyFacade"
    PhysicalPath="$(MSBuildProjectDirectory)\MyFacade\"
    TargetPath="$(MSBuildProjectDirectory)\Release\MyFacade"
    Updateable="true"
    Force="true"
    Debug="false"
    Clean="true"
    ToolPath="C:\Windows\Microsoft.NET\Framework\v4.0.30319\">      
</AspNetCompiler>

IIS 7, HttpHandler and HTTP Error 500.21

One solution that I've found is that you should have to change the .Net Framework back to v2.0 by Right Clicking on the site that you have manager under the Application Pools from the Advance Settings.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

If you have Exchange 2010:

(In my case, the error message didn't contain " for [email protected]")

This shows how to add a receive connector: http://exchangeserverpro.com/how-to-configure-a-relay-connector-for-exchange-server-2010/

But I also needed to perform a step found here: http://recover-email.blogspot.com.au/2013/12/how-to-solve-exchange-smtp-server-error.html

  • Go to Exchange Management Shell and run the command
  • Get-ReceiveConnector "JiraTest" | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"

While working on this, I ran the following on the affected server's PowerShell console until the error went away:

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "Test Email" -Body "This is a test"

How to fix 'Microsoft Excel cannot open or save any more documents'

I had this same issue, there was no issue regarding memory in my server machine, Finally i was able to fix it by following steps

  1. In your application hosting server, go to its "Component Services"
  2. enter image description here

3.Find "Microsoft Excel Application" in right side.

4.Open its properties by right click

5.Under Identity tab select the option interactive user and click Ok button.

Check once again. Hope it helps

NOTE: But now you may end up with another COM error "Retrieving the COM class factory for component...". In that case Just set the Identity to this User and enter the username and password of a user who has sufficient rights. In my case I entered a user of power user group.

How to increase request timeout in IIS?

To Increase request time out add this to web.config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

and for a specific page add this

<location path="somefile.aspx">
    <system.web>
        <httpRuntime executionTimeout="180"/>
    </system.web>
</location>

The default is 90 seconds for .NET 1.x.

The default 110 seconds for .NET 2.0 and later.

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Uncommon but may help some.

ensure you're using [HttpPut] from System.Web.Http

We were getting a 'Method not allowed' 405, on a HttpPut decorrated method.

Our problem would seem to be uncommon, as we accidentally used the [HttpPut] attribute from System.Web.Mvc and not System.Web.Http

The reason being, resharper suggested the .Mvc version, where-as usually System.Web.Http is already referenced when you derive directly from ApiController we were using a class that extended ApiController.

Asp.net 4.0 has not been registered

I had the same issue but solved it...... Microsoft has a fix for something close to this that actually worked to solve this issue. you can visit this page http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6.aspx

The issue occurs after you installed framework 4.5 and/or framework 4.6. The Visual Studio 2012 Update 5 doesn't fix the issue, I tried that first.

The msdn blog has this to say: "After the installation of the Microsoft .NET Framework 4.6, users may experience the following dialog box displayed in Microsoft Visual Studio when either creating new Web Site or Windows Azure project or when opening existing projects....."

According to the Blog the dialog is benign. just click OK, nothing is effected by the dialog... The comments in the blog suggests that VS 2015 has the same problem, maybe even worse.

How to set up subdomains on IIS 7

This one drove me crazy... basically you need two things:

1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.

2) You must add an additional website in IIS 7 named subdomain.example.com

  • Sites > Add Website
  • Site Name: subdomain.example.com
  • Physical Path: select the subdomain directory
  • Binding: same ip as example.com
  • Host name: subdomain.example.com

Server cannot set status after HTTP headers have been sent IIS7.5

Just to add to the responses above. I had this same issue when i first started using ASP.Net MVC and i was doing a Response.Redirect during a controller action:

Response.Redirect("/blah", true);

Instead of returning a Response.Redirect action i should have been returning a RedirectAction:

return Redirect("/blah");

Hosting ASP.NET in IIS7 gives Access is denied?

For me, nothing worked except the following, which solved the problem: open IIS, select the site, open Authentication (in the IIS section), right click Anonymous Authentication and select Edit, select Application Pool Identity.

The remote host closed the connection. The error code is 0x800704CD

I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.

To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).

You need to decide what the best way forward is depending on your app.

Using Custom Domains With IIS Express

For Visual Studio 2015 the steps in the above answers apply but the applicationhost.config file is in a new location. In your "solution" folder follow the path, this is confusing if you upgraded and would have TWO versions of applicationhost.config on your machine.

\.vs\config

Within that folder you will see your applicationhost.config file

Alternatively you could just search your solution folder for the .config file and find it that way.

I personally used the following configuration:

enter image description here

With the following in my hosts file:

127.0.0.1       jam.net
127.0.0.1       www.jam.net

And the following in my applicationhost.config file:

<site name="JBN.Site" id="2">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="C:\Dev\Jam\shoppingcart\src\Web\JBN.Site" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation="*:49707:" />
            <binding protocol="http" bindingInformation="*:49707:localhost" /> 
    </bindings>
</site>

Remember to run your instance of visual studio 2015 as an administrator! If you don't want to do this every time I recomend this:

How to Run Visual Studio as Administrator by default

I hope this helps somebody, I had issues when trying to upgrade to visual studio 2015 and realized that none of my configurations were being carried over.

Is there a way to reset IIS 7.5 to factory settings?

You need to uninstall IIS (Internet Information Services) but the key thing here is to make sure you uninstall the Windows Process Activation Service or otherwise your ApplicationHost.config will be still around. When you uninstall WAS then your configuration will be cleaned up and you will truly start with a fresh new IIS (and all data/configuration will be lost).

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Bad Request - Invalid Hostname IIS7

If working on local server or you haven't got domain name, delete "Host Name:" field. enter image description here

IIS7 Permissions Overview - ApplicationPoolIdentity

On Windows Server 2008(r2) you can't assign an application pool identity to a folder through Properties->Security. You can do it through an admin command prompt using the following though:

icacls "c:\yourdirectory" /t /grant "IIS AppPool\DefaultAppPool":(R)

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

Dots in URL causes 404 with ASP.NET mvc and IIS

Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.

  @Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

1_in SqlServer Security=>Login=>NT AUTHORITY\SYSTEM=>RightClick=>Property=>UserMaping=>Select YourDatabse=>Public&&Owner Select=>OK 2_In IIs Application Pools DefaultAppPool=>Advance Setting=>Identity=>LocalSystem=>Ok

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

Remove Server Response Header IIS7

Or add in web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <remove name="X-AspNet-Version" />
            <remove name="X-AspNetMvc-Version" />
            <remove name="X-Powered-By" />
            <!-- <remove name="Server" />  this one doesn't work -->
        </customHeaders>
    </httpProtocol>
</system.webServer>

How do you migrate an IIS 7 site to another server?

Microsoft Web Deploy v3 can export and import all your files, the configuration settings, etc. It puts it all into a zip archive ready to import on the new server. It can even upgrade to newer versions of IIS (v7-v8).

http://www.iis.net/extensions/WebDeploymentTool

After installing the tool: Right click your server or website in IIS Management Console, select 'Deploy', 'Export Application...' and run through the export.

On the new server, import the exported zip archive in the same way.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

How to set the Default Page in ASP.NET?

Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.

<add verb="GET" path="default.aspx" type="RedirectHandler"/>

Make sure Default.aspx does not exists physically at your application root. If it exists physically the HttpHandler will not be given any chance to execute. Physical file overrides HttpHandler mapping.

Moreover you can re-use this for pages other than default.aspx.

<add verb="GET" path="index.aspx" type="RedirectHandler"/>

//RedirectHandler.cs in your App_Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
    public RedirectHandler()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Redirect("CreateThings.aspx");
        context.Response.End();
    }

    #endregion
}

How do I create a user account for basic authentication?

Right click on Computer and choose "Manage" (or go to Control Panel > Administrative Tools > Computer Management) and under "Local Users and Groups" you can add a new user. Then, give that user permission to read the directory where the site is hosted.

Note: After creating the user, be sure to edit the user and remove all roles.

Invalid application path

Try : Internet Information Services (IIS) Manager -> Default Web Site -> Click Error Pages properties and select Detail errors

How to register ASP.NET 2.0 to web server(IIS7)?

ASP .NET 2.0:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir

ASP .NET 4.0:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

Run Command Prompt as Administrator to avoid the ...requested operation requires elevation error


aspnet_regiis.exe should no longer be used with IIS7 to install ASP.NET

  1. Open Control Panel
  2. Programs\Turn Windows Features on or off
  3. Internet Information Services
  4. World Wide Web Services
  5. Application development Features
  6. ASP.Net <== check mark here

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I had the same issue and found that it was caused because i had a character mistakenly typed in my Web.config after the end tag. My Web.config looked like this right at the end: </section>h. The "h" was an extra character after the closing tag.

IIS7 Cache-Control

The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.

Instead try simply navigating somewhere else and then navigating back.

You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.

enabling cross-origin resource sharing on IIS7

The solution for me was to add :

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>
</system.webServer>

To my web.config

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Will this answer Help you?
If you are receiving the following message in the EventViewer

The Module DLL aspnetcorev2.dll failed to load. The data is the error.

Then yes this will solve your problem


To check your event Viewer

  1. press Win+R and type: eventvwr, then press ENTER.
  2. On the left side of Windows Event Viewer click on Windows Logs -> Application.
  3. Now you need to find some ERRORS for source IIS-W3SVC-WP in the middle window.

if you receiving the previous message error then solution is :

Install Microsoft Visual C++ 2015 Redistributable 86x AND 64X (both of them)

Source

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

Looks like the user account you're using for your app pool doesn't have rights to the web site directory, so it can't read config from there. Check the app pool and see what user it is configured to run as. Check the directory and see if that user has appropriate rights to it. While you're at it, check the event log and see if IIS logged any more detailed diagnostic information there.

Is it safe to delete the "InetPub" folder?

As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.

My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

Basically:

Use IncludeErrorDetailPolicy instead if CustomErrors doesn't solve it for you (e.g. if you're ASP.NET stack is >2012):

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 
= IncludeErrorDetailPolicy.Always;

Note: Be careful returning detailed error info can reveal sensitive information to 'hackers'. See Simon's comment on this answer below.

TL;DR version

For me CustomErrors didn't really help. It was already set to Off, but I still only got a measly an error has occurred message. I guess the accepted answer is from 3 years ago which is a long time in the web word nowadays. I'm using Web API 2 and ASP.NET 5 (MVC 5) and Microsoft has moved away from an IIS-only strategy, while CustomErrors is old skool IIS ;).

Anyway, I had an issue on production that I didn't have locally. And then found I couldn't see the errors in Chrome's Network tab like I could on my dev machine. In the end I managed to solve it by installing Chrome on my production server and then browsing to the app there on the server itself (e.g. on 'localhost'). Then more detailed errors appeared with stack traces and all.

Only afterwards I found this article from Jimmy Bogard (Note: Jimmy is mr. AutoMapper!). The funny thing is that his article is also from 2012, but in it he already explains that CustomErrors doesn't help for this anymore, but that you CAN change the 'Error detail' by setting a different IncludeErrorDetailPolicy in the global WebApi configuration (e.g. WebApiConfig.cs):

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 
= IncludeErrorDetailPolicy.Always;

Luckily he also explains how to set it up that webapi (2) DOES listen to your CustomErrors settings. That's a pretty sensible approach, and this allows you to go back to 2012 :P.

Note: The default value is 'LocalOnly', which explains why I was able to solve the problem the way I described, before finding this post. But I understand that not everybody can just remote to production and startup a browser (I know I mostly couldn't until I decided to go freelance AND DevOps).

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

IIS: Where can I find the IIS logs?

Try the Windows event log, there can be some useful information

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

If the error message is just

"Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.", then grant the login permission for 'NT AUTHORITY\NETWORK SERVICE'

by using

"sp_grantlogin 'NT AUTHORITY\NETWORK SERVICE'" 

else if the error message is like

"Cannot open database "Phaeton.mdf" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\NETWORK SERVICE'."

try using

"EXEC sp_grantdbaccess 'NT AUTHORITY\NETWORK SERVICE'" 

under your "Phaeton" database.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

My app was an ASP.Net3.5 app (using version 2 of the framework). When ASP.Net3.5 apps got created Visual Studio automatically added scriptResourceHandler to the web.config. Later versions of .Net put this into the machine.config. If you run your ASP.Net 3.5 app using the version 4 app pool (depending on install order this is the default app pool), you will get this error.

When I moved to using the version 2.0 app pool. The error went away. I then had to deal with the error when serving WCF .svc :

HTTP Error 404.17 - Not Found The requested content appears to be script and will not be served by the static file handler

After some investigation, it seems that I needed to register the WCF handler. using the following steps:

  1. open Visual Studio Command Prompt (as administrator)
  2. navigate to "C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation"
  3. Run servicemodelreg -i

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

I fixed it this way

  1. Go to IIS
  2. Select your Project
  3. Click on "Authentication"
  4. Click on "Anonymous Authentication" > Edit > select "Application pool identity" instead of "Specific User".
  5. Done.

"401 Unauthorized" on a directory

  1. Open IIS and select site that is causing 401
  2. Select Authentication property in IIS Header
  3. Select Anonymous Authentication
  4. Right click on it, select Edit and choose Application pool identity
  5. Restart site and it should work

Enable IIS7 gzip

You will need to enable the feature in the Windows Features control panel:

IIS feature screenshot

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

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

To solve the issue try to repair the .net framework 4 and then run the command

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

enter image description here

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

Cannot read configuration file due to insufficient permissions

Instead of giving access to all IIS users like IIS_IUSRS you can also give access only to the Application Pool Identity using the site. This is the recommended approach by Microsoft and more information can be found here:

https://support.microsoft.com/en-za/help/4466942/understanding-identities-in-iis

https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

Fix:

enter image description here

Start by looking at Config File parameter above to determine the location that needs access. The entire publish folder in this case needs access. Right click on the folder and select properties and then the Security tab.

enter image description here

Click on Edit... and then Add....

Now look at Internet Information Services (IIS) Manager and Application Pools:

enter image description here

In my case my site runs under LocalTest Application Pool and then I enter the name IIS AppPool\LocalTest

enter image description here

Press Check Names and the user should be found.

enter image description here

Give the user the needed access (Default: Read & Execute, List folder contents and Read) and everything should work.

System.Security.SecurityException when writing to Event Log

I'm not working on IIS, but I do have an application that throws the same error on a 2K8 box. It works just fine on a 2K3 box, go figure.

My resolution was to "Run as administrator" to give the application elevated rights and everything works happily. I hope this helps lead you in the right direction.

Windows 2008 is rights/permissions/elevation is really different from Windows 2003, gar.

Problem in running .net framework 4.0 website on iis 7.0

After mapping of Application follow these steps

Open IIS Click on Applications Pools Double click on website Change Manage pipeline mode to "classic" click Ok.

Ow change .Net Framework Version to Lower version

Then click Ok

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

IIS7 folder permissions for web application

Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.

IIS - 401.3 - Unauthorized

Another problem that may arise relating to receiving an unauthorized is related to the providers used in the authentication setting from IIS. In My case I was experience that problem If I set the Windows Authentication provider as "Negotiate". After I selected "NTLM" option the access was granted.

More Information on Authentication providers

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authentication/windowsauthentication/providers/

When to use the !important property in CSS

I'm using !important to change the style of an element on a SharePoint web part. The JavaScript code that builds the elements on the web part is buried many levels deep in the SharePoint inner-workings.

Attempting to find where the style is applied, and then attempting to modify it seems like a lot of wasted effort to me. Using the !important tag in a custom CSS file is much, much easier.

how to install multiple versions of IE on the same system?

To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.

SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.

However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.

get parent's view from a layout

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

Is key-value pair available in Typescript?

TypeScript has Map. You can use like:

public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);

myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data

Java: how to use UrlConnection to post request with authorization?

To send a POST request call:

        connection.setDoOutput(true); // Triggers POST.

If you want to sent text in the request use:

        java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
        wr.write(textToSend);
        wr.flush();

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

How do I copy to the clipboard in JavaScript?

Using the JavaScript feature using try/catch you can even have better error handling in doing so like this:

copyToClipboard() {
    let el = document.getElementById('Test').innerText
    el.focus(); // el.select();
    try {
        var successful = document.execCommand('copy');
        if (successful) {
            console.log('Copied Successfully! Do whatever you want next');
        }
        else {
            throw ('Unable to copy');
        }
    }
    catch (err) {
        console.warn('Oops, Something went wrong ', err);
    }
}

Table with fixed header and fixed column on pure css

The existing answers will suit most people, but for those who are looking to add shadows under the fixed header and to the right of the first (fixed) column, here's a working example (pure css):

http://jsbin.com/nayifepaxo/1/edit?html,output

The main trick in getting this to work is using ::after to add shadows to the right of each of the first td in each tr:

tr td:first-child:after {
  box-shadow: 15px 0 15px -15px rgba(0, 0, 0, 0.05) inset;
  content: "";
  position:absolute;
  top:0;
  bottom:0;
  right:-15px;
  width:15px;
}

Took me a while (too long...) to get it all working so I figured I'd share for those who are in a similar situation.

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Rails: How to reference images in CSS within Rails 4

The hash is because the asset pipeline and server Optimize caching http://guides.rubyonrails.org/asset_pipeline.html

Try something like this:

 background-image: url(image_path('check.png'));

Goodluck

How to force cp to overwrite without confirmation

As other answers have stated, this could happend if cp is an alias of cp -i.

You can append a \ before the cp command to use it without alias.

\cp -fR source target

What are the differences between LDAP and Active Directory?

Short Summary

Active Directory is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol (LDAP).

Long Answer

Firstly, one needs to know what's Directory Service.

Directory Service is a software system that stores, organises, and provides access to information in a computer operating system's directory. In software engineering, a directory is a map between names and values. It allows the lookup of named values, similar to a dictionary.

For more details, read https://en.wikipedia.org/wiki/Directory_service

Secondly,as one could imagine, different vendors implement all kinds of forms of directory service, which is harmful to multi-vendor interoperability.

Thirdly, so in the 1980s, the ITU and ISO came up with a set of standards - X.500, for directory services, initially to support the requirements of inter-carrier electronic messaging and network name lookup.

Fourthly, so based on this standard, Lightweight Directory Access Protocol, LDAP, is developed. It uses the TCP/IP stack and a string encoding scheme of the X.500 Directory Access Protocol (DAP), giving it more relevance on the Internet.

Lastly, based on this LDAP/X.500 stack, Microsoft implemented a modern directory service for Windows, originating from the X.500 directory, created for use in Exchange Server. And this implementation is called Active Directory.

So in a short summary, Active Directory is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol (LDAP).

PS[0]: This answer heavily copies content from the wikipedia page listed above.

PS[1]: To know why it may be better use directory service rather just using a relational database, read https://en.wikipedia.org/wiki/Directory_service#Comparison_with_relational_databases

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)

Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.

For subdomains (like www.example.com) you can use CNAME records pointing to your-app-name.herokuapp.com. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)

Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com is an HTTP redirect to www.example.com.

Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.

Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):

@   IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.

Remember @ here is a shorthand for the root domain (example.com). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.

See also:

Remarks:

  • Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.

  • Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.

In Bootstrap 3,How to change the distance between rows in vertical?

There's a simply way of doing it. You define for all the rows, except the first one, the following class with properties:

.not-first-row
{
   position: relative;
   top: -20px;
}

Then you apply the class to all non-first rows and adjust the negative top value to fit your desired row space. It's easy and works way better. :) Hope it helped.

restrict edittext to single line

The @Aleks G OnKeyListener() works really well, but I ran it from MainActivity and so had to modify it slightly:

EditText searchBox = (EditText) findViewById(R.id.searchbox);
searchBox.setOnKeyListener(new OnKeyListener() {

    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
            //if the enter key was pressed, then hide the keyboard and do whatever needs doing.
            InputMethodManager imm = (InputMethodManager) MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchBox.getApplicationWindowToken(), 0);

            //do what you need on your enter key press here

            return true;
        }

        return false;
    }
});

I hope this helps anyone trying to do the same.

Android image caching

Google's libs-for-android has a nice libraries for managing image and file cache.

http://code.google.com/p/libs-for-android/

jQuery: serialize() form and other parameters

pass value of parameter like this

data : $('#form_id').serialize() + "&parameter1=value1&parameter2=value2"

and so on.

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

How to drop unique in MySQL?

Try it to remove uique of a column:

ALTER TABLE  `0_ms_labdip_details` DROP INDEX column_tcx

Run this code in phpmyadmin and remove unique of column

How can I pad a String in Java?

How about using recursion? Solution given below is compatible with all JDK versions and no external libraries required :)

private static String addPadding(final String str, final int desiredLength, final String padBy) {
        String result = str;
        if (str.length() >= desiredLength) {
            return result;
        } else {
            result += padBy;
            return addPadding(result, desiredLength, padBy);
        }
    }

NOTE: This solution will append the padding, with a little tweak you can prefix the pad value.

CSS word-wrapping in div

try white-space:normal; This will override inheriting white-space:nowrap;

Salt and hash a password in Python

Firstly import:-

import hashlib, uuid

Then change your code according to this in your method:

uname = request.form["uname"]
pwd=request.form["pwd"]
salt = hashlib.md5(pwd.encode())

Then pass this salt and uname in your database sql query, below login is a table name:

sql = "insert into login values ('"+uname+"','"+email+"','"+salt.hexdigest()+"')"

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

I encountered the same issue, when jdk 1.7 was used to compile then jre 1.4 was used for execution.

My solution was to set environment variable PATH by adding pathname C:\glassfish3\jdk7\bin in front of the existing PATH setting. The updated value is "C:\glassfish3\jdk7\bin;C:\Sun\SDK\bin". After the update, the problem was gone.

I want to vertical-align text in select box

just had this problem, but for mobile devices, mainly mobile firefox. The trick for me was to define a height, padding, line height, and finally box sizing, all on the select element. Not using your example numbers here, but for the sake of an example:

padding: 20px;
height: 60px;
line-height: 1;
-webkit-box-sizing: padding-box;
-moz-box-sizing: padding-box;
box-sizing: padding-box;

ComboBox: Adding Text and Value to an Item (no Binding Source)

//set 
comboBox1.DisplayMember = "Value"; 
//to add 
comboBox1.Items.Add(new KeyValuePair("2", "This text is displayed")); 
//to access the 'tag' property 
string tag = ((KeyValuePair< string, string >)comboBox1.SelectedItem).Key; 
MessageBox.Show(tag);

Heap space out of memory

No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()) but it is not guaranteed to run.

First try increasing the memory by setting -Xmx256m

How to get DropDownList SelectedValue in Controller in MVC

Use SelectList to bind @HtmlDropdownListFor and specify selectedValue parameter in it.

http://msdn.microsoft.com/en-us/library/dd492553(v=vs.108).aspx

Example : you can do like this for getting venderid

@Html.DropDownListFor(m => m.VendorId,Model.Vendor)


   public class MobileViewModel 
   {          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public int VenderID{get;set;}
   }
   [HttpPost]
   public ActionResult Action(MobileViewModel model)
   {
            var Id = model.VenderID;

Kafka consumer list

I realize that this question is nearly 4 years old now. Much has changed in Kafka since then. This is mentioned above, but only in small print, so I write this for users who stumble over this question as late as I did.

  1. Offsets by default are now stored in a Kafka Topic (not in Zookeeper any more), see Offsets stored in Zookeeper or Kafka?
  2. There's a kafka-consumer-groups utility which returns all the information, including the offset of the topic and partition, of the consumer, and even the lag (Remark: When you ask for the topic's offset, I assume that you mean the offsets of the partitions of the topic). In my Kafka 2.0 test cluster:
kafka-consumer-groups --bootstrap-server kafka:9092 --describe
    --group console-consumer-69763 Consumer group 'console-consumer-69763' has no active members.

TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID     HOST            CLIENT-ID
pytest          0          5               6               1               -               -               -
``


Repeat rows of a data.frame

df <- data.frame(a = 1:2, b = letters[1:2]) 
df[rep(seq_len(nrow(df)), each = 2), ]

how to add or embed CKEditor in php page

no need to require the ckeditor.php, because CKEditor will not processed by PHP...

you need just following the _samples directory and see what they do.

just need to include ckeditor.js by html tag, and do some configuration in javascript.

Free FTP Library

You may consider FluentFTP, previously known as System.Net.FtpClient.

It is released under The MIT License and available on NuGet (FluentFTP).

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

Rather than resetting the locale after the installation of the locales package you can answer the questions you would normally get asked (which is disabled by noninteractive) before installing the package so that the package scripts setup the locale correctly, this example sets the locale to english (British, UTF-8):

RUN echo locales locales/default_environment_locale select en_GB.UTF-8 | debconf-set-selections
RUN echo locales locales/locales_to_be_generated select "en_GB.UTF-8 UTF-8" | debconf-set-selections

RUN \
  apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y locales && \
  rm -rf /var/lib/apt/lists/*

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

UIButton title text color

I created a custom class MyButton extended from UIButton. Then added this inside the Identity Inspector:

enter image description here

After this, change the button type to Custom:

enter image description here

Then you can set attributes like textColor and UIFont for your UIButton for the different states:

enter image description here

Then I also created two methods inside MyButton class which I have to call inside my code when I want a UIButton to be displayed as highlighted:

- (void)changeColorAsUnselection{
    [self setTitleColor:[UIColor colorFromHexString:acColorGreyDark] 
               forState:UIControlStateNormal & 
                        UIControlStateSelected & 
                        UIControlStateHighlighted];
}

- (void)changeColorAsSelection{
    [self setTitleColor:[UIColor colorFromHexString:acColorYellow] 
               forState:UIControlStateNormal & 
                        UIControlStateHighlighted & 
                        UIControlStateSelected];
}

You have to set the titleColor for normal, highlight and selected UIControlState because there can be more than one state at a time according to the documentation of UIControlState. If you don't create these methods, the UIButton will display selection or highlighting but they won't stay in the UIColor you setup inside the UIInterface Builder because they are just available for a short display of a selection, not for displaying selection itself.

Comprehensive methods of viewing memory usage on Solaris

Here are the basics. I'm not sure that any of these count as "clear and simple" though.

ps(1)

For process-level view:

$ ps -opid,vsz,rss,osz,args
  PID  VSZ  RSS   SZ COMMAND
 1831 1776 1008  222 ps -opid,vsz,rss,osz,args
 1782 3464 2504  433 -bash
$

vsz/VSZ: total virtual process size (kb)

rss/RSS: resident set size (kb, may be inaccurate(!), see man)

osz/SZ: total size in memory (pages)

To compute byte size from pages:

$ sz_pages=$(ps -o osz -p $pid | grep -v SZ )
$ sz_bytes=$(( $sz_pages * $(pagesize) ))
$ sz_mbytes=$(( $sz_bytes / ( 1024 * 1024 ) ))
$ echo "$pid OSZ=$sz_mbytes MB"

vmstat(1M)

$ vmstat 5 5 
 kthr      memory            page            disk          faults      cpu
 r b w   swap  free  re  mf pi po fr de sr rm s3 -- --   in   sy   cs us sy id
 0 0 0 535832 219880  1   2  0  0  0  0  0 -0  0  0  0  402   19   97  0  1 99
 0 0 0 514376 203648  1   4  0  0  0  0  0  0  0  0  0  402   19   96  0  1 99
^C

prstat(1M)

   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  1852 martin   4840K 3600K cpu0    59    0   0:00:00 0.3% prstat/1
  1780 martin   9384K 2920K sleep   59    0   0:00:00 0.0% sshd/1
  ...

swap(1)

"Long listing" and "summary" modes:

$ swap -l
swapfile             dev  swaplo blocks   free
/dev/zvol/dsk/rpool/swap 256,1      16 1048560 1048560
$ swap -s 
total: 42352k bytes allocated + 20192k reserved = 62544k used, 607672k available
$

top(1)

An older version (3.51) is available on the Solaris companion CD from Sun, with the disclaimer that this is "Community (not Sun) supported". More recent binary packages available from sunfreeware.com or blastwave.org.

load averages:  0.02,  0.00,  0.00;                      up 2+12:31:38                                                                                            08:53:58
31 processes: 30 sleeping, 1 on cpu
CPU states: 98.0% idle,  0.0% user,  2.0% kernel,  0.0% iowait,  0.0% swap
Memory: 1024M phys mem, 197M free mem, 512M total swap, 512M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1898 martin     1  54    0 3336K 1808K cpu      0:00  0.96% top
     7 root      11  59    0   10M 7912K sleep    0:09  0.02% svc.startd

sar(1M)

And just what's wrong with sar? :)

How to concatenate strings in a Windows batch file?

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Rounding a number to the nearest 5 or 10 or X

Simply ROUND(x/5)*5 should do the job.

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
  
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");
  }

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");
  }

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    e.preventDefault();
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
  }
  
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {
    e.preventDefault();
    window.location.assign("https://www.google.com");
  }

});
_x000D_
.error {
  color: #000;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
}
_x000D_
<html>
  <body>
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      </div>
      
      <div class="input-container">
      <label>Address:</label>
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      </div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>
    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

How to store images in mysql database using php

I found the answer, For those who are looking for the same thing here is how I did it. You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.

HTML CODE

<input type="file" name="imageUpload" id="imageUpload">

PHP CODE

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

CODE TO DISPLAY THE IMAGE

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

Where is SQLite database stored on disk?

If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:

database: db/development.sqlite3

This means that it will be in the {RAILS_ROOT}/db directory.

Escaping special characters in Java Regular Expressions

use

pattern.compile("\"");
String s= p.toString()+"yourcontent"+p.toString();

will give result as yourcontent as is

Angular - "has no exported member 'Observable'"

My resolution was adding the following import: import { of } from 'rxjs/observable/of';

So the overall code of hero.service.ts after the change is:

import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { of } from 'rxjs/observable/of';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class HeroService {

  constructor() { }

  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }
}

Get the first item from an iterable that matches a condition

The most efficient way in Python 3 are one of the following (using a similar example):

With "comprehension" style:

next(i for i in range(100000000) if i == 1000)

WARNING: The expression works also with Python 2, but in the example is used range that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use xrange instead).

Note that the expression avoid to construct a list in the comprehension expression next([i for ...]), that would cause to create a list with all the elements before filter the elements, and would cause to process the entire options, instead of stop the iteration once i == 1000.

With "functional" style:

next(filter(lambda i: i == 1000, range(100000000)))

WARNING: This doesn't work in Python 2, even replacing range with xrange due that filter create a list instead of a iterator (inefficient), and the next function only works with iterators.

Default value

As mentioned in other responses, you must add a extra-parameter to the function next if you want to avoid an exception raised when the condition is not fulfilled.

"functional" style:

next(filter(lambda i: i == 1000, range(100000000)), False)

"comprehension" style:

With this style you need to surround the comprehension expression with () to avoid a SyntaxError: Generator expression must be parenthesized if not sole argument:

next((i for i in range(100000000) if i == 1000), False)

How to prevent scrollbar from repositioning web page?

I used some jquery to solve this

$('html').css({
    'overflow-y': 'hidden'
});

$(document).ready(function(){
  $(window).load(function() {
    $('html').css({
      'overflow-y': ''
    });
  });
});

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

Java naming convention for static final variables

Don't live fanatically with the conventions that SUN have med up, do whats feel right to you and your team.

For example this is how eclipse do it, breaking the convention. Try adding implements Serializable and eclipse will ask to generate this line for you.

Update: There were special cases that was excluded didn't know that. I however withholds to do what you and your team seems fit.

OWIN Startup Class Missing

In my case I logged into ftp server. Took backup of current files on ftp server. Delete all files manually from ftp server. Clean solution, redeployed the code. It worked.

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

How to clear browsing history using JavaScript?

to disable back function of the back button:

window.addEventListener('popstate', function (event) {
  history.pushState(null, document.title, location.href);
});

QUERY syntax using cell reference

To make it work with both text and numbers:

Exact match:

=query(D:E,"select * where D like '"&C1&"'", 0)

Convert search string to lowercase:

=query(D:E,"select * where D like lower('"&C1&"')", 0)

Convert to lowercase and contain part of the search string:

=query(D:E,"select * where D like lower('%"&C1&"%')", 0)

enter image description here

A1                = query/formula
yellow / A:B  = result area
green / C1    = search area
blue / D:E     = data area

If you get error when the input is text and not numbers; move the data and delete the (now empty) columns. Then move the data back.

Changing a specific column name in pandas DataFrame

What about?

df.columns.values[2] = "new_name"

JAVA How to remove trailing zeros from a double

Use a DecimalFormat object with a format string of "0.#".

How to allocate aligned memory only using the standard library?

You could also try posix_memalign() (on POSIX platforms, of course).

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

Return in Scala

Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.

What is the most efficient way to get first and last line of a text file?

Getting the first line is trivially easy. For the last line, presuming you know an approximate upper bound on the line length, os.lseek some amount from SEEK_END find the second to last line ending and then readline() the last line.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

In my case, this has been resolved by going to control panel > java > security > then add url in the exception site list. Then apply. Test again the site and it should now allow you to run the local java.

Select data from "show tables" MySQL query

Have you looked into querying INFORMATION_SCHEMA.Tables? As in

SELECT ic.Table_Name,
    ic.Column_Name,
    ic.data_Type,
    IFNULL(Character_Maximum_Length,'') AS `Max`,
    ic.Numeric_precision as `Precision`,
    ic.numeric_scale as Scale,
    ic.Character_Maximum_Length as VarCharSize,
    ic.is_nullable as Nulls, 
    ic.ordinal_position as OrdinalPos, 
    ic.column_default as ColDefault, 
    ku.ordinal_position as PK,
    kcu.constraint_name,
    kcu.ordinal_position,
    tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
    left outer join INFORMATION_SCHEMA.key_column_usage ku
        on ku.table_name = ic.table_name
        and ku.column_name = ic.column_name
    left outer join information_schema.key_column_usage kcu
        on kcu.column_name = ic.column_name
        and kcu.table_name = ic.table_name
    left outer join information_schema.table_constraints tc
        on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

Make sure you have not committed a typo as in my case

msyql_fetch_assoc should be mysql

Is bool a native C type?

C99 added a builtin _Bool data type (see Wikipedia for details), and if you #include <stdbool.h>, it provides bool as a macro to _Bool.

You asked about the Linux kernel in particular. It assumes the presence of _Bool and provides a bool typedef itself in include/linux/types.h.

How/when to generate Gradle wrapper files?

Generating the Gradle Wrapper

Project build gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
    gradleVersion = '2.2' 
}

// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Then at the command-line run

gradle wrapper

If you're missing gradle on your system install it or the above won't work. On a Mac it is best to install via Homebrew.

brew install gradle

After you have successfully run the wrapper task and generated gradlew, don't use your system gradle. It will save you a lot of headaches.

./gradlew assemble

What about the gradle plugin seen above?

com.android.tools.build:gradle:1.0.1

You should set the version to be the latest and you can check the tools page and edit the version accordingly.

See what Android Studio generates

The addition of gradle and the newest Android Studio have changed project layout dramatically. If you have an older project I highly recommend creating a clean one with the latest Android Studio and see what Google considers the standard project.

Android Studio has facilities for importing older projects which can also help.

Laravel Eloquent LEFT JOIN WHERE NULL

use Illuminate\Database\Eloquent\Builder;

$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
     $query = $query->where('orders.customer_id', 'NULL') 
});
    $query = $query->get();

How can I generate an HTML report for Junit results?

There are multiple options available for generating HTML reports for Selenium WebDriver scripts.

1. Use the JUNIT TestWatcher class for creating your own Selenium HTML reports

The TestWatcher JUNIT class allows overriding the failed() and succeeded() JUNIT methods that are called automatically when JUNIT tests fail or pass.

The TestWatcher JUNIT class allows overriding the following methods:

  • protected void failed(Throwable e, Description description)

failed() method is invoked when a test fails

  • protected void finished(Description description)

finished() method is invoked when a test method finishes (whether passing or failing)

  • protected void skipped(AssumptionViolatedException e, Description description)

skipped() method is invoked when a test is skipped due to a failed assumption.

  • protected void starting(Description description)

starting() method is invoked when a test is about to start

  • protected void succeeded(Description description)

succeeded() method is invoked when a test succeeds

See below sample code for this case:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class TestClass2 extends WatchManClassConsole {

    @Test public void testScript1() {
        assertTrue(1 < 2); >
    }

    @Test public void testScript2() {
        assertTrue(1 > 2);
    }

    @Test public void testScript3() {
        assertTrue(1 < 2);
    }

    @Test public void testScript4() {
        assertTrue(1 > 2);
    }
}

import org.junit.Rule; 
import org.junit.rules.TestRule; 
import org.junit.rules.TestWatcher; 
import org.junit.runner.Description; 
import org.junit.runners.model.Statement; 

public class WatchManClassConsole {

    @Rule public TestRule watchman = new TestWatcher() { 

        @Override public Statement apply(Statement base, Description description) { 
            return super.apply(base, description); 
        } 

        @Override protected void succeeded(Description description) { 
            System.out.println(description.getDisplayName() + " " + "success!"); 
        } 

        @Override protected void failed(Throwable e, Description description) { 
            System.out.println(description.getDisplayName() + " " + e.getClass().getSimpleName()); 
        }
    }; 
}

2. Use the Allure Reporting framework

Allure framework can help with generating HTML reports for your Selenium WebDriver projects.

The reporting framework is very flexible and it works with many programming languages and unit testing frameworks.

You can read everything about it at http://allure.qatools.ru/.

You will need the following dependencies and plugins to be added to your pom.xml file

  1. maven surefire
  2. aspectjweaver
  3. allure adapter

See more details including code samples on this article: http://test-able.blogspot.com/2015/10/create-selenium-html-reports-with-allure-framework.html

Remove padding or margins from Google Charts

By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:

// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
               'width': 350,
               'height': 400,
               'chartArea': {'width': '100%', 'height': '80%'},
               'legend': {'position': 'bottom'}
    };

If you want to tune it more, try changing these values or using other properties from the link above.

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

How do I fix PyDev "Undefined variable from import" errors?

I'm using opencv which relies on binaries etc so I have scripts where every other line has this silly error. Python is a dynamic language so such occasions shouldn't be considered errors.

I removed these errors altogether by going to:

Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Undefined -> Undefined Variable From Import -> Ignore

And that's that.

It may also be, Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Imports -> Import not found -> Ignore

day of the week to day number (Monday = 1, Tuesday = 2)

The date function can return this if you specify the format correctly:

$daynum = date("w", strtotime("wednesday"));

will return 0 for Sunday through to 6 for Saturday.

An alternative format is:

$daynum = date("N", strtotime("wednesday"));

which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).

Can you install and run apps built on the .NET framework on a Mac?

  • .NET Core will install and run on macOS - and just about any other desktop OS.
    IDEs are available for the mac, including:

  • Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.

Setting default value in select drop-down using Angularjs

Problem 1:

The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?

Problem 2:

Make sure you're using the following ng-options:

<select ng-model="object.item" ng-options="item.id as item.name for item in list" />

And put this in your controller to select a default value:

object.item = 4

Bring a window to the front in WPF

I know this question is rather old, but I've just come across this precise scenario and wanted to share the solution I've implemented.

As mentioned in comments on this page, several of the solutions proposed do not work on XP, which I need to support in my scenario. While I agree with the sentiment by @Matthew Xavier that generally this is a bad UX practice, there are times where it's entirely a plausable UX.

The solution to bringing a WPF window to the top was actually provided to me by the same code I'm using to provide the global hotkey. A blog article by Joseph Cooney contains a link to his code samples that contains the original code.

I've cleaned up and modified the code a little, and implemented it as an extension method to System.Windows.Window. I've tested this on XP 32 bit and Win7 64 bit, both of which work correctly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interop;
using System.Runtime.InteropServices;

namespace System.Windows
{
    public static class SystemWindows
    {
        #region Constants

        const UInt32 SWP_NOSIZE = 0x0001;
        const UInt32 SWP_NOMOVE = 0x0002;
        const UInt32 SWP_SHOWWINDOW = 0x0040;

        #endregion

        /// <summary>
        /// Activate a window from anywhere by attaching to the foreground window
        /// </summary>
        public static void GlobalActivate(this Window w)
        {
            //Get the process ID for this window's thread
            var interopHelper = new WindowInteropHelper(w);
            var thisWindowThreadId = GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);

            //Get the process ID for the foreground window's thread
            var currentForegroundWindow = GetForegroundWindow();
            var currentForegroundWindowThreadId = GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);

            //Attach this window's thread to the current window's thread
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);

            //Set the window position
            SetWindowPos(interopHelper.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

            //Detach this window's thread from the current window's thread
            AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);

            //Show and activate the window
            if (w.WindowState == WindowState.Minimized) w.WindowState = WindowState.Normal;
            w.Show();
            w.Activate();
        }

        #region Imports

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

        [DllImport("user32.dll")]
        private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        #endregion
    }
}

I hope this code helps others who encounter this problem.

In Go's http package, how do I get the query string on a POST request?

Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}

How to install pip for Python 3.6 on Ubuntu 16.10?

In at least in ubuntu 16.10, the default python3 is python3.5. As such, all of the python3-X packages will be installed for python3.5 and not for python3.6.

You can verify this by checking the shebang of pip3:

$ head -n1 $(which pip3)
#!/usr/bin/python3

Fortunately, the pip installed by the python3-pip package is installed into the "shared" /usr/lib/python3/dist-packages such that python3.6 can also take advantage of it.

You can install packages for python3.6 by doing:

python3.6 -m pip install ...

For example:

$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py

How to declare global variables in Android?

You could create a class that extends Application class and then declare your variable as a field of that class and providing getter method for it.

public class MyApplication extends Application {
    private String str = "My String";

    synchronized public String getMyString {
        return str;
    }
}

And then to access that variable in your Activity, use this:

MyApplication application = (MyApplication) getApplication();
String myVar = application.getMyString();

Auto-loading lib files in Rails 4

Use config.to_prepare to load you monkey patches/extensions for every request in development mode.

config.to_prepare do |action_dispatcher|
 # More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
 Rails.logger.info "\n--- Loading extensions for #{self.class} "
 Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
   Rails.logger.info "Loading extension(s): #{entry}"
   require_dependency "#{entry}"
 end
 Rails.logger.info "--- Loaded extensions for #{self.class}\n"

end

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

How to use putExtra() and getExtra() for string data

Use this to "put" the file...

Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
String strName = null;
i.putExtra("STRING_I_NEED", strName);

Then, to retrieve the value try something like:

String newString;
if (savedInstanceState == null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("STRING_I_NEED");
    }
} else {
    newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

Disable validation of HTML5 form elements

I had a read of the spec and did some testing in Chrome, and if you catch the "invalid" event and return false that seems to allow form submission.

I am using jquery, with this HTML.

_x000D_
_x000D_
// suppress "invalid" events on URL inputs_x000D_
$('input[type="url"]').bind('invalid', function() {_x000D_
  alert('invalid');_x000D_
  return false;_x000D_
});_x000D_
_x000D_
document.forms[0].onsubmit = function () {_x000D_
  alert('form submitted');_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input type="url" value="http://" />_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

I haven't tested this in any other browsers.

JavaScript: client-side vs. server-side validation

Yes, client side validation can be totally bypassed, always. You need to do both, client side to provide a better user experience, and server side to be sure that the input you get is actually validated and not just supposedly validated by the client.

How to get object length

Here's a jQuery-ised function of Innuendo's answer, ready for use.

$.extend({
    keyCount : function(o) {
        if(typeof o == "object") {
            var i, count = 0;
            for(i in o) {
                if(o.hasOwnProperty(i)) {
                    count++;
                }
            }
            return count;
        } else {
            return false;
        }
    }
});

Can be called like this:

var cnt = $.keyCount({"foo" : "bar"}); //cnt = 1;

Converting between strings and ArrayBuffers

var decoder = new TextDecoder ();
var string = decoder.decode (arrayBuffer);

See https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder/decode

Does Python have a package/module management system?

As a Ruby and Perl developer and learning-Python guy, I haven't found easy_install or pip to be the equivalent to RubyGems or CPAN.

I tend to keep my development systems running the latest versions of modules as the developers update them, and freeze my production systems at set versions. Both RubyGems and CPAN make it easy to find modules by listing what's available, then install and later update them individually or in bulk if desired.

easy_install and pip make it easy to install a module ONCE I located it via a browser search or learned about it by some other means, but they won't tell me what is available. I can explicitly name the module to be updated, but the apps won't tell me what has been updated nor will they update everything in bulk if I want.

So, the basic functionality is there in pip and easy_install but there are features missing that I'd like to see that would make them friendlier and easier to use and on par with CPAN and RubyGems.

What is the purpose of XSD files?

Before understanding the XSD(XML Schema Definition) let me explain;

What is schema?

for example; emailID: peter#gmail

You can identify the above emailID is not valid because there is no @, .com or .net or .org.

We know the email schema it looks like [email protected].

Conclusion: Schema does not validate the data, It does the validation of structure.

XSD is actually one of the implementation of XML Schema. others we have

We use XSD to validate XML data.

Using an Alias in a WHERE clause

Or you can have your alias in a HAVING clause

Scroll to bottom of div?

You can use the Element.scrollTo() method.

It can be animated using the built-in browser/OS animation, so it's super smooth.

_x000D_
_x000D_
function scrollToBottom() {
    const scrollContainer = document.getElementById('container');
    scrollContainer.scrollTo({
        top: scrollContainer.scrollHeight,
        left: 0,
        behavior: 'smooth'
    });
}

// initialize dummy content
const scrollContainer = document.getElementById('container');
const numCards = 100;
let contentInnerHtml = '';
for (let i=0; i<numCards; i++) {
  contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
}
scrollContainer.innerHTML = contentInnerHtml;
_x000D_
.overflow-y-scroll {
  overflow-y: scroll;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="d-flex flex-column vh-100">
  <div id="container" class="overflow-y-scroll flex-grow-1"></div>
  <div>
    <button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to position three divs in html horizontally?

Get rid of the position:relative; and replace it with float:left; and float:right;.

Example in jsfiddle: http://jsfiddle.net/d9fHP/1/

        <html>
<title>
Website Title </title>
<div id="the whole thing" style="float:left; height:100%; width:100%">
    <div id="leftThing" style="float:left; width:25%; background-color:blue;">
         Left Side Menu
    </div>
    <div id="content" style="float:left; width:50%; background-color:green;">
         Random Content
    </div>
    <div id="rightThing" style="float:right; width:25%; background-color:yellow;">
         Right Side Menu
    </div>
</div>
</html>?

how can get index & count in vuejs

you can just add 1

<li v-for="(catalog, itemObjKey) in catalogs">this index : {{itemObjKey + 1}}</li>

to get the length of an array/objects

{{ catalogs.length }}

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)

$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
    "No explorer process found / Nobody interactively logged on"
}
Else
{
    ForEach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
    }
}

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

The x86 JS simulator and ARM simulator can also be very useful to understand how different pieces hardware works and make tests without exiting your favourite browser.

Replacing blank values (white space) with NaN in pandas

For a very fast and simple solution where you check equality against a single value, you can use the mask method.

df.mask(df == ' ')

cannot load such file -- bundler/setup (LoadError)

I had this because something bad was in my vendor/bundle. Nothing to do with Apache, just in local dev env.

To fix, I deleted vendor\bundle, and also deleted the reference to it in my .bundle/config so it wouldn't get re-used.

Then, I re-bundled (which then installed to GEM_HOME instead of vendor/bundle and the problem went away.

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

Can I set an unlimited length for maxJsonLength in web.config?

I suggest setting it to Int32.MaxValue.

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;

My httpd.conf is empty

The /etc/apache2/httpd.conf is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf!

“httpd.conf is for user options.” No it isn't, it's there for historic reasons.

Using Apache server, all user options should go into a new *.conf-file inside /etc/apache2/conf.d/. This method should be "update-safe", as httpd.conf or apache2.conf may get overwritten on the next server update.

Inside /etc/apache2/apache2.conf, you will find the following line, which includes those files:

# Include generic snippets of statements
Include conf.d/

As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/. Use a2enconf FILENAME_WITHOUT_SUFFIX to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf (e.g. conf-available/my-settings.conf);

Session variables not working php

I had similar issue and with the cookie domain:

    ini_set('session.cookie_domain', '.domain.com');

the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.

How to limit depth for recursive file list?

Make use of find's options

There is actually no exec of /bin/ls needed;

Find has an option that does just that:

find . -maxdepth 2 -type d -ls

To see only the one level of subdirectories you are interested in, add -mindepth to the same level as -maxdepth:

find . -mindepth 2 -maxdepth 2 -type d -ls

Use output formatting

When the details that get shown should be different, -printf can show any detail about a file in custom format; To show the symbolic permissions and the owner name of the file, use -printf with %M and %u in the format.

I noticed later you want the full ownership information, which includes the group. Use %g in the format for the symbolic name, or %G for the group id (like also %U for numeric user id)

find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'

This should give you just the details you need, for just the right files.

I will give an example that shows actually different values for user and group:

$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data  www-data /tmp/user/33
drwx------ octopussy root     /tmp/user/126
drwx------ root      root     /tmp/user/0
drwx------ siegel    root     /tmp/user/1000
drwxrwxrwt root      root     /tmp/systemd-[...].service-HRUQmm/tmp

(Edited for readability: indented, shortened last line)


Notes on performance

Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:

Not only do we save creating a new process for each name - a huge task - the information does not even need to be read, as find already knows it.

How to get the bluetooth devices as a list?

You should change your code as below:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

List<String> s = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices)
   s.add(bt.getName());

setListAdapter(new ArrayAdapter<String>(this, R.layout.list, s));

How to use Apple's new San Francisco font on a webpage

Basically, this is what worked for me:

-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif 

P.S. This works on all systems.

Laravel 5.1 API Enable Cors

I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT and DELETE) which will be preceded by an OPTIONS request, specifying the middleware in the $routeMiddleware array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS as well. This is because without an OPTIONS route Laravel will internally respond to that method without the CORS headers.

So in short either define the middleware in the $middleware array which runs globally for all requests or if you're doing it in $middlewareGroups or $routeMiddleware then also define a route handler for OPTIONS. This can be done like this:

Route::match(['options', 'put'], '/route', function () {
    // This will work with the middleware shown in the accepted answer
})->middleware('cors');

I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    private static $allowedOriginsWhitelist = [
      'http://localhost:8000'
    ];

    // All the headers must be a string

    private static $allowedOrigin = '*';

    private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';

    private static $allowCredentials = 'true';

    private static $allowedHeaders = '';

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if (! $this->isCorsRequest($request))
      {
        return $next($request);
      }

      static::$allowedOrigin = $this->resolveAllowedOrigin($request);

      static::$allowedHeaders = $this->resolveAllowedHeaders($request);

      $headers = [
        'Access-Control-Allow-Origin'       => static::$allowedOrigin,
        'Access-Control-Allow-Methods'      => static::$allowedMethods,
        'Access-Control-Allow-Headers'      => static::$allowedHeaders,
        'Access-Control-Allow-Credentials'  => static::$allowCredentials,
      ];

      // For preflighted requests
      if ($request->getMethod() === 'OPTIONS')
      {
        return response('', 200)->withHeaders($headers);
      }

      $response = $next($request)->withHeaders($headers);

      return $response;
    }

    /**
     * Incoming request is a CORS request if the Origin
     * header is set and Origin !== Host
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function isCorsRequest($request)
    {
      $requestHasOrigin = $request->headers->has('Origin');

      if ($requestHasOrigin)
      {
        $origin = $request->headers->get('Origin');

        $host = $request->getSchemeAndHttpHost();

        if ($origin !== $host)
        {
          return true;
        }
      }

      return false;
    }

    /**
     * Dynamic resolution of allowed origin since we can't
     * pass multiple domains to the header. The appropriate
     * domain is set in the Access-Control-Allow-Origin header
     * only if it is present in the whitelist.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function resolveAllowedOrigin($request)
    {
      $allowedOrigin = static::$allowedOrigin;

      // If origin is in our $allowedOriginsWhitelist
      // then we send that in Access-Control-Allow-Origin

      $origin = $request->headers->get('Origin');

      if (in_array($origin, static::$allowedOriginsWhitelist))
      {
        $allowedOrigin = $origin;
      }

      return $allowedOrigin;
    }

    /**
     * Take the incoming client request headers
     * and return. Will be used to pass in Access-Control-Allow-Headers
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function resolveAllowedHeaders($request)
    {
      $allowedHeaders = $request->headers->get('Access-Control-Request-Headers');

      return $allowedHeaders;
    }
}

Also written a blog post on this.

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

How to prevent gcc optimizing some statements in C?

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to disable clicking inside div

If you want it in pure CSS:

pointer-events:none;

Please initialize the log4j system properly warning

What worked for me is to create a log4j properties file (you can find many examples over the net) and place it in properties folder in your project directory (create this folder if not exicts). The right click on the folder and Build Path->Use as Source Folder.

Hope it helps!

How can I count the number of characters in a Bash variable

${#str_var}  

where str_var is your string.

How to convert Base64 String to javascript file object like as from file input form?

This is the latest async/await pattern solution.

export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {

    const res: Response = await fetch(dataUrl);
    const blob: Blob = await res.blob();
    return new File([blob], fileName, { type: 'image/png' });
}

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

Most Pythonic way to provide global configuration variables in config.py?

A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:

#globals.py

class dbinfo :      # for database globals
    username = 'abcd'
    password = 'xyz'

class runtime :
    debug = False
    output = 'stdio'

Then, if you have two code files c1.py and c2.py, both can have at the top

import globals as gl

Now all code can access and set values, as such:

gl.runtime.debug = False
print(gl.dbinfo.username)

People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.

By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.

This lacks some of the clever error checking of other approaches, but is simple and easy to follow.

Convert String to SecureString

You don't. The whole reason for using the SecureString object is to avoid creating a string object (which is loaded into memory and kept there in plaintext until garbage collection). However, you can add characters to a SecureString by appending them.

var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');

Are static methods inherited in Java?

This concept is not that easy as it looks. We can access static members without inheritance, which is HasA-relation. We can access static members by extending the parent class also. That doesn't imply that it is an ISA-relation (Inheritance). Actually static members belong to the class, and static is not an access modifier. As long as the access modifiers permit to access the static members we can use them in other classes. Like if it is public then it will be accessible inside the same package and also outside the package. For private we can't use it anywhere. For default, we can use it only within the package. But for protected we have to extend the super class. So getting the static method to other class does not depend on being Static. It depends on Access modifiers. So, in my opinion, Static members can access if the access modifiers permit. Otherwise, we can use them like we use by Hasa-relation. And has a relation is not inheritance. Again we can not override the static method. If we can use other method but cant override it, then it is HasA-relation. If we can't override them it won't be inheritance.So the writer was 100% correct.

HTML5 tag for horizontal line break

Instead of using <hr>, you can one of the border of the enclosing block and display it as a horizontal line.

Here is a sample code:

The HTML:

<div class="title_block">
    <h3>This is a header.</h3>
</div>
<p>Here is some sample paragraph text.<br>
This demonstrates that a horizontal line goes between the title and the paragraph.</p>

The CSS:

.title_block {
    border-bottom: 1px solid #ddd;
    padding-bottom: 5px;
    margin-bottom: 5px;
}

Convert object to JSON in Android

Most people are using gson : check this

Gson gson = new Gson();
String json = gson.toJson(myObj);

How to change the default collation of a table?

To change the default character set and collation of a table including those of existing columns (note the convert to clause):

alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;

Edited the answer, thanks to the prompting of some comments:

Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41

and

That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46

How to search file text for a pattern and replace it with a given value

Here's a solution for find/replace in all files of a given directory. Basically I took the answer provided by sepp2k and expanded it.

# First set the files to search/replace in
files = Dir.glob("/PATH/*")

# Then set the variables for find/replace
@original_string_or_regex = /REGEX/
@replacement_string = "STRING"

files.each do |file_name|
  text = File.read(file_name)
  replace = text.gsub!(@original_string_or_regex, @replacement_string)
  File.open(file_name, "w") { |file| file.puts replace }
end

How to remove the character at a given index from a string in C?

memmove can handle overlapping areas, I would try something like that (not tested, maybe +-1 issue)

char word[] = "abcdef";  
int idxToDel = 2; 
memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

Before: "abcdef"

After: "abdef"

Can I change the fill color of an svg path with CSS?

you put this css for svg circle.

svg:hover circle{
    fill: #F6831D;
    stroke-dashoffset: 0;
    stroke-dasharray: 700;
    stroke-width: 2;
}

Is there a naming convention for MySQL?

I would say that first and foremost: be consistent.

I reckon you are almost there with the conventions that you have outlined in your question. A couple of comments though:

Points 1 and 2 are good I reckon.

Point 3 - sadly this is not always possible. Think about how you would cope with a single table foo_bar that has columns foo_id and another_foo_id both of which reference the foo table foo_id column. You might want to consider how to deal with this. This is a bit of a corner case though!

Point 4 - Similar to Point 3. You may want to introduce a number at the end of the foreign key name to cater for having more than one referencing column.

Point 5 - I would avoid this. It provides you with little and will become a headache when you want to add or remove columns from a table at a later date.

Some other points are:

Index Naming Conventions

You may wish to introduce a naming convention for indexes - this will be a great help for any database metadata work that you might want to carry out. For example you might just want to call an index foo_bar_idx1 or foo_idx1 - totally up to you but worth considering.

Singular vs Plural Column Names

It might be a good idea to address the thorny issue of plural vs single in your column names as well as your table name(s). This subject often causes big debates in the DB community. I would stick with singular forms for both table names and columns. There. I've said it.

The main thing here is of course consistency!

Get latest from Git branch

Although git pull origin yourbranch works, it's not really a good idea

You can alternatively do the following:

git fetch origin
git merge origin/yourbranch

The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.

The second line merges your current branch with that of yourbranch that you fetched from origin (which is one of your remotes).

This is assuming origin points to the repository at address ssh://11.21.3.12:23211/dir1/dir2

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.

As soon as you show a Dialog it throws the error:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

You can see its a MessageBox causing the problem in the stack trace:

at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon,  MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)  

Solution

If you're running your app on a Scheduled Task send an email instead of showing a Dialog.

Can we create an instance of an interface in Java?

Yes it is correct. you can do it with an inner class.

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

Creating for loop until list.length

Yes you can, with range [docs]:

for i in range(1, len(l)):
    # i is an integer, you can access the list element with l[i]

but if you are accessing the list elements anyway, it's more natural to iterate over them directly:

for element in l:
   # element refers to the element in the list, i.e. it is the same as l[i]

If you want to skip the the first element, you can slice the list [tutorial]:

for element in l[1:]:
    # ...

can you do another for loop inside this for loop

Sure you can.

PHP Sort a multidimensional array by element containing date

For 'd/m/Y' dates:

usort($array, function ($a, $b, $i = 'datetime') { 
    $t1 = strtotime(str_replace('/', '-', $a[$i]));
    $t2 = strtotime(str_replace('/', '-', $b[$i]));

    return $t1 > $t2;
});

where $i is the array index

How are echo and print different in PHP?

As the PHP.net manual suggests, take a read of this discussion.

One major difference is that echo can take multiple parameters to output. E.g.:

echo 'foo', 'bar';   // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error

If you're looking to evaluate the outcome of an output statement (as below) use print. If not, use echo.

$res = print('test');
var_dump($res); //bool(true)

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

If you get this error due to foreach and you really need to save one entity first inside loop and use generated identity further in loop, as was in my case, the easiest solution is to use another DBContext to insert entity which will return Id and use this Id in outer context

For example

    using (var context = new DatabaseContext())
    {
        ...
        using (var context1 = new DatabaseContext())
        {
            ...
               context1.SaveChanges();
        }                         
        //get id of inserted object from context1 and use is.   
      context.SaveChanges();
   }

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you want to present a new view in the same storyboard,

In CurrentViewController.m,

#import "YourViewController.h"

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];

To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

How to filter in NaN (pandas)?

Pandas uses numpy's NaN value. Use numpy.isnan to obtain a Boolean vector from a pandas series.

"Expected an indented block" error?

You have to indent the docstring after the function definition there (line 3, 4):

def print_lol(the_list):
"""this doesn't works"""
    print 'Ain't happening'

Indented:

def print_lol(the_list):
    """this works!"""
    print 'Aaaand it's happening'

Or you can use # to comment instead:

def print_lol(the_list):
#this works, too!
    print 'Hohoho'

Also, you can see PEP 257 about docstrings.

Hope this helps!

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

SimpleXML - I/O warning : failed to load external entity

You can also load the content with cURL, if file_get_contents insn't enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

How to increment a variable on a for loop in jinja template?

if anyone want to add a value inside loop then you can use this its working 100%

{% set ftotal= {'total': 0} %} 
{%- for pe in payment_entry -%}
    {% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %} 
{%- endfor -%}

{{ftotal.total}}

output = 5

Subtracting two lists in Python

I'm not sure what the objection to a for loop is: there is no multiset in Python so you can't use a builtin container to help you out.

Seems to me anything on one line (if possible) will probably be helishly complex to understand. Go for readability and KISS. Python is not C :)

How to clear mysql screen console in windows?

SQL> clear scr

This command clears the screen in MYSQL

Is having an 'OR' in an INNER JOIN condition a bad idea?

I use following code for get different result from condition That worked for me.


Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)

Communication between tabs or windows

This is a development storage part of Tomas M answer for Chrome. We must add listener

window.addEventListener("storage", (e)=> { console.log(e) } );

Load/save item in storage not runt this event - we MUST trigger it manually by

window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME

and now, all open tab-s will receive event

requestFeature() must be called before adding content

I had this issue with Dialogs based on an extended DialogFragment which worked fine on devices running API 26 but failed with API 23. The above strategies didn't work but I resolved the issue by removing the onCreateView method (which had been added by a more recent Android Studio template) from the DialogFragment and creating the dialog in onCreateDialog.

How to implement class constructor in Visual Basic?

Suppose your class is called MyStudent. Here's how you define your class constructor:

Public Class MyStudent
    Public StudentId As Integer

    'Here's the class constructor:
    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Here's how you call it:

Dim student As New MyStudent(studentId)

Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.

How to determine the Boost version on a system?

If you only need to know for your own information, just look in /usr/include/boost/version.hpp (Ubuntu 13.10) and read the information directly

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

I also Struggled with el captain installed. I installed the VirtualBox 4.3.26 version. Other latest versions doesnt worked for me. It works like a charm :)

Strip HTML from Text JavaScript

I would like to share an edited version of the Shog9's approved answer.


As Mike Samuel pointed with a comment, that function can execute inline javascript codes.
But Shog9 is right when saying "let the browser do it for you..."

so.. here my edited version, using DOMParser:

function strip(html){
   let doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

here the code to test the inline javascript:

strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")

Also, it does not request resources on parse (like images)

strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")

How do I do a Date comparison in Javascript?

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

module.exports vs. export default in Node.js and ES6

You need to configure babel correctly in your project to use export default and export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

then add below configration in .babelrc

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]

Filename too long in Git for Windows

The better solution is enable the longpath parameter from Git.

git config --system core.longpaths true

But a workaround that works is remove the node_modules folder from Git:

$ git rm -r --cached node_modules
$ vi .gitignore

Add node_modules in a new row inside the .gitignore file. After doing this, push your modifications:

$ git add .gitignore
$ git commit -m "node_modules removed"
$ git push

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:

0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)

Then I can declare something like

typedef struct {
  uint8_t msgType;
  uint16_t targetAddr; // may have to bswap
  uint8_t data[12];
  uint8_t checksum;
} __attribute__((packed)) myStruct;

and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.

Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.

Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)

Android change SDK version in Eclipse? Unable to resolve target android-x

Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):

SELECT DISTINCT Left(LastName, 1)
FROM Authors;

SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

Bootstrap center heading

.text-left {
  text-align: left;
}

.text-right {
  text-align: right;
}

.text-center {
  text-align: center;
}

bootstrap has added three css classes for text align.

List of all unique characters in a string?

Use an OrderedDict. This will ensure that the order is preserved

>>> ''.join(OrderedDict.fromkeys( "aaabcabccd").keys())
'abcd'

PS: I just timed both the OrderedDict and Set solution, and the later is faster. If order does not matter, set should be the natural solution, if Order Matter;s this is how you should do.

>>> from timeit import Timer
>>> t1 = Timer(stmt=stmt1, setup="from __main__ import data, OrderedDict")
>>> t2 = Timer(stmt=stmt2, setup="from __main__ import data")
>>> t1.timeit(number=1000)
1.2893918431815337
>>> t2.timeit(number=1000)
0.0632140599081196

Difference between binary tree and binary search tree

Binary Tree stands for a data structure which is made up of nodes that can only have two children references.

Binary Search Tree (BST) on the other hand, is a special form of Binary Tree data structure where each node has a comparable value, and smaller valued children attached to left and larger valued children attached to the right.

Thus, all BST's are Binary Tree however only some Binary Tree's may be also BST. Notify that BST is a subset of Binary Tree.

So, Binary Tree is more of a general data-structure than Binary Search Tree. And also you have to notify that Binary Search Tree is a sorted tree whereas there is no such set of rules for generic Binary Tree.

Binary Tree

A Binary Tree which is not a BST;

         5
       /   \
      /     \
     9       2
    / \     / \
  15   17  19  21

Binary Search Tree (sorted Tree)

A Binary Search Tree which is also a Binary Tree;

         50
       /    \
      /      \
     25      75
    /  \    /  \
  20    30 70   80

Binary Search Tree Node property

Also notify that for any parent node in the BST;

  • All the left nodes have smaller value than the value of the parent node. In the upper example, the nodes with values { 20, 25, 30 } which are all located on the left (left descendants) of 50, are smaller than 50.

  • All the right nodes have greater value than the value of the parent node. In the upper example, the nodes with values { 70, 75, 80 } which are all located on the right (right descendants) of 50, are greater than 50.

There is no such a rule for Binary Tree Node. The only rule for Binary Tree Node is having two childrens so it self-explains itself that why called binary.

Set adb vendor keys

I had the same problem running Ubuntu 18.04. I tried multiple solutions but my device (OnePlus 5T) was always unauthorized.

Solution

  1. Configure udev rules on Ubuntu. To do this, just follow the official documentation: https://developer.android.com/studio/run/device

    The idVendor of my device (OnePlus) is not listed. To get it, just connect your device and use lsusb:

    Bus 003 Device 008: ID 2a70:4ee7

    In this example, 2a70 is the idVendor.

  2. Remove existing adb keys on Ubuntu:

    rm -v ~/.android/adbkey* ~/.android/adbkey ~/.android/adbkey.pub

  3. 'Revoke USB debugging authorizations' on your device configuration (developer options).

  4. Finally, restart the adb server to create a new key:

    sudo adb kill-server sudo adb devices

After that, I got the authorization prompt on my device and I authorized it.

Combining node.js and Python

This sounds like a scenario where zeroMQ would be a good fit. It's a messaging framework that's similar to using TCP or Unix sockets, but it's much more robust (http://zguide.zeromq.org/py:all)

There's a library that uses zeroMQ to provide a RPC framework that works pretty well. It's called zeroRPC (http://www.zerorpc.io/). Here's the hello world.

Python "Hello x" server:

import zerorpc

class HelloRPC(object):
    '''pass the method a name, it replies "Hello name!"'''
    def hello(self, name):
        return "Hello, {0}!".format(name)

def main():
    s = zerorpc.Server(HelloRPC())
    s.bind("tcp://*:4242")
    s.run()

if __name__ == "__main__" : main()

And the node.js client:

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
//calls the method on the python object
client.invoke("hello", "World", function(error, reply, streaming) {
    if(error){
        console.log("ERROR: ", error);
    }
    console.log(reply);
});

Or vice-versa, node.js server:

var zerorpc = require("zerorpc");

var server = new zerorpc.Server({
    hello: function(name, reply) {
        reply(null, "Hello, " + name, false);
    }
});

server.bind("tcp://0.0.0.0:4242");

And the python client

import zerorpc, sys

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
name = sys.argv[1] if len(sys.argv) > 1 else "dude"
print c.hello(name)

Changing width property of a :before css selector using JQuery

I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style element to the document's head like:

$('head').append('<style>.column:before{width:800px !important;}</style>');

See a live demo here

I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:

/var/www/*

Or type:

find /var/www -name index.html -print

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I had a similar issue when I checked out a web project from a github repo on my eclipse. src/main/java was directly inside the project root in Package Explorer. My expectation was that src/main/java be visible inside a source folder "Java Resources". There were few things which I did to achieve this.

  1. Right click on Project > Build Path > Configure Build Path..
  2. Select filter "Java Build Path" and click on Tab "Libraries" Verify your "JRE System Library". If it is not pointing to your latest JDK, then you can click on Edit Button and follow the subsequent dialog boxes to select most appropriate JDK home path in your system. Once done click Apply, Apply and Close, Finish to close all the associated open boxes for the current filter.
  3. Select filter "Java Compiler" and ensure your JDK Compliance points to correct JDK. Click Aapply
  4. Select filter "Project Facets". Ensure both Java and Dynamic Web Module is selected with correct version.
  5. Click Apply and Close.
  6. Source folder "Java Resources" gets created with src/main/java in it when viewed in Project Explorer.

How can I set / change DNS using the command-prompt at windows 8

First, the network name is likely "Ethernet", not "Local Area Connection". To find out the name you can do this:

netsh interface show interface

Which will show the name under the "Interface Name" column (shown here in bold):

Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Connected      Dedicated        Ethernet

Now you can change the primary dns (index=1), assuming that your interface is static (not using dhcp):

netsh interface ipv4 add dnsserver "Ethernet" address=192.168.x.x index=1

2018 Update - The command will work with either dnsserver (singular) or dnsservers (plural). The following example uses the latter and is valid as well:

netsh interface ipv4 add dnsservers "Ethernet" address=192.168.x.x index=1

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

Upgrade python in a virtualenv

If you happen to be using the venv module that comes with Python 3.3+, it supports an --upgrade option. Per the docs:

Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place

python3 -m venv --upgrade ENV_DIR

How to check if pytorch is using the GPU?

On the office site and the get start page, check GPU for PyTorch as below:

import torch
torch.cuda.is_available()

Reference: PyTorch|Get Start

nvarchar(max) still being truncated

The problem with creating dynamic SQL using string expression is that SQL does limit the evaluation of string expressions to 4,000 chars. You can assign a longer string to an nvarchar(max) variable, but as soon as you include + in the expression (such as + CASE ... END + ), then the expression result is limited to 4,000 chars.

One way to fix this is to use CONCAT instead of +. For example:

SET @sql = CONCAT(@sql, N'
     ... dynamic SQL statements ...
    ', CASE ... END, N'
     ... dynamic SQL statements ...
    ')

Where @sql is declared as nvarchar(max).

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);

And

<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>

In javaScript:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>

Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.

How to find the privileges and roles granted to a user in Oracle?

In addition to VAV's answer, The first one was most useful in my environment

select * from USER_ROLE_PRIVS where USERNAME='SAMPLE';
select * from USER_TAB_PRIVS where Grantee = 'SAMPLE';
select * from USER_SYS_PRIVS where USERNAME = 'SAMPLE';

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

I suggest you use Promise

myApp.service('dataService', function($http,$q) {

  delete $http.defaults.headers.common['X-Requested-With'];
  this.getData = function() {
     deferred = $q.defer();
     $http({
         method: 'GET',
         url: 'https://www.example.com/api/v1/page',
         params: 'limit=10, sort_by=created:desc',
         headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
     }).success(function(data){
         // With the data succesfully returned, we can resolve promise and we can access it in controller
         deferred.resolve();
     }).error(function(){
          alert("error");
          //let the function caller know the error
          deferred.reject(error);
     });
     return deferred.promise;
  }
});

so In your controller you can use the method

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(response) {
        $scope.data = response;
    });
});

promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.

How can I make a CSS glass/blur effect work for an overlay?

Here's a solution that works with fixed backgrounds, if you have a fixed background and you have some overlayed elements and you need blured backgrounds for them, this solution works:

Image we have this simple HTML:

<body> <!-- or any wrapper -->
   <div class="content">Some Texts</div>
</body>

A fixed background for <body> or the wrapper element:

body {
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

And here for example we have a overlayed element with a white transparent background:

.content {
  background-color: rgba(255, 255, 255, 0.3);
  position: relative;
}

Now we need to use the exact same background image of our wrapper for our overlay elements too, i use it as a :before psuedo-class:

.content:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: blur(5px);
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

Since the fixed background works in a same way in both wrapper and overlayed elements, we have the background in exactly same scroll position of the overlayed element and we can simply blur it. Here's a working fiddle, tested in Firefox, Chrome, Opera and Edge: https://jsfiddle.net/0vL2rc4d/

NOTE: In firefox there's a bug that makes screen flicker when scrolling and there are fixed blurred backgrounds. if there's any fix, let me know

How to take the first N items from a generator or list?

import itertools

top5 = itertools.islice(array, 5)

How do I raise the same Exception with a custom message in Python?

The current answer did not work good for me, if the exception is not re-caught the appended message is not shown.

But doing like below both keeps the trace and shows the appended message regardless if the exception is re-caught or not.

try:
  raise ValueError("Original message")
except ValueError as err:
  t, v, tb = sys.exc_info()
  raise t, ValueError(err.message + " Appended Info"), tb

( I used Python 2.7, have not tried it in Python 3 )

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

More info: http://laravel.com/docs/eloquent#query-scopes

In angular $http service, How can I catch the "status" of error?

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

Taken from the angular docs:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

Simple java program of pyramid

You can try in this way.

   for(int a=5;a>0;a--){
        int b=0;
       for(b=0;b<a;b++){
           System.out.print(" ");
       }
        for (int j=b;j<5;j++){
            System.out.print(" $ ");
        }
        System.out.println("");

    }

Out put

      $ 
     $  $ 
    $  $  $ 
   $  $  $  $ 

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

CMD command to check connected USB devices

You could use wmic command:

wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>

Drivetype 2 indicates that its a removable disk.

Javascript code for showing yesterday's date and todays date

Yesterday Date can be calculated as:-

let now = new Date();
    var defaultDate = now - 1000 * 60 * 60 * 24 * 1;
    defaultDate = new Date(defaultDate);

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

Maybe not very elegant, but it does the job:

exec(open("script.py").read())

jquery get all input from specific form

The below code helps to get the details of elements from the specific form with the form id,

$('#formId input, #formId select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements from all the forms which are place in the loading page,

$('form input, form select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,

$('input, select').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

NOTE: We add the more element tag name what we need in the object list like as below,

Example: to get name of attribute "textarea",

$('input, select, textarea').each(
    function(index){  
        var input = $(this);
        alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
    }
);

Safely limiting Ansible playbooks to a single machine?

Since version 1.7 ansible has the run_once option. Section also contains some discussion of various other techniques.

Element-wise addition of 2 lists?

If you need to handle lists of different sizes, worry not! The wonderful itertools module has you covered:

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>

In Python 2, zip_longest is called izip_longest.

See also this relevant answer and comment on another question.

A cron job for rails: best practices?

Use Craken (rake centric cron jobs)

How can building a heap be O(n) time complexity?

I think there are several questions buried in this topic:

  • How do you implement buildHeap so it runs in O(n) time?
  • How do you show that buildHeap runs in O(n) time when implemented correctly?
  • Why doesn't that same logic work to make heap sort run in O(n) time rather than O(n log n)?

How do you implement buildHeap so it runs in O(n) time?

Often, answers to these questions focus on the difference between siftUp and siftDown. Making the correct choice between siftUp and siftDown is critical to get O(n) performance for buildHeap, but does nothing to help one understand the difference between buildHeap and heapSort in general. Indeed, proper implementations of both buildHeap and heapSort will only use siftDown. The siftUp operation is only needed to perform inserts into an existing heap, so it would be used to implement a priority queue using a binary heap, for example.

I've written this to describe how a max heap works. This is the type of heap typically used for heap sort or for a priority queue where higher values indicate higher priority. A min heap is also useful; for example, when retrieving items with integer keys in ascending order or strings in alphabetical order. The principles are exactly the same; simply switch the sort order.

The heap property specifies that each node in a binary heap must be at least as large as both of its children. In particular, this implies that the largest item in the heap is at the root. Sifting down and sifting up are essentially the same operation in opposite directions: move an offending node until it satisfies the heap property:

  • siftDown swaps a node that is too small with its largest child (thereby moving it down) until it is at least as large as both nodes below it.
  • siftUp swaps a node that is too large with its parent (thereby moving it up) until it is no larger than the node above it.

The number of operations required for siftDown and siftUp is proportional to the distance the node may have to move. For siftDown, it is the distance to the bottom of the tree, so siftDown is expensive for nodes at the top of the tree. With siftUp, the work is proportional to the distance to the top of the tree, so siftUp is expensive for nodes at the bottom of the tree. Although both operations are O(log n) in the worst case, in a heap, only one node is at the top whereas half the nodes lie in the bottom layer. So it shouldn't be too surprising that if we have to apply an operation to every node, we would prefer siftDown over siftUp.

The buildHeap function takes an array of unsorted items and moves them until they all satisfy the heap property, thereby producing a valid heap. There are two approaches one might take for buildHeap using the siftUp and siftDown operations we've described.

  1. Start at the top of the heap (the beginning of the array) and call siftUp on each item. At each step, the previously sifted items (the items before the current item in the array) form a valid heap, and sifting the next item up places it into a valid position in the heap. After sifting up each node, all items satisfy the heap property.

  2. Or, go in the opposite direction: start at the end of the array and move backwards towards the front. At each iteration, you sift an item down until it is in the correct location.

Which implementation for buildHeap is more efficient?

Both of these solutions will produce a valid heap. Unsurprisingly, the more efficient one is the second operation that uses siftDown.

Let h = log n represent the height of the heap. The work required for the siftDown approach is given by the sum

(0 * n/2) + (1 * n/4) + (2 * n/8) + ... + (h * 1).

Each term in the sum has the maximum distance a node at the given height will have to move (zero for the bottom layer, h for the root) multiplied by the number of nodes at that height. In contrast, the sum for calling siftUp on each node is

(h * n/2) + ((h-1) * n/4) + ((h-2)*n/8) + ... + (0 * 1).

It should be clear that the second sum is larger. The first term alone is hn/2 = 1/2 n log n, so this approach has complexity at best O(n log n).

How do we prove the sum for the siftDown approach is indeed O(n)?

One method (there are other analyses that also work) is to turn the finite sum into an infinite series and then use Taylor series. We may ignore the first term, which is zero:

Taylor series for buildHeap complexity

If you aren't sure why each of those steps works, here is a justification for the process in words:

  • The terms are all positive, so the finite sum must be smaller than the infinite sum.
  • The series is equal to a power series evaluated at x=1/2.
  • That power series is equal to (a constant times) the derivative of the Taylor series for f(x)=1/(1-x).
  • x=1/2 is within the interval of convergence of that Taylor series.
  • Therefore, we can replace the Taylor series with 1/(1-x), differentiate, and evaluate to find the value of the infinite series.

Since the infinite sum is exactly n, we conclude that the finite sum is no larger, and is therefore, O(n).

Why does heap sort require O(n log n) time?

If it is possible to run buildHeap in linear time, why does heap sort require O(n log n) time? Well, heap sort consists of two stages. First, we call buildHeap on the array, which requires O(n) time if implemented optimally. The next stage is to repeatedly delete the largest item in the heap and put it at the end of the array. Because we delete an item from the heap, there is always an open spot just after the end of the heap where we can store the item. So heap sort achieves a sorted order by successively removing the next largest item and putting it into the array starting at the last position and moving towards the front. It is the complexity of this last part that dominates in heap sort. The loop looks likes this:

for (i = n - 1; i > 0; i--) {
    arr[i] = deleteMax();
}

Clearly, the loop runs O(n) times (n - 1 to be precise, the last item is already in place). The complexity of deleteMax for a heap is O(log n). It is typically implemented by removing the root (the largest item left in the heap) and replacing it with the last item in the heap, which is a leaf, and therefore one of the smallest items. This new root will almost certainly violate the heap property, so you have to call siftDown until you move it back into an acceptable position. This also has the effect of moving the next largest item up to the root. Notice that, in contrast to buildHeap where for most of the nodes we are calling siftDown from the bottom of the tree, we are now calling siftDown from the top of the tree on each iteration! Although the tree is shrinking, it doesn't shrink fast enough: The height of the tree stays constant until you have removed the first half of the nodes (when you clear out the bottom layer completely). Then for the next quarter, the height is h - 1. So the total work for this second stage is

h*n/2 + (h-1)*n/4 + ... + 0 * 1.

Notice the switch: now the zero work case corresponds to a single node and the h work case corresponds to half the nodes. This sum is O(n log n) just like the inefficient version of buildHeap that is implemented using siftUp. But in this case, we have no choice since we are trying to sort and we require the next largest item be removed next.

In summary, the work for heap sort is the sum of the two stages: O(n) time for buildHeap and O(n log n) to remove each node in order, so the complexity is O(n log n). You can prove (using some ideas from information theory) that for a comparison-based sort, O(n log n) is the best you could hope for anyway, so there's no reason to be disappointed by this or expect heap sort to achieve the O(n) time bound that buildHeap does.

Get a random item from a JavaScript array

// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})

// 2. Get first item
var item = items[0]

Shorter:

var item = items.sort(function() {return 0.5 - Math.random()})[0];

What are the differences in die() and exit() in PHP?

This page says die is an alies of exit, so they are identical. But also explains that:

there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script.

So, call me paranoid, but there may be no dieing in the future.

HTML5 Canvas vs. SVG vs. div

While there is still some truth to most of the answers above, I think they deserve an update:

Over the years the performance of SVG has improved a lot and now there is hardware-accelerated CSS transitions and animations for SVG that do not depend on JavaScript performance at all. Of course JavaScript performance has improved, too and with it the performance of Canvas, but not as much as SVG got improved. Also there is a "new kid" on the block that is available in almost all browsers today and that is WebGL. To use the same words that Simon used above: It beats both Canvas and SVG hands down. This doesn't mean it should be the go-to technology, though, since it's a beast to work with and it is only faster in very specific use-cases.

IMHO for most use-cases today, SVG gives the best performance/usability ratio. Visualizations need to be really complex (with respect to number of elements) and really simple at the same time (per element) so that Canvas and even more so WebGL really shine.

In this answer to a similar question I am providing more details, why I think that the combination of all three technologies sometimes is the best option you have.