Programs & Examples On #Iis 7.5

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

HTTP Error 404.3-Not Found in IIS 7.5

You should install IIS sub components from

Control Panel -> Programs and Features -> Turn Windows features on or off

Internet Information Services has subsection World Wide Web Services / Application Development Features

There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.

Run from cmd:

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

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.

Also, look at this answer.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Check if there is any conflict in your IIS authentication. i.e. you enable the anonymous authentication and ASP.NET impersonation both might cause the error also.

Viewing my IIS hosted site on other machines on my network

In addition to modifying your firewall, don't forget to add port binding too!

Open $(SolutionDir)\.vs\config\applicationHost.config and find binding definitions, should be something like this

<sites>
    <site name="Samples.Html5.Web" id="1">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
            <virtualDirectory path="/" physicalPath="C:\Git\Samples.Html5.Web" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:63000:localhost" />
        </bindings>
    </site>
    ...
</sites>

Just add extra lines to reflect your machine IP and designated port

<bindings>
    <binding protocol="http" bindingInformation="*:63000:localhost" />
    <binding protocol="http" bindingInformation="*:63000:10.0.0.201" />
</bindings>

Source: https://blog.falafel.com/expose-iis-express-site-local-network/

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

There is one way that I have used my self. Go to Control Panel\Programs\Turn Windows features on or off then uninstall IIS and all of its components completely. I restart windows but I'm not sure if it's required or not. Then install it again from the same path.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.

TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.

How do I give ASP.NET permission to write to a folder in Windows 7?

The full command would be something like below, notice the quotes

icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"

Detailed 500 error message, ASP + IIS 7.5

Found it.

http://blogs.iis.net/ksingla/archive/2009/02/16/iis-7-5-updates-to-custom-errors-and-compression.aspx

run cmd as administrator, go to your system32\inetsrv folder and execute:

appcmd.exe set config -section:system.webServer/httpErrors -allowAbsolutePathsWhenDelegated:true

Now I can see detailed asp errors .

Register .NET Framework 4.5 in IIS 7.5

Hosting asp.net 4.5/4.5.1 Web application on Local IIS 1)Be Sure IIS Installation before Visual Installation Installataion then aspnet_regiis will already registerd with IIS

If Not Install IIS and then Register aspnet_regiis with IIS by cmd Editor

For VS2012 and 32 bit OS Run Below code on command editor :

1)Install IIS First & then

2)

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319   

  C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i

For VS2012 and 64 bit OS Below code on command editor:

1)Install IIS First & then

2)

cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319    
  C:\Windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis -i

BY Following Above Steps Current Version of VS2012 registered with IIS Hosting (VS2012 Web APP)

Create VS2012 Web Application(WebForm/MVC) then Build Application Right Click On WebApplication(WebForm/MVC) go to 'Properties' Click On 'Web' Tab on then 'Use Local IIS Web Server' Then Uncheck 'Use IIS Express' (If Visul Studio 2013 Select 'Local IIS' from Dropdown) Provide Project Url like "http://localhost/MvcDemoApp" Then Click On 'Create Virtual Directory' Button Then Open IIS by Prssing 'Window + R' Run Command and type 'inetmgr' and 'Enter' (or 'OK' Button) Then Expand 'Sites->Default Web Site' you Hosted Successfully. If Still Gets any Server Error like 'The resource cannot be found.' Then Include following code in web.config

 <configuration>
     <system.webServer>
         <modules runAllManagedModulesForAllRequests="true"></modules>

And Run Application

If still problem occurs Check application pool by : In iis Right click on application->Manage Application->Advanced setting->General. you see the application pool. then close advance setting window. click on 'Application Pools' you will see the all application pools in middle window. Right click on application pool in which application hosted(DefaultAppPool). click 'Basic Setting' -> Change .Net FrameWork Version to->.Net FrameWork v4.0.30349

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config Listen [::0]:8080

IIS error, Unable to start debugging on the webserver

None of the other solutions worked for me. I resolved this issue by using the commands below.

For 32 bit machine:

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis –i

For 64 bit machine:

C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis –i

The issue is because the web.config file is not installed correctly.

How prevent CPU usage 100% because of worker process in iis

Diagnosing

In terms of diagnosing what App Pool is causing trouble, you can:

  1. Select the server
  2. Go to IIS > Worker Processes

Server Settings

This should bring up a menu like this so you can determine which App Pool is running amok.

Worker Processes

From there you can simply restart the the app pool and 9 times out of 10 that will fix any immediate issues you're having.

Treating

Unless you run some sort of controversial business, this is probably not a DDOS attack. It's likely that some code is just hanging because it couldn't get through to another server or got stuck in a loop or mis-allocated resources or your app pool just hasn't been recycled in a while.

You can deal with this problem programmatically without having to manually identify, log in, and recycle the app pool. Just configure the CPU property on your App Pool. You can have it kill (and automatically restart) your process anytime you reach a CPU threshold for a certain amount of time.

In your case, if you want it to restart at 80%, you can right click on the app pool and go to Advanced Settings and apply the following configurations:

App Pool Advanced Settings

NOTE: As kraken101 pointed out, different IIS GUIs have treated this differently over time. While the config value is always in 1/1000 of a %, sometimes the GUI takes the whole percent.

You can add this to your config section like this:

<applicationPools>
   <add name="DefaultAppPool">
     <cpu limit="80000" action="KillW3wp" resetInterval="00:01:00" />
   </add>
</applicationPools>

Alternatively, you could script it with Powershell's WebAdministration Module like this:
(*make sure web-scripting-tools is enabled)

Import-Module WebAdministration

$appPoolName = "DefaultAppPool"
$appPool = Get-Item "IIS:\AppPools\$appPoolName"
$appPool.cpu.limit = 80000
$appPool.cpu.action = "KillW3wp"
$appPool.cpu.resetInterval = "00:01:00"
$appPool | Set-Item

Preventing

The steps above will help fix some things once they've broken, but won't really solve any underlying issues you have.

Here are some resources on doing performance monitoring:

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Old question but anyway !

Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)

So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!

How do I get to IIS Manager?

First of all, you need to check that the IIS is installed in your machine, for that you can go to:

Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'

If not, check it, and Press Accept to install it.

Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).

Edit: You should have something like this: enter image description here

Script not served by static file handler on IIS7.5

Register asp.net again....will solve the issue.
enter image description here

Go to Visual Studio Command Prompt,
And register asp.net as windows\microsoft.net\Framework[.Net version num]\aspnet_regiis.exe -i

Fixing slow initial load for IIS

Options A, B and D seem to be in the same category since they only influence the initial start time, they do warmup of the website like compilation and loading of libraries in memory.

Using C, setting the idle timeout, should be enough so that subsequent requests to the server are served fast (restarting the app pool takes quite some time - in the order of seconds).

As far as I know, the timeout exists to save memory that other websites running in parallel on that machine might need. The price being that one time slow load time.

Besides the fact that the app pool gets shutdown in case of user inactivity, the app pool will also recycle by default every 1740 minutes (29 hours).

From technet:

Internet Information Services (IIS) application pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks.

As long as app pool recycling is left on, it should be enough. But if you really want top notch performance for most components, you should also use something like the Application Initialization Module you mentioned.

ASP.NET MVC on IIS 7.5

You can solve this error by running cmd as admin than enter image description here

Do the same as in picture for windows 32 bit

Just make changes in 64 bit as framework64 instead of framework only Than go to iis and refresh the site
If u still got some error make changes in application pool

How to Find App Pool Recycles in Event Log

As link-only answers are not preferred, I will just copy and paste the content of the link of the accepted answer


It is definitely System Log.

Which Log file? Well -- you can check the physical path by right-clicking on the System Log (e.g. Server Manager | Diagnostics | Event Viewer | Windows Logs). The default physical path is %SystemRoot%\System32\Winevt\Logs\System.evtx.

You can create a Custom Filter and filter by "Source: WAS" to quickly see only entries generated by IIS.

You may need first to enable logging of such even for a specific App Pool -- by default App Pool has only 3 recycle events out of 8 enabled. To change it using GUI: II S Manager | Application Pools | Select App Pool -> Advanced Settings | Generate Recycle Event Log Entry.

ASP.NET 4.5 has not been registered on the Web server

I had the same problem. After a long search , I change the application pool to ASP.NET v4.x in the IIS manager.

How to enable ASP classic in IIS7.5

If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:

Add an 'Application Server' role:

  1. Click Start, point to Control Panel, click Programs, and then click Turn Windows features on or off.
  2. Right-click Server Manager, select Add Roles.
  3. On the Add Roles Wizard page, select Application Server, click Next three times, and then click Install. Windows Server installs the new role.

Then, add a 'Web Server' role:

  1. Web Server Role (IIS): in ServerManager, Roles, if the Web Server (IIS) role does not exist then add it.
  2. Under Web Server (IIS) role add role services for: ApplicationDevelopment:ASP, ApplicationDevelopment:ISAPI Exstensions, Security:Request Filtering.

More info: http://www.iis.net/learn/application-frameworks/running-classic-asp-applications-on-iis-7-and-iis-8/classic-asp-not-installed-by-default-on-iis

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

How to increase request timeout in IIS?

For AspNetCore, it looks like this:

<aspNetCore requestTimeout="00:20:00">

From here

How to give ASP.NET access to a private key in a certificate in the certificate store?

Note on granting permissions via MMC, Certs, Select Cert, right-click, all-tasks, "Manage Private Keys"

Manage Private Keys is only on the menu list for Personal... So if you've put your cert in Trusted People, etc. you're out of luck.

We found a way around this which worked for us. Drag and drop the cert to Personal, do the Manage Private Keys thing to grant permissions. Remember to set to use object-type built-ins and use the local machine not domain. We granted rights to the DefaultAppPool user and left it at that.

Once you're done, drag and drop the cert back where ever you originally had it. Presto.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

This issue can also happen due to the following

1.In the Web.Config

<system.webServer>
     <modules runAllManagedModulesForAllRequests="true" /> 
<system.webServer>

2.Make sure the following are available in the bin folder on the server where the Web API is deployed

  • System.Net.Http

  • System.Net.Http.Formatting

  • System.Web.Http.WebHost

  • System.Web.Http

These assemblies won't be copied in the bin folder by default if the publish is through Visual Studio because the Web API packages are installed through Nuget in the development machine. Still if you want to achieve these files to be available as part of Visual Studio publish then you need to set CopyLocal to True for these Assemblies

Sadish Kumar.V

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

Click on "Connect as" and select "specific user", then type in the credentials of your user (I used the admin of the server).

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

In my case, there was something wrong with the .NET Core Windows Hosting Bundle installation.

I had that installed and had restarted IIS using ("net stop was /y" and "net start w3svc") after installation, but I would get that 500.19 error with Error Code 0x8007000d and Config Source -1: 0:.

I managed to resolve the issue by repairing the .NET Core Windows Hosting Bundle installation and restarting IIS using the commands I mentioned above.

Hope this helps someone!

Android Relative Layout Align Center

You can use gravity with aligning top and bottom.

 android:gravity="center_vertical"
 android:layout_alignTop="@id/place_category_icon"
 android:layout_alignBottom="@id/place_category_icon"

Change / Add syntax highlighting for a language in Sublime 2/3

I finally found a way to customize the given Themes.

Go to C:\Program Files\Sublime Text 3\Packages and copy + rename Color Scheme - Default.sublime-package to Color Scheme - Default.zip. Afterwards unzip it and copy the Theme, you want to change to %APPDATA%\Sublime Text 3\Packages\User. (In my case, All Hallow's Eve.tmTheme).

Then you can open it with any Text Editor and change / add something, for example for changing this in JavaScript:

<dict>
    <key>name</key>
    <string>Lang Variable</string>
    <key>scope</key>
    <string>variable.language</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#FF0000</string>
    </dict>
</dict>

This will mark this in JavaScript Files red. You can select your Theme under Preferences -> Color Scheme -> User -> <Your Name>.

Failing to run jar file from command line: “no main manifest attribute”

You can select the "Runnable JAR File" after you click on "Export".

You can specify your main driver in "Launch Configuration"

enter image description here enter image description here

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

How to declare array of zeros in python (or an array of a certain size)

The simplest solution would be

"\x00" * size # for a buffer of binary zeros
[0] * size # for a list of integer zeros

In general you should use more pythonic code like list comprehension (in your example: [0 for unused in xrange(100)]) or using string.join for buffers.

Comparing strings in Java

In onclik function replace first line with this line u will definitely get right result.

if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){

validate a dropdownlist in asp.net mvc

For ListBox / DropDown in MVC5 - i've found this to work for me sofar:

in Model:

[Required(ErrorMessage = "- Select item -")]
 public List<string> SelectedItem { get; set; }
 public List<SelectListItem> AvailableItemsList { get; set; }

in View:

@Html.ListBoxFor(model => model.SelectedItem, Model.AvailableItemsList)
@Html.ValidationMessageFor(model => model.SelectedItem, "", new { @class = "text-danger" })

How to print without newline or space?

@lenooh satisfied my query. I discovered this article while searching for 'python suppress newline'. I'm using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn't want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn't cruncxed to a halt nor been sent to lunch on a merry infinite loop - as a plea to 'leave me be, I'm doing fine, but this may take some time.' interactive message - like a progress bar in text.

The print('Skimming for', search_string, '\b! .001', end='') initializes the message by preparing for the next screen-write, which will print three backspaces as ??? rubout and then a period, wiping off '001' and extending the line of periods. After search_string parrots user input, the \b! trims the exclamation point of my search_string text to back over the space which print() otherwise forces, properly placing the punctuation. That's followed by a space and the first 'dot' of the 'progress bar' which I'm simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])
#print footers here
 if not (len(list)==items):
    print('#error_handler')

The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03')) line. First, to erase to the left, it backs up the cursor over the three numeric characters with the '\b\b\b' as ??? rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write() waits for a full buffer or the output channel to close, the sys.stdout.flush() forces the immediate write. sys.stdout.flush() is built into the end of print() which is bypassed with print(txt, end='' ). Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.

The three digits wiped and rewritten is by no means necessary - it's just a flourish which exemplifies sys.stdout.write() versus print(). You could just as easily prime with a period and forget the three fancy backslash-b ? backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through - without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush() pair.

Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ? rubout but instead prints a space, creating an apparent list of fractions instead.

—(o=8> wiz

Query to get all rows from previous month

SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

How to change pivot table data source in Excel?

Looks like this depends heavily on your version of Excel. I am using the 2007 version and it offers no wizard option when you right click on the table. You need to click on the pivot table to make extra 'PivotTable Tools' appear to the right of the other tabs at the top of the screen. Click the 'options' tab that appears here then there is a big icon on the middle of the ribbon named 'change data source'.

Remove xticks in a matplotlib plot?

This snippet might help in removing the xticks only.

from matplotlib import pyplot as plt    
plt.xticks([])

This snippet might help in removing the xticks and yticks both.

from matplotlib import pyplot as plt    
plt.xticks([]),plt.yticks([])

Maximum call stack size exceeded error

I was facing same issue I have resolved it by removing a field name which was used twice on ajax e.g

    jQuery.ajax({
    url : '/search-result',
    data : {
      searchField : searchField,
      searchFieldValue : searchField,
      nid    :  nid,
      indexName : indexName,
      indexType : indexType
    },
.....

How to copy files between two nodes using ansible

To copy remote-to-remote files you can use the synchronize module with 'delegate_to: source-server' keyword:

- hosts: serverB
  tasks:    
   - name: Copy Remote-To-Remote (from serverA to serverB)
     synchronize: src=/copy/from_serverA dest=/copy/to_serverB
     delegate_to: serverA

This playbook can run from your machineC.

Free FTP Library

After lots of investigation in the same issue I found this one to be extremely convenient: https://github.com/flagbug/FlagFtp

For example (try doing this with the standard .net "library" - it will be a real pain) -> Recursively retreving all files on the FTP server:

  public IEnumerable<FtpFileInfo> GetFiles(string server, string user, string password)
    {
        var credentials = new NetworkCredential(user, password);
        var baseUri = new Uri("ftp://" + server + "/");

        var files = new List<FtpFileInfo>();
        AddFilesFromSubdirectory(files, baseUri, credentials);

        return files;
    }

    private void AddFilesFromSubdirectory(List<FtpFileInfo> files, Uri uri, NetworkCredential credentials)
    {
        var client = new FtpClient(credentials);
        var lookedUpFiles = client.GetFiles(uri);
        files.AddRange(lookedUpFiles);

        foreach (var subDirectory in client.GetDirectories(uri))
        {
            AddFilesFromSubdirectory(files, subDirectory.Uri, credentials);
        }
    }

Choice between vector::resize() and vector::reserve()

reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

Is there any better choice in this kind of scenario?

it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

iPhone app could not be installed at this time

Recently default Xcode project settings set ONLY_ACTIVE_ARCH (Build Active Architecture Only) to yes for Debug configuration.
So your build can not be installed on different hardware than the one you use for development.
Change this setting and installation should go fine.
enter image description here

Return list using select new in LINQ

public List<Object> GetProjectForCombo()
{
   using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
   {
     var query = db.Project
     .Select<IEnumerable<something>,ProjectInfo>(p=>
                 return new ProjectInfo{Name=p.ProjectName, Id=p.ProjectId);       

     return query.ToList<Object>();
   }

}

How can I insert data into Database Laravel?

The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:

Route::post('test/register', array('uses'=>'TestController@create'));

Also, you need to hash your passwords:

public function create()
{
    $user = new User;

    $user->username = Input::get('username');
    $user->email = Input::get('email');
    $user->password = Hash::make(Input::get('password'));
    $user->save();

    return Redirect::back();
}

And I removed the line:

$user= Input::all();

Because in the next command you replace its contents with

$user = new User;

To debug your Input, you can, in the first line of your controller:

dd( Input::all() );

It will display all fields in the input.

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

Self-explanatory code follows which first creates a std::tm corresponding to 10-10-2012 12:38:40, converts that to a std::chrono::system_clock::time_point, adds 0.123456 seconds, and then prints that out by converting back to a std::tm. How to handle the fractional seconds is in the very last step.

#include <iostream>
#include <chrono>
#include <ctime>

int main()
{
    // Create 10-10-2012 12:38:40 UTC as a std::tm
    std::tm tm = {0};
    tm.tm_sec = 40;
    tm.tm_min = 38;
    tm.tm_hour = 12;
    tm.tm_mday = 10;
    tm.tm_mon = 9;
    tm.tm_year = 112;
    tm.tm_isdst = -1;
    // Convert std::tm to std::time_t (popular extension)
    std::time_t tt = timegm(&tm);
    // Convert std::time_t to std::chrono::system_clock::time_point
    std::chrono::system_clock::time_point tp = 
                                     std::chrono::system_clock::from_time_t(tt);
    // Add 0.123456 seconds
    // This will not compile if std::chrono::system_clock::time_point has
    //   courser resolution than microseconds
    tp += std::chrono::microseconds(123456);
    
    // Now output tp

    // Convert std::chrono::system_clock::time_point to std::time_t
    tt = std::chrono::system_clock::to_time_t(tp);
    // Convert std::time_t to std::tm (popular extension)
    tm = std::tm{0};
    gmtime_r(&tt, &tm);
    // Output month
    std::cout << tm.tm_mon + 1 << '-';
    // Output day
    std::cout << tm.tm_mday << '-';
    // Output year
    std::cout << tm.tm_year+1900 << ' ';
    // Output hour
    if (tm.tm_hour <= 9)
        std::cout << '0';
    std::cout << tm.tm_hour << ':';
    // Output minute
    if (tm.tm_min <= 9)
        std::cout << '0';
    std::cout << tm.tm_min << ':';
    // Output seconds with fraction
    //   This is the heart of the question/answer.
    //   First create a double-based second
    std::chrono::duration<double> sec = tp - 
                                    std::chrono::system_clock::from_time_t(tt) +
                                    std::chrono::seconds(tm.tm_sec);
    //   Then print out that double using whatever format you prefer.
    if (sec.count() < 10)
        std::cout << '0';
    std::cout << std::fixed << sec.count() << '\n';
}

For me this outputs:

10-10-2012 12:38:40.123456

Your std::chrono::system_clock::time_point may or may not be precise enough to hold microseconds.

Update

An easier way is to just use this date library. The code simplifies down to (using C++14 duration literals):

#include "date.h"
#include <iostream>
#include <type_traits>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    static_assert(std::is_same<decltype(t),
                               time_point<system_clock, microseconds>>{}, "");
    std::cout << t << '\n';
}

which outputs:

2012-10-10 12:38:40.123456

You can skip the static_assert if you don't need to prove that the type of t is a std::chrono::time_point.

If the output isn't to your liking, for example you would really like dd-mm-yyyy ordering, you could:

#include "date.h"
#include <iomanip>
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    using namespace std;
    auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
    auto dp = floor<days>(t);
    auto time = make_time(t-dp);
    auto ymd = year_month_day{dp};
    cout.fill('0');
    cout << ymd.day() << '-' << setw(2) << static_cast<unsigned>(ymd.month())
         << '-' << ymd.year() << ' ' << time << '\n';
}

which gives exactly the requested output:

10-10-2012 12:38:40.123456

Update

Here is how to neatly format the current time UTC with milliseconds precision:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace std::chrono;
    std::cout << date::format("%F %T\n", time_point_cast<milliseconds>(system_clock::now()));
}

which just output for me:

2016-10-17 16:36:02.975

C++17 will allow you to replace time_point_cast<milliseconds> with floor<milliseconds>. Until then date::floor is available in "date.h".

std::cout << date::format("%F %T\n", date::floor<milliseconds>(system_clock::now()));

Update C++20

In C++20 this is now simply:

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    auto t = sys_days{10d/10/2012} + 12h + 38min + 40s + 123456us;
    std::cout << t << '\n';
}

Or just:

std::cout << std::chrono::system_clock::now() << '\n';

std::format will be available to customize the output.

How to disable button in React.js

this.input is undefined until the ref callback is called. Try setting this.input to some initial value in your constructor.

From the React docs on refs, emphasis mine:

the callback will be executed immediately after the component is mounted or unmounted

Android Layout Right Align

To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.

    <ImageButton
        android:id="@+id/btnGenesis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="left"
        android:src="@drawable/prev" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/lblVerseHeading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <Spinner
        android:id="@+id/spinnerVerses"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <ImageButton
        android:id="@+id/btnExodus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="right"
        android:src="@drawable/next" />
</LinearLayout>

CSS Font Border?

Stroke font-character with a Less mixin

Here's a LESS mixin to generate the stroke: http://codepen.io/anon/pen/BNYGBy?editors=110

/// Stroke font-character
/// @param  {Integer} $stroke - Stroke width
/// @param  {Color}   $color  - Stroke color
/// @return {List}            - text-shadow list
.stroke(@stroke, @color) {
  @maxi: @stroke + 1;
  .i-loop (@i) when (@i > 0) {
    @maxj: @stroke + 1;
    .j-loop (@j) when (@j > 0) {
      text-shadow+: (@i - 1)*(1px)  (@j - 1)*(1px) 0 @color;
      text-shadow+: (@i - 1)*(1px)  (@j - 1)*(-1px) 0 @color;
      text-shadow+: (@i - 1)*(-1px)  (@j - 1)*(-1px) 0 @color;
      text-shadow+: (@i - 1)*(-1px)  (@j - 1)*(1px) 0 @color;
      .j-loop(@j - 1);
    }
    .j-loop (0) {}
    .j-loop(@maxj);
    .i-loop(@i - 1);
  }
  .i-loop (0) {}
  .i-loop(@maxi);
  text-shadow+: 0 0 0 @color;
}

(it's based on pixelass answer that instead uses SCSS)

Connect Java to a MySQL database

Short and Sweet code.

try {       
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver Loaded");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
    //Database Name - testDB, Username - "root", Password - ""
    System.out.println("Connected...");         
} catch(Exception e) {
    e.printStackTrace();
}

For SQL server 2012

try {
    String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123"; 
    //KHILAN is Host    and 1433 is port number     
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    System.out.println("Driver Loaded");
    conn = DriverManager.getConnection(url);
    System.out.println("Connected...");
} catch(Exception e) {
    e.printStackTrace();
}

How to view file history in Git?

git log --all -- path/to/file should work

new Runnable() but no new thread?

Runnable is just an interface, which provides the method run. Threads are implementations and use Runnable to call the method run().

How can I get a list of all classes within current module in Python?

I was able to get all I needed from the dir built in plus getattr.

# Works on pretty much everything, but be mindful that 
# you get lists of strings back

print dir(myproject)
print dir(myproject.mymodule)
print dir(myproject.mymodule.myfile)
print dir(myproject.mymodule.myfile.myclass)

# But, the string names can be resolved with getattr, (as seen below)

Though, it does come out looking like a hairball:

def list_supported_platforms():
    """
        List supported platforms (to match sys.platform)

        @Retirms:
            list str: platform names
    """
    return list(itertools.chain(
        *list(
            # Get the class's constant
            getattr(
                # Get the module's first class, which we wrote
                getattr(
                    # Get the module
                    getattr(platforms, item),
                    dir(
                        getattr(platforms, item)
                    )[0]
                ),
                'SYS_PLATFORMS'
            )
            # For each include in platforms/__init__.py 
            for item in dir(platforms)
            # Ignore magic, ourselves (index.py) and a base class.
            if not item.startswith('__') and item not in ['index', 'base']
        )
    ))

Expected block end YAML error

This error also occurs if you use four-space instead of two-space indentation.

e.g., the following would throw the error:

fields:
    - metadata: {}
        name: colName
        nullable: true

whereas changing indentation to two-spaces would fix it:

fields:
  - metadata: {}
    name: colName
    nullable: true

Laravel Eloquent: Ordering results of all()

Note, you can do:

$results = Project::select('name')->orderBy('name')->get();

This generate a query like:

"SELECT name FROM proyect ORDER BY 'name' ASC"

In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:

$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();

Now is php who order the result.

Bootstrap push div content to new line

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

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

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

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

Spring JPA @Query with LIKE

Another way: instead CONCAT function we can use double pipe: :lastname || '%'

@Query("select c from Customer c where c.lastName LIKE :lastname||'%'")
List<Customer> findCustomByLastName( @Param("lastname") String lastName);

You can put anywhere, prefix, suffix or both

:lastname ||'%'  
'%' || :lastname  
'%' || :lastname || '%'  

Why can't Python find shared objects that are in directories in sys.path?

sys.path is only searched for Python modules. For dynamic linked libraries, the paths searched must be in LD_LIBRARY_PATH. Check if your LD_LIBRARY_PATH includes /usr/local/lib, and if it doesn't, add it and try again.

Some more information (source):

In Linux, the environment variable LD_LIBRARY_PATH is a colon-separated set of directories where libraries should be searched for first, before the standard set of directories; this is useful when debugging a new library or using a nonstandard library for special purposes. The environment variable LD_PRELOAD lists shared libraries with functions that override the standard set, just as /etc/ld.so.preload does. These are implemented by the loader /lib/ld-linux.so. I should note that, while LD_LIBRARY_PATH works on many Unix-like systems, it doesn't work on all; for example, this functionality is available on HP-UX but as the environment variable SHLIB_PATH, and on AIX this functionality is through the variable LIBPATH (with the same syntax, a colon-separated list).

Update: to set LD_LIBRARY_PATH, use one of the following, ideally in your ~/.bashrc or equivalent file:

export LD_LIBRARY_PATH=/usr/local/lib

or

export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

Use the first form if it's empty (equivalent to the empty string, or not present at all), and the second form if it isn't. Note the use of export.

What is the easiest way to encrypt a password when I save it to the registry?

This is what you would like to do:

OurKey.SetValue("Password", StringEncryptor.EncryptString(textBoxPassword.Text));
OurKey.GetValue("Password", StringEncryptor.DecryptString(textBoxPassword.Text));

You can do that with this the following classes. This class is a generic class is the client endpoint. It enables IOC of various encryption algorithms using Ninject.

public class StringEncryptor
{
    private static IKernel _kernel;

    static StringEncryptor()
    {
        _kernel = new StandardKernel(new EncryptionModule());
    }

    public static string EncryptString(string plainText)
    {
        return _kernel.Get<IStringEncryptor>().EncryptString(plainText);
    }

    public static string DecryptString(string encryptedText)
    {
        return _kernel.Get<IStringEncryptor>().DecryptString(encryptedText);
    }
}

This next class is the ninject class that allows you to inject the various algorithms:

public class EncryptionModule : StandardModule
{
    public override void Load()
    {
        Bind<IStringEncryptor>().To<TripleDESStringEncryptor>();
    }
}

This is the interface that any algorithm needs to implement to encrypt/decrypt strings:

public interface IStringEncryptor
{
    string EncryptString(string plainText);
    string DecryptString(string encryptedText);
}

This is a implementation using the TripleDES algorithm:

public class TripleDESStringEncryptor : IStringEncryptor
{
    private byte[] _key;
    private byte[] _iv;
    private TripleDESCryptoServiceProvider _provider;

    public TripleDESStringEncryptor()
    {
        _key = System.Text.ASCIIEncoding.ASCII.GetBytes("GSYAHAGCBDUUADIADKOPAAAW");
        _iv = System.Text.ASCIIEncoding.ASCII.GetBytes("USAZBGAW");
        _provider = new TripleDESCryptoServiceProvider();
    }

    #region IStringEncryptor Members

    public string EncryptString(string plainText)
    {
        return Transform(plainText, _provider.CreateEncryptor(_key, _iv));
    }

    public string DecryptString(string encryptedText)
    {
        return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));
    }

    #endregion

    private string Transform(string text, ICryptoTransform transform)
    {
        if (text == null)
        {
            return null;
        }
        using (MemoryStream stream = new MemoryStream())
        {
            using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
            {
                byte[] input = Encoding.Default.GetBytes(text);
                cryptoStream.Write(input, 0, input.Length);
                cryptoStream.FlushFinalBlock();

                return Encoding.Default.GetString(stream.ToArray());
            }
        }
    }
}

You can watch my video and download the code for this at : http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html

How to do a subquery in LINQ?

You could do something like this for your case - (syntax may be a bit off). Also look at this link

subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();

finalQuery = from u in Users where u.LastName.Contains('fra')  && subQuery.Contains(u.Id) select u;

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

How to style a div to be a responsive square?

Another way is to use a transparent 1x1.png with width: 100%, height: auto in a div and absolutely positioned content within it:

html:

<div>
    <img src="1x1px.png">
    <h1>FOO</h1>
</div>

css:

div {
    position: relative;
    width: 50%;
}

img {
    width: 100%;
    height: auto;
}

h1 {
    position: absolute;
    top: 10px;
    left: 10px;
}

Fidle: http://jsfiddle.net/t529bjwc/

Upload video files via PHP and save them in appropriate folder and have a database entry

HTML Code

<html>
<body>

<head>
<title></title>
</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file"><span>Filename:</span></label>
    <input type="file" name="file" id="file" /> 
    <br />
<input type="submit" name="submit" value="Submit" />
</form>



<?php

    //============================= DATABASE CONNECTIVITY d ====================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    //============================= DATABASE CONNECTIVITY u ====================
    //============================= Retrieve data from DB d ====================
    $sql = "SELECT name, size, type FROM videos";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) 
        {
        $path = "uploaded/" . $row["name"];

            echo $path . "<br>";

        }
    } else {
        echo "0 results";
    }
    $conn->close();
    //============================= Retrieve data from DB d ====================

?>


</body>
</html>

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You forgot the dot of class selector of result class.

Live Demo

$(".result").hover(
  function () {
    $(this).addClass("result_hover");
  },
  function () {
    $(this).removeClass("result_hover");
  }
);

You can use toggleClass on hover event

Live Demo

 $(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

RE error: illegal byte sequence on Mac OS X

A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc' fails, because byte 0xfc is not a valid UTF-8 char.
Note that, by contrast, GNU sed (Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.

Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)

However, the same effect can be had ad-hoc for a single command only:

LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure

Note: What matters is an effective LC_CTYPE setting of C, so LC_CTYPE=C sed ... would normally also work, but if LC_ALL happens to be set (to something other than C), it will override individual LC_*-category variables such as LC_CTYPE. Thus, the most robust approach is to set LC_ALL.

However, (effectively) setting LC_CTYPE to C treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.

In a nutshell: setting LC_CTYPE to C causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.

Again, this may be fine if you needn't match multibyte-encoded characters such as é, and simply want to pass such characters through.

If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.


The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed error message is trying to say by invalid byte sequence.

Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1, frequently used to encode "Western European" languages.

Example:

The accented letter à has Unicode codepoint 0xE0 (224) - the same as in ISO-8859-1. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0, whereas trying to pass the single byte 0xE0 is invalid under UTF-8.

Here's a demonstration of the problem using the string voilà encoded as ISO-8859-1, with the à represented as one byte (via an ANSI-C-quoted bash string ($'...') that uses \x{e0} to create the byte):

Note that the sed command is effectively a no-op that simply passes the input through, but we need it to provoke the error:

  # -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'

To simply ignore the problem, the above LCTYPE=C approach can be used:

  # No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'

If you want to determine which parts of the input cause the problem, try the following:

  # Convert bytes in the 8-bit range (high bit set) to hex. representation.
  # -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'

The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)


Performing encoding conversions on demand:

Standard utility iconv can be used to convert to (-t) and/or from (-f) encodings; iconv -l lists all supported ones.

Examples:

Convert FROM ISO-8859-1 to the encoding in effect in the shell (based on LC_CTYPE, which is UTF-8-based by default), building on the above example:

  # Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

Note that this conversion allows you to properly match foreign characters:

  # Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

To convert the input BACK to ISO-8859-1 after processing, simply pipe the result to another iconv command:

sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1

How do I empty an input value with jQuery?

A better way is:

$("#element").val(null);

Java IOException "Too many open files"

Although in most general cases the error is quite clearly that file handles have not been closed, I just encountered an instance with JDK7 on Linux that well... is sufficiently ****ed up to explain here.

The program opened a FileOutputStream (fos), a BufferedOutputStream (bos) and a DataOutputStream (dos). After writing to the dataoutputstream, the dos was closed and I thought everything went fine.

Internally however, the dos, tried to flush the bos, which returned a Disk Full error. That exception was eaten by the DataOutputStream, and as a consequence the underlying bos was not closed, hence the fos was still open.

At a later stage that file was then renamed from (something with a .tmp) to its real name. Thereby, the java file descriptor trackers lost track of the original .tmp, yet it was still open !

To solve this, I had to first flush the DataOutputStream myself, retrieve the IOException and close the FileOutputStream myself.

I hope this helps someone.

syntax error: unexpected token <

I had a similar problem, and my issue was that I was sending javascript to display console messages.

Even when I looked at the file in my browser (not through the application) it showed exactly as I expected it to (eg the extra tags weren't showing), but there were showing in the html/text output and were trying to be parsed.

Hope this helps someone!

How can I get the named parameters from a URL using Flask?

It's really simple. Let me divide this process into two simple steps.

  1. On the html template you will declare name attribute for username and password like this:
<form method="POST">
<input type="text" name="user_name"></input>
<input type="text" name="password"></input>
</form>
  1. Then, modify your code like this:
from flask import request

@app.route('/my-route', methods=['POST'])
# you should always parse username and 
# password in a POST method not GET
def my_route():
    username = request.form.get("user_name")
    print(username)
    password = request.form.get("password")
    print(password)
    #now manipulate the username and password variables as you wish
    #Tip: define another method instead of methods=['GET','POST'], if you want to  
    # render the same template with a GET request too

How can I change the Bootstrap default font family using font from Google?

I think the best and cleanest way would be to get a custom download of bootstrap.

http://getbootstrap.com/customize/

You can then change the font-defaults in the Typography (in that link). This then gives you a .Less file that you can make further changes to defaults with later.

How do I create a multiline Python string with inline variables?

NOTE: The recommended way to do string formatting in Python is to use format(), as outlined in the accepted answer. I'm preserving this answer as an example of the C-style syntax that's also supported.

# NOTE: format() is a better choice!
string1 = "go"
string2 = "now"
string3 = "great"

s = """
I will %s there
I will go %s
%s
""" % (string1, string2, string3)

print(s)

Some reading:

Refresh Fragment at reload

Use a ContentProvider and load you data using a 'CursorLoader'. With this architecture your data will be automatically reloaded on database changes. Use third-party frameworks for your ContentProvider - you don't really want to implement it by yourself...

Eclipse does not highlight matching variables

maybe because it not supports code highlights inside scriplets. not sure though.

You can try using one of the eclipse plugin like 'glance search' which works great. Here's a link for that- http://code.google.com/p/eclipse-glance/

setting min date in jquery datepicker

The problem is that the default option of "yearRange" is 10 years.

So 2012 - 10 = 2002.

So change the yearRange to c-20:c or just 1999 (yearRange: '1999:c'), and use that in combination with restrict dates (mindate, maxdate).

For more info: http://jqueryui.com/demos/datepicker/#option-yearRange


See example: http://jsfiddle.net/kGjdL/

And your code with the addition:

$(function () {
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1999, 10 - 1, 25),
        maxDate: '+30Y',
        yearRange: '1999:c',
        inline: true
    });
});

How can I go back/route-back on vue-router?

You can use Programmatic Navigation.In order to go back, you use this:

router.go(n) 

Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:

<a @click="$router.go(-1)">back</a>

What is the purpose of the word 'self'?

Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this (a-la Java/C++) or explicit @ (a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:

def fubar(x):
    self.x = x

class C:
    frob = fubar

Now the fubar function wouldn't work since it would assume that self is a global variable (and in frob as well). The alternative would be to execute method's with a replaced global scope (where self is the object).

The implicit approach would be

def fubar(x)
    myX = x

class C:
    frob = fubar

This would mean that myX would be interpreted as a local variable in fubar (and in frob as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.

However the current situation works out well:

 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar

here when called as a method frob will receive the object on which it's called via the self parameter, and fubar can still be called with an object as parameter and work the same (it is the same as C.frob I think).

How to fix nginx throws 400 bad request headers on any header testing tools?

When nginx returns 400(bad request) it will log the reason into error log, at "info" level and take a look into error log when testing.

Min and max value of input in angular4 application

Actually when you use type="number" your input control populate with up/down arrow to increment/decrement numeric value, so when you update textbox value with those button it will not pass limit of 100, but when you manually give input like 120/130 and so on, it will not validate for max limit, so you have to validate it by code.

You can disable manual input OR you have to write some code on valueChange/textChange/key* event.

How to normalize a vector in MATLAB efficiently? Any related built-in function?

The only problem you would run into is if the norm of V is zero (or very close to it). This could give you Inf or NaN when you divide, along with a divide-by-zero warning. If you don't care about getting an Inf or NaN, you can just turn the warning on and off using WARNING:

oldState = warning('off','MATLAB:divideByZero');  % Return previous state then
                                                  %   turn off DBZ warning
uV = V/norm(V);
warning(oldState);  % Restore previous state

If you don't want any Inf or NaN values, you have to check the size of the norm first:

normV = norm(V);
if normV > 0,  % Or some other threshold, like EPS
  uV = V/normV;
else,
  uV = V;  % Do nothing since it's basically 0
end

If I need it in a program, I usually put the above code in my own function, usually called unit (since it basically turns a vector into a unit vector pointing in the same direction).

Spring RestTemplate timeout

Here are my 2 cents. Nothing new, but some explanations, improvements and newer code.

By default, RestTemplate has infinite timeout. There are two kinds of timeouts: connection timeout and read time out. For instance, I could connect to the server but I could not read data. The application was hanging and you have no clue what's going on.

I am going to use annotations, which these days are preferred over XML.

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {

        var factory = new SimpleClientHttpRequestFactory();

        factory.setConnectTimeout(3000);
        factory.setReadTimeout(3000);

        return new RestTemplate(factory);
    }
}

Here we use SimpleClientHttpRequestFactory to set the connection and read time outs. It is then passed to the constructor of RestTemplate.

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {

        return builder
                .setConnectTimeout(Duration.ofMillis(3000))
                .setReadTimeout(Duration.ofMillis(3000))
                .build();
    }
}

In the second solution, we use the RestTemplateBuilder. Also notice the parameters of the two methods: they take Duration. The overloaded methods that take directly milliseconds are now deprecated.

Edit Tested with Spring Boot 2.1.0 and Java 11.

What does it mean "No Launcher activity found!"

It means you didn't specify an Activity for Android to launch as the default when the app opens from the launcher. You have to add an Intent Filter in the Manifest for the Activity you would like to act as the default when the app is being launched.

Read http://developer.android.com/guide/topics/intents/intents-filters.html#ccases for more details.

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

The tilde operator in Python

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

How can I find the number of arguments of a Python function?

inspect.getargspec() to meet your needs

from inspect import getargspec

def func(a, b):
    pass
print len(getargspec(func).args)

jquery: how to get the value of id attribute?

You can also try this way

<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>

jquery

$('.select_continent').click(function () {
alert($(this).data('value'));
});

Good luck !!!!

Predefined type 'System.ValueTuple´2´ is not defined or imported

For .NET 4.6.2 or lower, .NET Core 1.x, and .NET Standard 1.x you need to install the NuGet package System.ValueTuple:

Install-Package "System.ValueTuple"

Or using a package reference in VS 2017:

<PackageReference Include="System.ValueTuple" Version="4.4.0" />

.NET Framework 4.7, .NET Core 2.0, and .NET Standard 2.0 include these types.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

I'm Using Xampp and Laravel 5.8 in Windows 10, and i've been like this before. When i got this problem, My XAMPP is no have Password Then I tried to delete some codes in config>database.php

'password' => env('DB_PASSWORD', ''),

And in .env

DB_PASSWORD=SECRET

the Problem is solved

How to delete files older than X hours

find $PATH -name $log_prefix"*"$log_ext -mmin +$num_mins -exec rm -f {} \;

Convert list of dictionaries to a pandas DataFrame

Supposing d is your list of dicts, simply:

df = pd.DataFrame(d)

Note: this does not work with nested data.

Get list of passed arguments in Windows batch script (.bat)

Here is a fairly simple way to get the args and set them as env vars. In this example I will just refer to them as Keys and Values.

Save the following code example as "args.bat". Then call the batch file you saved from a command line. example: arg.bat --x 90 --y 120

I have provided some echo commands to step you through the process. But the end result is that --x will have a value of 90 and --y will have a value of 120(that is if you run the example as specified above ;-) ).

You can then use the 'if defined' conditional statement to determine whether or not to run your code block. So lets say run: "arg.bat --x hello-world" I could then use the statement "IF DEFINED --x echo %--x%" and the results would be "hello-world". It should make more sense if you run the batch.

@setlocal enableextensions enabledelayedexpansion
@ECHO off
ECHO.
ECHO :::::::::::::::::::::::::: arg.bat example :::::::::::::::::::::::::::::::
ECHO :: By:      User2631477, 2013-07-29                                   ::
ECHO :: Version: 1.0                                                         ::
ECHO :: Purpose: Checks the args passed to the batch.                        ::
ECHO ::                                                                      ::
ECHO :: Start by gathering all the args with the %%* in a for loop.          ::
ECHO ::                                                                      ::
ECHO :: Now we use a 'for' loop to search for our keys which are identified  ::
ECHO :: by the text '--'. The function then sets the --arg ^= to the next    ::
ECHO :: arg. "CALL:Function_GetValue" ^<search for --^> ^<each arg^>         ::
ECHO ::                                                                      ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

ECHO.

ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO :: From the command line you could pass... arg.bat --x 90 --y 220       ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
ECHO.Checking Args:"%*"

FOR %%a IN (%*) do (
    CALL:Function_GetValue "--","%%a" 
)

ECHO.
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO :: Now lets check which args were set to variables...                   ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO :: For this we are using the CALL:Function_Show_Defined "--x,--y,--z"   ::
ECHO ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
CALL:Function_Show_Defined "--x,--y,--z"
endlocal
goto done

:Function_GetValue

REM First we use find string to locate and search for the text.
echo.%~2 | findstr /C:"%~1" 1>nul

REM Next we check the errorlevel return to see if it contains a key or a value
REM and set the appropriate action.

if not errorlevel 1 (
  SET KEY=%~2
) ELSE (
  SET VALUE=%~2
)
IF DEFINED VALUE (
    SET %KEY%=%~2
    ECHO.
    ECHO ::::::::::::::::::::::::: %~0 ::::::::::::::::::::::::::::::
    ECHO :: The KEY:'%KEY%' is now set to the VALUE:'%VALUE%'                     ::
    ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ECHO.
    ECHO %KEY%=%~2
    ECHO.
    REM It's important to clear the definitions for the key and value in order to
    REM search for the next key value set.
    SET KEY=
    SET VALUE=
)
GOTO:EOF

:Function_Show_Defined 
ECHO.
ECHO ::::::::::::::::::: %~0 ::::::::::::::::::::::::::::::::
ECHO :: Checks which args were defined i.e. %~2
ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
ECHO.
SET ARGS=%~1
for %%s in (%ARGS%) DO (
    ECHO.
    ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ECHO :: For the ARG: '%%s'                         
    IF DEFINED %%s (
        ECHO :: Defined as: '%%s=!%%s!'                                             
    ) else (
        ECHO :: Not Defined '%%s' and thus has no value.
    )
    ECHO :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ECHO.
)
goto:EOF

:done

How can I check if a var is a string in JavaScript?

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

See: http://jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

What strategies and tools are useful for finding memory leaks in .NET?

After one of my fixes for managed application I had the same thing, like how to verify that my application will not have the same memory leak after my next change, so I've wrote something like Object Release Verification framework, please take a look on the NuGet package ObjectReleaseVerification. You can find a sample here https://github.com/outcoldman/OutcoldSolutions-ObjectReleaseVerification-Sample, and information about this sample http://outcoldman.ru/en/blog/show/322

Fuzzy matching using T-SQL

do it this way

         create table person(
         personid int identity(1,1) primary key,
         firstname varchar(20),
         lastname varchar(20),
         addressindex int,
         sound varchar(10)
         )

and later on create a trigger

         create trigger trigoninsert for dbo.person
         on insert 
         as
         declare @personid int;
         select @personid=personid from inserted;
         update person
         set sound=soundex(firstname) where personid=@personid;

now what i can do is i can create a procedure which looks something like this

         create procedure getfuzzi(@personid int)
          as
         declare @sound varchar(10);
         set @sound=(select sound from person where personid=@personid;
         select personid,firstname,lastname,addressindex from person
         where sound=@sound

this will return you all the names that are nearly in match with the names provided by for a particular personid

Shell command to sum integers, one per line?

Plain bash one liner

$ cat > /tmp/test
1 
2 
3 
4 
5
^D

$ echo $(( $(cat /tmp/test | tr "\n" "+" ) 0 ))

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

WPF loading spinner

In WPF, you can now simply do:

Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; // set the cursor to loading spinner

Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow; // set the cursor back to arrow

Change drawable color programmatically

Another way to do this on Lollipop, android 5.+ is setting a tint on a bitmap drawable like such:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_back"
    android:tint="@color/red_tint"/>

This will work for you if you have a limited number of colors you want to use on your drawables. Check out my blog post for more information.

HTML input textbox with a width of 100% overflows table cells

Take out the "http://www.w3.org/TR/html4/loose.dtd" from the DOCTYPE declaration and it fix your problem.

Cheers! :)

Why are you not able to declare a class as static in Java?

As explained above, a Class cannot be static unless it's a member of another Class.

If you're looking to design a class "of which there cannot be multiple instances", you may want to look into the "Singleton" design pattern.

Beginner Singleton info here.

Caveat:

If you are thinking of using the singleton pattern, resist with all your might. It is one of the easiest DesignPatterns to understand, probably the most popular, and definitely the most abused. (source: JavaRanch as linked above)

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

Cannot find module '@angular/compiler'

Try this

  1. npm uninstall angular-cli
  2. npm install @angular/cli --save-dev

How to Display Multiple Google Maps per page with API V3

Here is how I have been able to generate multiple maps on the same page using Google Map API V3. Kindly note that this is an off the cuff code that addresses the issue above.

The HTML bit

<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>

Javascript for map initialization

<script type="text/javascript">
var map, map2;

function initialize(condition) {
    // create the maps
    var myOptions = {
        zoom: 14,
        center: new google.maps.LatLng(0.0, 0.0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script> 

How to print multiple lines of text with Python

I wanted to answer to the following question which is a little bit different than this:

Best way to print messages on multiple lines

He wanted to show lines from repeated characters too. He wanted this output:

----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000

----------------------------------------

You can create those lines inside f-strings with a multiplication, like this:

run_mode, num_repeats, num_runs = 'short', 5, 1000

s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}

{'-'*40}
"""

print(s)

Unit testing private methods in C#

Another option that has not been mentioned is just creating the unit test class as a child of the object that you are testing. NUnit Example:

[TestFixture]
public class UnitTests : ObjectWithPrivateMethods
{
    [Test]
    public void TestSomeProtectedMethod()
    {
        Assert.IsTrue(this.SomeProtectedMethod() == true, "Failed test, result false");
    }
}

This would allow easy testing of private and protected (but not inherited private) methods, and it would allow you to keep all your tests separate from the real code so you aren't deploying test assemblies to production. Switching your private methods to protected methods would be acceptable in a lot of inherited objects, and it is a pretty simple change to make.

HOWEVER...

While this is an interesting approach to solving the problem of how to test hidden methods, I am unsure that I would advocate that this is the correct solution to the problem in all cases. It seems a little odd to be internally testing an object, and I suspect there might be some scenarios that this approach will blow up on you. (Immutable objects for example, might make some tests really hard).

While I mention this approach, I would suggest that this is more of a brainstormed suggestion than a legitimate solution. Take it with a grain of salt.

EDIT: I find it truly hilarious that people are voting this answer down, since I explicitly describe this as a bad idea. Does that mean that people are agreeing with me? I am so confused.....

What is the difference between ports 465 and 587?

SMTP protocol: smtps (port 465) v. msa (port 587)

Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.

Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.

Port 587 is for msa
It is almost like standard SMTP port. MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).


Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.

Using :focus to style outer div?

You can tab between div tags. Just add a tab index to the div. It's best to use jQuery and CSS classes to solve this problem. Here's a working sample tested in IE, Firefox, and Chrome (Latest versions... didn't test older).

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            var divParentIdFocus;
            var divParentIdUnfocus = null;

            $(document).ready(function() {              

                    $("div").focus(function() {
                        //$(this).attr("class", "highlight");
                        var curDivId = $(this).attr("id");

                        // This Check needs to be performed when/if div regains focus
                        // from child element.
                        if (divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }

                        divParentIdFocus = curDivId;
                    });


                    $("textarea").focus(function(){
                        var curDivId = $(this).closest("div").attr("id");

                        if(divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }
                    });

                    $("#div1").focus();
            });

            function refreshHighlight()
            {
                if(divParentIdUnfocus != null){
                    $("#" +divParentIdUnfocus).attr("class", "noHighlight");
                    divParentIdUnfocus = null;
                }

                $("#" + divParentIdFocus).attr("class", "highlight");
            }
        </script>
        <style type="text/css">
            .highlight{
                background-color:blue;
                border: 3px solid black;
                font-weight:bold;
                color: white;
            }
            .noHighlight{           
            }
            div, h1,textarea, select { outline: none; }

        </style>
    <head>
    <body>
        <div id = "div1" tabindex="100">
            <h1>Div 1</h1> <br />
            <textarea rows="2" cols="25" tabindex="101">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="102">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="103">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="104">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div2" tabindex="200">
            <h1>Div 2</h1> <br />
            <textarea rows="2" cols="25" tabindex="201">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="202">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="203">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="204">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div3" tabindex="300">
            <h1>Div 3</h1> <br />
            <textarea rows="2" cols="25" tabindex="301">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="302">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="303">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="304">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div4" tabindex="400">
            <h1>Div 4</h1> <br />
            <textarea rows="2" cols="25" tabindex="401">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="402">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="403">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="404">~Your Text Here~</textarea> <br />
        </div>      
    </body>
</html>

efficient way to implement paging

The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.

-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees

DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;

 DECLARE @PageDetails TABLE
       (
        <<IdentityColumn of Table>> int,
        rownum int,
        [PageNumber] int
       )           
       INSERT INTO @PageDetails values(0, 0, 0)
       ;WITH CTE AS
       (
       SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
       )
       Insert into @PageDetails 
       SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0


--SELECT * FROM @PageDetails 

-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM 
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>

VB.NET Empty String Array

Something like:

Dim myArray(9) as String

Would give you an array of 10 String references (each pointing to Nothing).

If you're not sure of the size at declaration time, you can declare a String array like this:

Dim myArray() as String

And then you can point it at a properly-sized array of Strings later:

ReDim myArray(9) as String

ZombieSheep is right about using a List if you don't know the total size and you need to dynamically populate it. In VB.NET that would be:

Dim myList as New List(Of String)
myList.Add("foo")
myList.Add("bar")

And then to get an array from that List:

myList.ToArray()

@Mark

Thanks for the correction.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

Facebook share button and custom text

you could combine AllisonC's idea with window.open function: http://www.w3schools.com/jsref/met_win_open.asp

function openWin(url) {
    myWindow = window.open(url, '', 'width=800,height=400');
    myWindow.focus();
}

And then on each link you call the openWin function with the right social net url.

What are the differences between git remote prune, git prune, git fetch --prune, etc

I don't blame you for getting frustrated about this. The best way to look at is this. There are potentially three versions of every remote branch:

  1. The actual branch on the remote repository
    (e.g., remote repo at https://example.com/repo.git, refs/heads/master)
  2. Your snapshot of that branch locally (stored under refs/remotes/...)
    (e.g., local repo, refs/remotes/origin/master)
  3. And a local branch that might be tracking the remote branch
    (e.g., local repo, refs/heads/master)

Let's start with git prune. This removes objects that are no longer being referenced, it does not remove references. In your case, you have a local branch. That means there's a ref named random_branch_I_want_deleted that refers to some objects that represent the history of that branch. So, by definition, git prune will not remove random_branch_I_want_deleted. Really, git prune is a way to delete data that has accumulated in Git but is not being referenced by anything. In general, it doesn't affect your view of any branches.

git remote prune origin and git fetch --prune both operate on references under refs/remotes/... (I'll refer to these as remote references). It doesn't affect local branches. The git remote version is useful if you only want to remove remote references under a particular remote. Otherwise, the two do exactly the same thing. So, in short, git remote prune and git fetch --prune operate on number 2 above. For example, if you deleted a branch using the git web GUI and don't want it to show up in your local branch list anymore (git branch -r), then this is the command you should use.

To remove a local branch, you should use git branch -d (or -D if it's not merged anywhere). FWIW, there is no git command to automatically remove the local tracking branches if a remote branch disappears.

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

How to find the Target *.exe file of *.appref-ms

The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address

LINQ to SQL - How to select specific columns and return strongly typed list

Make a call to the DB searching with myid (Id of the row) and get back specific columns:

var columns = db.Notifications
                .Where(x => x.Id == myid)
                .Select(n => new { n.NotificationTitle, 
                                   n.NotificationDescription, 
                                   n.NotificationOrder });

How to delete the first row of a dataframe in R?

While I agree with the most voted answer, here is another way to keep all rows except the first:

dat <- tail(dat, -1)

This can also be accomplished using Hadley Wickham's dplyr package.

dat <- dat %>% slice(-1)

How to find all the subclasses of a class given its name?

How can I find all subclasses of a class given its name?

We can certainly easily do this given access to the object itself, yes.

Simply given its name is a poor idea, as there can be multiple classes of the same name, even defined in the same module.

I created an implementation for another answer, and since it answers this question and it's a little more elegant than the other solutions here, here it is:

def get_subclasses(cls):
    """returns all subclasses of argument, cls"""
    if issubclass(cls, type):
        subclasses = cls.__subclasses__(cls)
    else:
        subclasses = cls.__subclasses__()
    for subclass in subclasses:
        subclasses.extend(get_subclasses(subclass))
    return subclasses

Usage:

>>> import pprint
>>> list_of_classes = get_subclasses(int)
>>> pprint.pprint(list_of_classes)
[<class 'bool'>,
 <enum 'IntEnum'>,
 <enum 'IntFlag'>,
 <class 'sre_constants._NamedIntConstant'>,
 <class 'subprocess.Handle'>,
 <enum '_ParameterKind'>,
 <enum 'Signals'>,
 <enum 'Handlers'>,
 <enum 'RegexFlag'>]

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

As already stated, the issue is caused by the export ordering within the barrel which is caused by circular dependencies.

A more detailed explanation is here: https://stackoverflow.com/a/37907696/893630

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try http://mystrd.at/modern-clean-css-sticky-footer/

The link above is down, but this link https://stackoverflow.com/a/18066619/1944643 is ok. :D

Demo:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="author" content="http://mystrd.at">
    <meta name="robots" content="noindex, nofollow">
    <title>James Dean CSS Sticky Footer</title>
    <style type="text/css">
        html {
            position: relative;
            min-height: 100%;
        }
        body {
            margin: 0 0 100px;
            /* bottom = footer height */
            padding: 25px;
        }
        footer {
            background-color: orange;
            position: absolute;
            left: 0;
            bottom: 0;
            height: 100px;
            width: 100%;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <article>
        <!-- or <div class="container">, etc. -->
        <h1>James Dean CSS Sticky Footer</h1>

        <p>Blah blah blah blah</p>
        <p>More blah blah blah</p>
    </article>
    <footer>
        <h1>Footer Content</h1>
    </footer>
</body>

</html>

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

-- replace NVARCHAR(42) with the actual type of your column
ALTER TABLE your_table
ALTER COLUMN your_column NVARCHAR(42) NULL

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

Java generics - get class?

I like the solution from

http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/

public class Dada<T> {

    private Class<T> typeOfT;

    @SuppressWarnings("unchecked")
    public Dada() {
        this.typeOfT = (Class<T>)
                ((ParameterizedType)getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
...

How to use template module with different set of variables?

I did it in this way.

In tasks/main.yml

- name: template test
  template: 
        src=myTemplateFile.j2
        dest={{item}}
   with_dict: some_dict

and in vars/main.yml

some_dict:
  /path/to/dest1:
    var1: 1
    var2: 2
  /path/to/dest2:
    var1: 3
    var2: 4

and in templates/myTemplateFile.j2

some_var = {{ item.value.var1 }}
some_other_var = {{ item.value.var2 }}

Hope this solves your problem.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Bind variable can be used in Oracle SQL query with "in" clause.

Works in 10g; I don't know about other versions.

Bind variable is varchar up to 4000 characters.

Example: Bind variable containing comma-separated list of values, e.g.

:bindvar = 1,2,3,4,5

select * from mytable
  where myfield in
    (
      SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
      FROM dual
      CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
    );

(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )

How to combine class and ID in CSS selector?

Ids are supposed to be unique document wide, so you shouldn't have to select based on both. You can assign an element multiple classes though with class="class1 class2"

How to switch to the new browser window, which opens after click on the button?

 main you can do :

 String mainTab = page.goToNewTab ();
 //do what you want
 page.backToMainPage(mainTab);  

 What you need to have in order to use the main   

        private static Set<String> windows;

            //get all open windows 
            //return current window
            public String initWindows() {
                windows = new HashSet<String>();
                driver.getWindowHandles().stream().forEach(n ->   windows.add(n));
                return driver.getWindowHandle();
            }

            public String getNewWindow() {
                List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
                        .collect(Collectors.toList());
                logger.info(newWindow.get(0));
                return newWindow.get(0);
            }


            public String goToNewTab() {
                String startWindow = driver.initWindows();
                driver.findElement(By.cssSelector("XX")).click();
                String newWindow = driver.getNewWindow();
                driver.switchTo().window(newWindow);
                return startWindow;
            }

            public void backToMainPage(String startWindow) {
                driver.close();
                driver.switchTo().window(startWindow);
            }

What exactly does Perl's "bless" do?

Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).

How to change int into int64?

This is probably obvious, but simplest:

i64 := int64(23)

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to prevent robots from automatically filling up a form?

  1. I use a method where there is a hidden textbox. Since bots parse the website they probably fill it. Then I check it if it is empty if it is not website returns back.

  2. Add email verification. The user receives an email and he needs to click a link. Otherwise discard the post in some time.

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

repaint() in Java

You're doing things in the wrong order.

You need to first add all JComponents to the JFrame, and only then call pack() and then setVisible(true) on the JFrame

If you later added JComponents that could change the GUI's size you will need to call pack() again, and then repaint() on the JFrame after doing so.

Get names of all files from a folder with Ruby

You also have the shortcut option of

Dir["/path/to/search/*"]

and if you want to find all Ruby files in any folder or sub-folder:

Dir["/path/to/search/**/*.rb"]

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject method that just makes a plain object. You can then use reflection to get at the properties you need.

If your controller takes a FormCollection, and you didn't add anything else to the data the json should be in form[0]:

public ActionResult Save(FormCollection forms) {
  string json = forms[0];
  // do your thing here.
}

Repeat string to certain length

This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rpt string increases.

def repeat(rpt, length):
    return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]

How to VueJS router-link active style

Just add to @Bert's solution to make it more clear:

    const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkExactActiveClass: "active" // active class for *exact* links.
})

As one can see, this line should be removed:

linkActiveClass: "active", // active class for non-exact links.

this way, ONLY the current link is hi-lighted. This should apply to most of the cases.

David

Javascript/DOM: How to remove all events of a DOM object?

As corwin.amber says, there are differences between Webkit an others.

In Chrome:

getEventListeners(document);

Which gives you an Object with all the existing event listeners:

Object 
 click: Array[1]
 closePopups: Array[1]
 keyup: Array[1]
 mouseout: Array[1]
 mouseover: Array[1]
 ...

From here you can reach the listener you want to remove:

getEventListeners(document).copy[0].remove();

So All the event listeners:

for(var eventType in getEventListeners(document)) {
   getEventListeners(document)[eventType].forEach(
      function(o) { o.remove(); }
   ) 
}

In Firefox

Is a little bit different because it uses a listener wrapper that contains no remove function. You have to get the listener you want to remove:

document.removeEventListener("copy", getEventListeners(document).copy[0].listener)

All the event listeners:

for(var eventType in getEventListeners(document)) {
  getEventListeners(document)[eventType].forEach(
    function(o) { document.removeEventListener(eventType, o.listener) }
  ) 
}

I stumbled with this post trying to disable the annoying copy protection of a news website.

Enjoy!

Create an application setup in visual studio 2013

Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.

visual-studio-installer-projects-extension

Exploitable PHP functions

Let's add pcntl_signal and pcntl_alarm to the list.

With the help of those functions you can work around any set_time_limit restriction created int the php.ini or in the script.

This script for example will run for 10 seconds despite of set_time_limit(1);

(Credit goes to Sebastian Bergmanns tweet and gist:

<?php
declare(ticks = 1);

set_time_limit(1);

function foo() {
    for (;;) {}
}

class Invoker_TimeoutException extends RuntimeException {}

class Invoker
{
    public function invoke($callable, $timeout)
    {
        pcntl_signal(SIGALRM, function() { throw new Invoker_TimeoutException; }, TRUE);
        pcntl_alarm($timeout);
        call_user_func($callable);
    }
}

try {
    $invoker = new Invoker;
    $invoker->invoke('foo', 1);
} catch (Exception $e) {
    sleep(10);
    echo "Still running despite of the timelimit";
}

How to set radio button selected value using jquery

This is the only syntax that worked for me

$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');

How does ApplicationContextAware work in Spring?

When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware and InitializingBean. If they are found, the methods are invoked. E.g. (very simplified)

Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
    ((ApplicationContextAware) bean).setApplicationContext(ctx);
}

Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:

@Inject // or @Autowired
private ApplicationContext ctx;

accessing a variable from another class

Java inbuilt libraries support only AIFC, AIFF, AU, SND and WAVE formats. Here I only discussed playing an audio file using Clip only and see the various methods of a clip.

  1. Create a main class PlayAudio.java.
  2. Create helper class Audio.java.

PlayAudio.java

import java.io.IOException;
import java.util.Scanner;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class PlayAudio {
public static void main(String[] args) throws 
UnsupportedAudioFileException, IOException, 
LineUnavailableException {

    PlayMp3 playMp3;
    playMp3=new PlayMp3();


    Scanner sc = new Scanner(System.in);

    while (true) {
        System.out.println("Enter Choice :-");
        System.out.println("1. Play");
        System.out.println("2. pause");
        System.out.println("3. resume");
        System.out.println("4. restart");
        System.out.println("5. stop");

        System.out.println(PlayMp3.status);
        System.out.println(":::- ");
        int c = sc.nextInt();

        if (c ==5){

            playMp3.stop();
            break;
        }

        switch (c) {
            case 1:
                playMp3.play();
                break;
            case 2:
                playMp3.pause();
                break;
            case 3:
                playMp3.resume();
                break;
            case 4:
                playMp3.restart();
                break;
            case 5:
                playMp3.stop();
            default:
                System.out.println("Please Enter Valid Option :-");

        }
    }
    sc.close();
   }
}

Audio.java

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class Audio {

private String filePath="mp.snd";
public static String status="paused";
private Long currentFrame=0L;
private Clip clip;

private AudioInputStream audioInputStream;

public Audio() throws UnsupportedAudioFileException, IOException, LineUnavailableException {

    audioInputStream = AudioSystem.getAudioInputStream(new File(filePath));

    clip = AudioSystem.getClip();

    clip.open(audioInputStream);

}


public void play(){
    clip.start();
    status = "playing";
}

public void pause(){

    if (status.equals("paused")) {
        System.out.println("audio is already paused");
        return;
    }
    currentFrame = clip.getMicrosecondPosition();
    clip.stop();
    status = "paused";
}
public void resume() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    if (status.equals("play"))
    {
        System.out.println("Audio is already being playing");
        return;
    }
    clip.close();

    //starts again and goes to currentFrame
    resetAudioStream();
    clip.setMicrosecondPosition(currentFrame);
    play();
    status="playing";

}

public void restart() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    clip.stop();
    clip.close();
    resetAudioStream();
    currentFrame = 0L;
    clip.setMicrosecondPosition(0);
    play();
    status="Playing from start";
}

public void stop(){

    currentFrame = 0L;
    clip.stop();
    clip.close();
    status="stopped";
}

private void resetAudioStream() throws IOException, UnsupportedAudioFileException, LineUnavailableException {

    audioInputStream = AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
    clip.open(audioInputStream);

   }

}

How to terminate script execution when debugging in Google Chrome?

If you are encountering this while using the debugger statement,

debugger;

... then I think the page will continue running forever until the js runtime yields, or the next break. Assuming you're in break-on-error mode (the pause-icon toggle), you can ensure a break happens by instead doing something like:

debugger;throw 1;

or maybe call a non-existent function:

debugger;z();

(Of course this doesn't help if you are trying to step through functions, though perhaps you could dynamically add in a throw 1 or z() or somesuch in the Sources panel, ctrl-S to save, and then ctrl-R to refresh... this may however skip one breakpoint, but may work if you're in a loop.)

If you are doing a loop and expect to trigger the debugger statement again, you could just type throw 1 instead.

throw 1;

Then when you hit ctrl-R, the next throw will be hit, and the page will refresh.

(tested with Chrome v38, circa Apr 2017)

How to vertically align text inside a flexbox?

You could change the ul and li displays to table and table-cell. Then, vertical-align would work for you:

ul {
    height: 20%;
    width: 100%;
    display: table;
}

li {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    background: silver;
    width: 100%; 
}

http://codepen.io/anon/pen/pckvK

Pick images of root folder from sub-folder

../ takes you one folder up the directory tree. Then, select the appropriate folder and its contents.

../images/logo.png

How to set session timeout dynamically in Java web applications?

As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.

getRequest().getSession().setMaxInactiveInterval(123);

Rollback to last git commit

git reset --hard will force the working directory back to the last commit and delete new/changed files.

How to print the data in byte array as characters?

If you want to print the bytes as chars you can use the String constructor.

byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

Subversion ignoring "--password" and "--username" options

The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.

IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?

If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password.

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

What is a good naming convention for vars, methods, etc in C++?

There are probably as many naming conventions as there are individuals, the debate being as endless (and sterile) as to which brace style to use and so forth.

So I'll have 2 advices:

  • be consistent within a project
  • don't use reserved identifiers (anything with two underscores or beginning with an underscore followed by an uppercase letter)

The rest is up to you.

Image overlay on responsive sized images bootstrap

I had a bit of trouble getting this to work as well. Using brouxhaha's answer got me 90% of the way to what I was looking for. But the padding adjust wouldn't allow me to put the text anywhere I wanted. Using top and left seemed to work better for my purposes.

.project-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    color: #fff;
    top: 80%;
    left: 20%;
}

http://jsfiddle.net/1rz0b7d8/1/

How to strip HTML tags from string in JavaScript?

I know this question has an accepted answer, but I feel that it doesn't work in all cases.

For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):

http://phpjs.org/functions/strip_tags:535

It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script /> tag above.

How to tell if string starts with a number with Python?

Your code won't work; you need or instead of ||.

Try

'0' <= strg[:1] <= '9'

or

strg[:1] in '0123456789'

or, if you are really crazy about startswith,

strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))

How to debug a referenced dll (having pdb)

The following solution worked for me. It involves copy pasting the .dll and .pdb files properly from project A to B: https://stackoverflow.com/a/16546777/5351410

What size should apple-touch-icon.png be for iPad and iPhone?

The icon on Apple's site is 152x152 pixels.
http://www.apple.com/apple-touch-icon.png

Hope that answers your question.

How to avoid Number Format Exception in java?

public class Main {
    public static void main(String[] args) {

        String number;

        while(true){

            try{
                number = JOptionPane.showInputDialog(null);

                if( Main.isNumber(number) )
                    break;

            }catch(NumberFormatException e){
                System.out.println(e.getMessage());
            }

        }

        System.out.println("Your number is " + number);

    }

    public static boolean isNumber(Object o){
        boolean isNumber = true;

        for( byte b : o.toString().getBytes() ){
            char c = (char)b;
            if(!Character.isDigit(c))
                isNumber = false;
        }

        return isNumber;
    }

}

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

Perform a Shapiro-Wilk Normality Test

What does shapiro.test do?

shapiro.test tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".

How to perform shapiro.test in R?

The R help page for ?shapiro.test gives,

x - a numeric vector of data values. Missing values are allowed, 
    but the number of non-missing values must be between 3 and 5000.

That is, shapiro.test expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:

> shapiro.test(heisenberg$HWWIchg)
#   Shapiro-Wilk normality test

# data:  heisenberg$HWWIchg 
# W = 0.9001, p-value = 0.2528

Interpreting results from shapiro.test:

First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality.

As shown above, the shapiro.test tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.

In case of the null hypothesis of shapiro.test, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:

set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
#   Shapiro-Wilk normality test
# data:  runif(50, min = 2, max = 4) 
# W = 0.9601, p-value = 0.08995

So, this (particular) sample runif(50, min=2, max=4) comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.

Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:

An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.

Although he also points out that R's data size limit protects this a bit:

Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.

If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!

@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:

In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.

Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:

For linear regression,

  1. Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.

  2. Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.

  3. Outliers. A cooks distance of > 1 is reasonable cause for concern.

Those are my thoughts (FWIW).

Hope this clears things up a bit.

multiple prints on the same line in Python

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],

Clear icon inside input text

You could use a reset button styled with an image...

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>

See it in action here: http://jsbin.com/uloli3/63

How to check if one DateTime is greater than the other in C#

if (StartDate>=EndDate)
{
    throw new InvalidOperationException("Ack!  StartDate is not before EndDate!");
}

Can a class member function template be virtual?

In the other answers the proposed template function is a facade and doesn't offer any practical benefit.

  • Template functions are useful for writing code only once using different types.
  • Virtual functions are useful for having a common interface for different classes.

The language doesn't allow virtual template functions but with a workaround it is possible to have both, e.g. one template implementation for each class and a virtual common interface.

It is however necessary to define for each template type combination a dummy virtual wrapper function:

#include <memory>
#include <iostream>
#include <iomanip>

//---------------------------------------------
// Abstract class with virtual functions
class Geometry {
public:
    virtual void getArea(float &area) = 0;
    virtual void getArea(long double &area) = 0;
};

//---------------------------------------------
// Square
class Square : public Geometry {
public:
    float size {1};

    // virtual wrapper functions call template function for square
    virtual void getArea(float &area) { getAreaT(area); }
    virtual void getArea(long double &area) { getAreaT(area); }

private:
    // Template function for squares
    template <typename T>
    void getAreaT(T &area) {
        area = static_cast<T>(size * size);
    }
};

//---------------------------------------------
// Circle
class Circle : public Geometry  {
public:
    float radius {1};

    // virtual wrapper functions call template function for circle
    virtual void getArea(float &area) { getAreaT(area); }
    virtual void getArea(long double &area) { getAreaT(area); }

private:
    // Template function for Circles
    template <typename T>
    void getAreaT(T &area) {
        area = static_cast<T>(radius * radius * 3.1415926535897932385L);
    }
};


//---------------------------------------------
// Main
int main()
{
    // get area of square using template based function T=float
    std::unique_ptr<Geometry> geometry = std::make_unique<Square>();
    float areaSquare;
    geometry->getArea(areaSquare);

    // get area of circle using template based function T=long double
    geometry = std::make_unique<Circle>();
    long double areaCircle;
    geometry->getArea(areaCircle);

    std::cout << std::setprecision(20) << "Square area is " << areaSquare << ", Circle area is " << areaCircle << std::endl;
    return 0;
}

Output:

Square area is 1, Circle area is 3.1415926535897932385

Try it here

How can I upgrade NumPy?

This works for me:

pip install numpy --upgrade

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Whilst you certainly can use MySQL's IF() control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE expression instead:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
         ELSE A
       END
WHERE  A IS NOT NULL

Of course, in this specific example it's a little wasteful to set A to itself in the ELSE clause—better entirely to filter such conditions from the UPDATE, via the WHERE clause:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
       END
WHERE  (A > 0 AND A < 1) OR (A > 1 AND A < 2)

(The inequalities entail A IS NOT NULL).

Or, if you want the intervals to be closed rather than open (note that this would set values of 0 to 1—if that is undesirable, one could explicitly filter such cases in the WHERE clause, or else add a higher precedence WHEN condition):

UPDATE Table
SET    A = CASE
         WHEN A BETWEEN 0 AND 1 THEN 1
         WHEN A BETWEEN 1 AND 2 THEN 2
       END
WHERE  A BETWEEN 0 AND 2

Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL() instead:

UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2

How to use the "required" attribute with a "radio" input field

You can use this code snippet ...

<html>
  <body>
     <form>
          <input type="radio" name="color" value="black" required />
          <input type="radio" name="color" value="white" />
          <input type="submit" value="Submit" />
    </form>
  </body>
</html>

Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.

Add the following into you .css file.

/* style all elements with a required attribute */
:required {
  background: red;
}

For more information you can refer following URL.

https://css-tricks.com/almanac/selectors/r/required/

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

How to get the name of the current Windows user in JavaScript

If the script is running on Microsoft Windows in an HTA or similar, you can do this:

var wshshell=new ActiveXObject("wscript.shell");
var username=wshshell.ExpandEnvironmentStrings("%username%");

Otherwise, as others have pointed out, you're out of luck. This is considered to be private information and is not provided by the browser to the javascript engine.

How to hide column of DataGridView when using custom DataSource?

Set that particular column's Visible property = false

dataGridView[ColumnName or Index].Visible = false;

Edit sorry missed the Columns Property dataGridView.Columns[ColumnName or Index].Visible = false;

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Cannot find control with name: formControlName in angular reactive form

For me even with [formGroup] the error was popping up "Cannot find control with name:''".
It got fixed when I added ngModel Value to the input box along with formControlName="fileName"

  <form class="upload-form" [formGroup]="UploadForm">
  <div class="row">
    <div class="form-group col-sm-6">
      <label for="fileName">File Name</label>
      <!-- *** *** *** Adding [(ngModel)]="FileName" fixed the issue-->
      <input type="text" class="form-control" id="fileName" [(ngModel)]="FileName"
        placeholder="Enter file name" formControlName="fileName"> 
    </div>
    <div class="form-group col-sm-6">
      <label for="selectedType">File Type</label>
      <select class="form-control" formControlName="selectedType" id="selectedType" 
        (change)="TypeChanged(selectedType)" name="selectedType" disabled="true">
        <option>Type 1</option>
        <option>Type 2</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label for="fileUploader">Select {{selectedType}} file</label>
    <input type="file" class="form-control-file" id="fileUploader" (change)="onFileSelected($event)">
  </div>
  <div class="w-80 text-right mt-3">
    <button class="btn btn-primary mb-2 search-button cancel-button" (click)="cancelUpload()">Cancel</button>
    <button class="btn btn-primary mb-2 search-button" (click)="uploadFrmwrFile()">Upload</button>
  </div>
 </form>

And in the controller

ngOnInit() {
this.UploadForm= new FormGroup({
  fileName: new FormControl({value: this.FileName}),
  selectedType: new FormControl({value: this.selectedType, disabled: true}, Validators.required),
  frmwareFile: new FormControl({value: ['']})
});
}

JQuery .hasClass for multiple values in an if statement

The hasClass method will accept an array of class names as an argument, you can do something like this:

$(document).ready(function() {
function filterFilesList() {
    var rows = $('.file-row');
    var checked = $("#filterControls :checkbox:checked");

    if (checked.length) {
        var criteriaCollection = [];

        checked.each(function() {
            criteriaCollection.push($(this).val());
        });

        rows.each(function() {
            var row = $(this);
            var rowMatch = row.hasClass(criteriaCollection);

            if (rowMatch) {
                row.show();
            } else {
                row.hide(200);
            }
        });
    } else {
        rows.each(function() {
            $(this).show();
        });
    }
}

    $("#filterControls :checkbox").click(filterFilesList);
    filterFilesList();
});

Show DialogFragment with animation growing from a point

To get a full-screen dialog with animation, write the following ...

Styles:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionModeBackground">?attr/colorPrimary</item>
    <item name="windowActionModeOverlay">true</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.NoActionBar.FullScreenDialog">
    <item name="android:windowAnimationStyle">@style/Animation.WindowSlideUpDown</item>
</style>

<style name="Animation.WindowSlideUpDown" parent="@android:style/Animation.Activity">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_down</item>
</style>

res/anim/slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:interpolator/accelerate_quad">

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromYDelta="100%"
        android:toYDelta="0%"/>
</set>

res/anim/slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="@android:interpolator/accelerate_quad">

    <translate
        android:duration="@android:integer/config_shortAnimTime"
        android:fromYDelta="0%"
        android:toYDelta="100%"/>
</set>

Java code:

public class MyDialog extends DialogFragment {

    @Override
    public int getTheme() {
        return R.style.AppTheme_NoActionBar_FullScreenDialog;
    }
}

private void showDialog() {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    Fragment previous = getSupportFragmentManager().findFragmentByTag(MyDialog.class.getName());
    if (previous != null) {
        fragmentTransaction.remove(previous);
    }
    fragmentTransaction.addToBackStack(null);

    MyDialog dialog = new MyDialog();
    dialog.show(fragmentTransaction, MyDialog.class.getName());
}

What is the difference between require_relative and require in Ruby?

I want to add that when using Windows you can use require './1.rb' if the script is run local or from a mapped network drive but when run from an UNC \\servername\sharename\folder path you need to use require_relative './1.rb'.

I don't mingle in the discussion which to use for other reasons.

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

How to find the files that are created in the last hour in unix

Check out this link for more details.

To find files which are created in last one hour in current directory, you can use -amin

find . -amin -60 -type f

This will find files which are created with in last 1 hour.

How to copy file from one location to another location?

Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original). Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.

 public static void main(String[] args) throws IOException {
                String destFolderPath = "D:/TestFile/abc";
                String fileName = "pqr.xlsx";
                String sourceFilePath= "D:/TestFile/xyz.xlsx";
                File f = new File(destFolderPath);
                if(f.mkdir()){
                    System.out.println("Directory created!!!!");
                }
                else {
                    System.out.println("Directory Exists!!!!");
                }
                f= new File(destFolderPath,fileName);
                if(f.createNewFile())   {

                    System.out.println("File Created!!!!");
                }   else {
                    System.out.println("File exists!!!!");
                }

                Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
                System.out.println("Copy done!!!!!!!!!!!!!!");


            }

How to comment and uncomment blocks of code in the Office VBA Editor

There is a built-in Edit toolbar in the VBA editor that has the Comment Block and Uncomment Block buttons by default, and other useful tools.

If you right-click any toolbar or menu (or go to the View menu > Toolbars), you will see a list of available toolbars (above the "Customize..." option). The Standard toolbar is selected by default. Select the Edit toolbar and the new toolbar will appear, with the Comment Block buttons in the middle.

enter image description here

*This is a simpler option to the ones mentioned.

Append to string variable

Ronal, to answer your question in the comment in my answer above:

function wasClicked(str)
{
  return str+' def';
}

Web scraping with Java

If you wish to automate scraping of large amount pages or data, then you could try Gotz ETL.

It is completely model driven like a real ETL tool. Data structure, task workflow and pages to scrape are defined with a set of XML definition files and no coding is required. Query can be written either using Selectors with JSoup or XPath with HtmlUnit.

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

How to load a UIView using a nib file created with Interface Builder

Thank you all. I did find a way to do what I wanted.

  1. Create your UIView with the IBOutlets you need.
  2. Create the xib in IB, design it to you liking and link it like this: The File's Owner is of class UIViewController (No custom subclass, but the "real" one). The File Owner's view is connected to the main view and its class is declared as the one from step 1).
  3. Connect your controls with the IBOutlets.
  4. The DynamicViewController can run its logic to decide what view/xib to load. Once its made the decission, in the loadView method put something like this:

    NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"QPickOneView"
                                                      owner:self
                                                    options:nil];
    
    QPickOneView* myView = [ nibViews objectAtIndex: 1];
    
    myView.question = question;
    

That's it!

The main bundle's loadNibNamed method will take care of initializing the view and creating the connections.

Now the ViewController can display a view or another depending on the data in memory, and the "parent" screen doesn't need to bother with this logic.

What is the purpose of Android's <merge> tag in XML layouts?

The include tag

The <include> tag lets you to divide your layout into multiple files: it helps dealing with complex or overlong user interface.

Let's suppose you split your complex layout using two include files as follows:

top_level_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <include layout="@layout/include1.xml" />

    <!-- Second include file -->
    <include layout="@layout/include2.xml" />

</LinearLayout>

Then you need to write include1.xml and include2.xml.

Keep in mind that the xml from the include files is simply dumped in your top_level_activity layout at rendering time (pretty much like the #INCLUDE macro for C).

The include files are plain jane layout xml.

include1.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView1"
    android:text="First include"
    android:textAppearance="?android:attr/textAppearanceMedium"/>

... and include2.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button1"
    android:text="Button" />

See? Nothing fancy. Note that you still have to declare the android namespace with xmlns:android="http://schemas.android.com/apk/res/android.

So the rendered version of top_level_activity.xml is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <TextView
        android:id="@+id/textView1"
        android:text="First include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />


</LinearLayout>

In your java code, all this is transparent: findViewById(R.id.textView1) in your activity class returns the correct widget ( even if that widget was declared in a xml file different from the activity layout).

And the cherry on top: the visual editor handles the thing swimmingly. The top level layout is rendered with the xml included.

The plot thickens

As an include file is a classic layout xml file, it means that it must have one top element. So in case your file needs to include more than one widget, you would have to use a layout.

Let's say that include1.xml has now two TextView: a layout has to be declared. Let's choose a LinearLayout.

include1.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout2" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</LinearLayout>

The top_level_activity.xml will be rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <LinearLayout 
        android:id="@+id/layout2" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

       <TextView
            android:id="@+id/textView1"
            android:text="Second include"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

       <TextView
            android:id="@+id/textView2"
            android:text="More text"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

   </LinearLayout>

     <!-- Second include file -->
   <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

But wait the two levels of LinearLayout are redundant!

Indeed, the two nested LinearLayout serve no purpose as the two TextView could be included under layout1for exactly the same rendering.

So what can we do?

Enter the merge tag

The <merge> tag is just a dummy tag that provides a top level element to deal with this kind of redundancy issues.

Now include1.xml becomes:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</merge>

and now top_level_activity.xml is rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file --> 
    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

You saved one hierarchy level, avoid one useless view: Romain Guy sleeps better already.

Aren't you happier now?

Makefile ifeq logical or

Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:

ifeq ($(shell test ".$(GCC_MINOR)" = .4  -o  \
                   ".$(GCC_MINOR)" = .5  -o  \
                   ".$(TODAY)"     = .Friday  &&  printf "true"), true)
    CFLAGS += -fno-strict-overflow
endif

Cookies on localhost with explicit domain

There seems to be an issue when you use https://<local-domain> and then http://<local-domain>. The http:// site does not send cookies with requests after https:// site sets them. Force reload and clear cache doesn't help. Only manual clearing of cookies works. Also, if I clear them on the https:// page, then http:// page starts working again.

Looks to be related to "Strict secure cookies". Good explanation here. It was released in Chrome 58 on 2017-04-19.

It looks like Chrome does in fact record both secure cookies and non-secure cookies as it will show the correct cookies depending on the page's protocol when clicking the address bar icon.

But Developer tools > Application > Cookies will not show a non-secure cookie when there is a secure cookie of the same name for the same domain, nor will it send the non-secure cookie with any requests. This seems like a Chrome bug, or if this behavior is expected, there should be some way to view the secure cookies when on a http page and an indication that they are being overridden.

Workaround is to use different named cookies depending on if they are for an http site or https site, and to name them specific to your app. A __Secure- prefix indicates that the cookie should be strictly secure, and is also a good practice because secure and non-secure won't collide. There are other benefits to prefixes too.

Using different /etc/hosts domains for https vs. http access would work too, but one accidental https://localhost visit will prevent any cookies of the same names to work on http://localhost sites - so this is not a good workaround.

I have filed a Chrome bug report.

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

`&mdash;` or `&#8212;` is there any difference in HTML output?

&mdash; :: &#8212; :: \u2014

When representing the m-dash in a JavaScript text string for output to HTML, note that it will be represented by its unicode value. There are cases when ampersand characters ('&') will not be resolved—notably certain contexts within JSX. In this case, neither &mdash; nor &#8212; will work. Instead you need to use the Unicode escape sequence: \u2014.

For example, when implementing a render() method to output text from a JavaScript variable:

render() {
   let text='JSX transcoders will preserve the & character&mdash;to ' 
            + 'protect from possible script hacking and cross-site hacks.'
   return (
     <div>{text}</div>
   )
}

This will output:

<div>JSX transcoders will preserve the & character&mdash;to protect from possible script hacking and cross-site hacks.</div>

Instead of the &– prefixed representation, you should use \u2014:

let text='JSX transcoders will preserve the & character\u2014to …'

How to set time to a date object in java

Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:

new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")

Check if a number is odd or even in python

Use the modulo operator:

if wordLength % 2 == 0:
    print "wordLength is even"
else:
    print "wordLength is odd"

For your problem, the simplest is to check if the word is equal to its reversed brother. You can do that with word[::-1], which create the list from word by taking every character from the end to the start:

def is_palindrome(word):
    return word == word[::-1]

ASP.NET Background image

resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...

hard-size your DIV relative to your image

position your asp:login control where needed...

PostgreSQL error 'Could not connect to server: No such file or directory'

It's very simple. Only add host in your database.yaml file.

How can I list (ls) the 5 last modified files in a directory?

By default ls -t sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.

For the newest 5 files ordered from newest to oldest, use head to take the first 5 lines of output:

ls -t | head -n 5

For the newest 5 files ordered from oldest to newest, use the -r switch to reverse ls's sort order, and use tail to take the last 5 lines of output:

ls -tr | tail -n 5

How to wrap text in textview in Android

In Android Studio 2.2.3 under the inputType property there is a property called textMultiLine. Selecting this option sorted out a similar problem for me. I hope that helps.

'Field required a bean of type that could not be found.' error spring restful API using mongodb

I also had the same error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field repository in com.kalsym.next.gen.campaign.controller.CampaignController required a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' that could not be found.


Action:

Consider defining a bean of type 'com.kalsym.next.gen.campaign.data.CustomerRepository' in your configuration.de here

And my packages were constructed in the same way as mentioned in the accepted answer. I fixed my issue by adding EnableMongoRepositories annotation in the main class like this:

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
public class CampaignAPI {

    public static void main(String[] args) {
        SpringApplication.run(CampaignAPI.class, args);
    }
}

If you need to add multiple don't forget the curly braces:

@EnableMongoRepositories(basePackageClasses
    = {
        MSASMSRepository.class, APartyMappingRepository.class
    })

Generating a random & unique 8 character string using MySQL

Create a random string

Here's a MySQL function to create a random string of a given length.

DELIMITER $$

CREATE DEFINER=`root`@`%` FUNCTION `RandString`(length SMALLINT(3)) RETURNS varchar(100) CHARSET utf8
begin
    SET @returnStr = '';
    SET @allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    SET @i = 0;

    WHILE (@i < length) DO
        SET @returnStr = CONCAT(@returnStr, substring(@allowedChars, FLOOR(RAND() * LENGTH(@allowedChars) + 1), 1));
        SET @i = @i + 1;
    END WHILE;

    RETURN @returnStr;
END

Usage SELECT RANDSTRING(8) to return an 8 character string.

You can customize the @allowedChars.

Uniqueness isn't guaranteed - as you'll see in the comments to other solutions, this just isn't possible. Instead you'll need to generate a string, check if it's already in use, and try again if it is.


Check if the random string is already in use

If we want to keep the collision checking code out of the app, we can create a trigger:

DELIMITER $$

CREATE TRIGGER Vehicle_beforeInsert
  BEFORE INSERT ON `Vehicle`
  FOR EACH ROW
  BEGIN
    SET @vehicleId = 1;
    WHILE (@vehicleId IS NOT NULL) DO 
      SET NEW.plate = RANDSTRING(8);
      SET @vehicleId = (SELECT id FROM `Vehicle` WHERE `plate` = NEW.plate);
    END WHILE;
  END;$$
DELIMITER ;

javascript toISOString() ignores timezone offset

Using moment.js, you can use keepOffset parameter of toISOString:

toISOString(keepOffset?: boolean): string;

moment().toISOString(true)

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Greedy means it will consume your pattern until there are none of them left and it can look no further.

Lazy will stop as soon as it will encounter the first pattern you requested.

One common example that I often encounter is \s*-\s*? of a regex ([0-9]{2}\s*-\s*?[0-9]{7})

The first \s* is classified as greedy because of * and will look as many white spaces as possible after the digits are encountered and then look for a dash character "-". Where as the second \s*? is lazy because of the present of *? which means that it will look the first white space character and stop right there.

How to load a model from an HDF5 file in Keras?

I done in this way

from keras.models import Sequential
from keras_contrib.losses import import crf_loss
from keras_contrib.metrics import crf_viterbi_accuracy

# To save model
model.save('my_model_01.hdf5')

# To load the model
custom_objects={'CRF': CRF,'crf_loss': crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}

# To load a persisted model that uses the CRF layer 
model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)

@angular/material/index.d.ts' is not a module

? DO NOT:

// old code that breaks
import { MatDialogModule,
  MatInputModule,
  MatButtonModule} from '@angular/material';

? DO:

// new code that works
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';

? Because:

Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.

Deleting a SQL row ignoring all foreign keys and constraints

On all tables with foreign keys pointing to this one, use:

ALTER TABLE MyOtherTable NOCHECK CONSTRAINT fk_name

Accessing Websites through a Different Port?

when viewing a website it gets assigned a random port, it will always come from port 80 (usually always, unless the server admin has changed the port) there's no way for someone to change that port unless you have control of the server.

Override back button to act like home button

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

Batch file to map a drive when the folder name contains spaces

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes 

does not work?

Installing python module within code

This should work:

import subprocess

def install(name):
    subprocess.call(['pip', 'install', name])

WP -- Get posts by category?

Check here : http://codex.wordpress.org/Template_Tags/get_posts

Note: The category parameter needs to be the ID of the category, and not the category name.

Disable hover effects on mobile browsers

Hello person from the future, you probably want to use the pointer and/or hover media query. The handheld media query was deprecated.

/* device is using a mouse or similar */
@media (pointer: fine) {
  a:hover {
    background: red;
  }
}

Can't access object property, even though it shows up in a console log

I struggled with this issue today, and thought I'll leave a reply with my solution.

I was fetching a data object via ajax, something like this: {"constants": {"value1":"x","value2":"y"},"i18n" {"data1":"x", "data2":"y"}}

Let's say this object is in a variable called data. Whenever I referenced data.i18n I got undefined.

  1. console.log(data) showed the object as expected
  2. console.log(Object.keys(data)) said ["constants","i18n"] as expected
  3. Renaming i18n to inter didn't change anything
  4. I even tried to switch the data to make "i18n" the first object
  5. Moved code around to make absolutely sure the object was completely set and there was no problem with the ajax promise.

Nothing helped... Then on the server side I wrote the data to the php log, and it revealed this:

{"constants": {"value1":"x","value2":"y"},"\u045618n" {"data1":"x", "data2":"y"}}

The "i" in the index key was actually a u0456 (cyrillic i). This was not visible in my php editor or the browser console log. Only the php log revealed this... That was a tricky one...

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

SVN repository backup strategies

as others have said, hot-backup.py from the Subversion team has some nice features over just plain svnadmin hotcopy

I run a scheduled task on a python script that spiders for all my repositories on the machine, and uses hotbackup to keep several days worth of hotcopies (paranoid of corruption) and an svnadmin svndump on a remote machine. Restoration is really easy from that - so far.

Find size and free space of the filesystem containing a given file

For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage() returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.

Simple example from documentation:

>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)

Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.

How does one parse XML files?

I'm not sure whether "best practice for parsing XML" exists. There are numerous technologies suited for different situations. Which way to use depends on the concrete scenario.

You can go with LINQ to XML, XmlReader, XPathNavigator or even regular expressions. If you elaborate your needs, I can try to give some suggestions.

How do you debug PHP scripts?

Usually I find create a custom log function able to save on file, store debug info, and eventually re-print on a common footer.

You can also override common Exception class, so that this type of debugging is semi-automated.

Find all packages installed with easy_install/pip?

If you use the Anaconda python distribution, you can use the conda list command to see what was installed by what method:

user@pc:~ $ conda list
# packages in environment at /anaconda3:
#
# Name                    Version                   Build  Channel
_ipyw_jlab_nb_ext_conf    0.1.0            py36h2fc01ae_0
alabaster                 0.7.10           py36h174008c_0
amqp                      2.2.2                     <pip>
anaconda                  5.1.0                    py36_2
anaconda-client           1.6.9                    py36_0

To grab the entries installed by pip (including possibly pip itself):

user@pc:~ $ conda list | grep \<pip
amqp                      2.2.2                     <pip>
astroid                   1.6.2                     <pip>
billiard                  3.5.0.3                   <pip>
blinker                   1.4                       <pip>
ez-setup                  0.9                       <pip>
feedgenerator             1.9                       <pip>

Of course you probably want to just select the first column, which you can do with (excluding pip if needed):

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}'
amqp        
astroid
billiard
blinker
ez-setup
feedgenerator 

Finally you can grab these values and pip uninstall all of them using the following:

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}' | xargs pip uninstall -y

Note the use of the -y flag for the pip uninstall to avoid having to give confirmation to delete.

Permission denied error while writing to a file in Python

In order to write on a file by using a Python script, you would have to create a text file first. Example A file such as C:/logs/logs.txt should exist. Only then the following code works:

logfile=open(r"C:/logs/logs.txt",'w')

So summary.

  1. A text file should exist on the specified location
  2. Make sure you close the file before running the Python script.

Nesting optgroups in a dropdownlist/select

I think if you have something that structured and complex, you might consider something other than a single drop-down box.