Programs & Examples On #.net 4.0

Version 4.0 of the .NET Framework. Use for questions specifically related to .NET Framework 4.0. For questions on .NET Framework generally, use the .net tag.

What are the true benefits of ExpandoObject?

It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Try to use another config file (not the one from your project) and RESTART Visual Studio:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.executionengine.x86.exe.config
(32-bit)

or

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.executionengine.exe.config
(64-bit)

Get property value from C# dynamic object by string (reflection?)

Use the following code to get Name and Value of a dynamic object's property.

dynamic d = new { Property1= "Value1", Property2= "Value2"};

var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
    var PropertyName=property.Name; 
//You get "Property1" as a result

  var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null); 
//You get "Value1" as a result

// you can use the PropertyName and Value here
 }

.NET 4.0 has a new GAC, why?

Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.

In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.

To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

Source

Why?

It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.

See the following information in MSDN about the GAC changes in 4.0.

For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.

As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.

Fixing slow initial load for IIS

See this article for tips on how to help performance issues. This includes both performance issues related to starting up, under the "cold start" section. Most of this will matter no matter what type of server you are using, locally or in production.

https://blogs.msdn.microsoft.com/b/mcsuksoldev/2011/01/19/common-performance-issues-on-asp-net-web-sites/

If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services. http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx

If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence=”false” into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list. http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx

http://msdn.microsoft.com/en-us/library/bb629393.aspx

Consider using NGEN on all assemblies. However without careful use this doesn’t give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost. http://msdn.microsoft.com/en-us/magazine/cc163610.aspx

App.Config Transformation for projects which are not Web Projects in Visual Studio?

I have created another alternative to the one posted by Vishal Joshi where the requirement to change the build action to Content is removed and also implemented basic support for ClickOnce deployment. I say basic, because I didn't test it thoroughly but it should work in the typical ClickOnce deployment scenario.

The solution consists of a single MSBuild project that once imported to an existent windows application project (*.csproj) extends the build process to contemplate app.config transformation.

You can read a more detailed explanation at Visual Studio App.config XML Transformation and the MSBuild project file can be downloaded from GitHub.

ComboBox- SelectionChanged event has old value, not new value

The correct value to check here is the SelectedItem property.

A ComboBox is a composite control with two of its parts being:

  1. The Text Part: the value in the this part corresponds to the Text property of the ComboBox.
  2. The Selector Part (i.e. the "drop-down" part): The selected item in this part corresponds to the SelectedItem property.

Expanded ComboBox Parts

The image above was taken immediately after the ComboBox was expanded (i.e. before selecting a new value). At this point both Text and SelectedItem are "Info", assuming the ComboBox items were strings. If the ComboBox items were instead all the values of an Enum called "LogLevel", SelectedItem would currently be LogLevel.Info.

When an item in the drop-down is clicked on, the value of SelectedItem is changed and the SelectionChanged event is raised. The Text property isn't updated yet, though, as the Text Part isn't updated until after the SelectionChanged handler is finished. This can be observed by putting a breakpoint in the handler and looking at the control:

ComboBox at breakpoint in SelectionChanged handler

Since the Text Part hasn't been updated at this point, the Text property returns the previously selected value.

TLS 1.2 in .NET Framework 4.0

The only way I have found to change this is directly on the code :

at the very beginning of your app you set

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

you should include the system.net class

I did this before calling a web service because we had to block tls1 too.

Twitter Bootstrap and ASP.NET GridView

Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:

GridLines="None"
CellSpacing="-1"

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

In case if you're trying to deploy a project using VSTS, then issue might be connected with checking "Hosted Windows Container" option instead of "Hosted VS2017"(or 18, etc.):

enter image description here

Passing a method parameter using Task.Factory.StartNew

For passing a single integer I agree with Reed Copsey's answer. If in the future you are going to pass more complicated constucts I personally like to pass all my variables as an Anonymous Type. It will look something like this:

foreach(int id in myIdsToCheck)
{
    Task.Factory.StartNew( (Object obj) => 
        {
           var data = (dynamic)obj;
           CheckFiles(data.id, theBlockingCollection,
               cancelCheckFile.Token, 
               TaskCreationOptions.LongRunning, 
               TaskScheduler.Default);
        }, new { id = id }); // Parameter value
}

You can learn more about it in my blog

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

Below step solved my issue:

Open CMD Prompt with Admin Privileges.

Run : iisreset.

Hope this helps.

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

I had this in a solution w/ 6 projects. One of my projects was referring to the named assembly as a file reference. The others were all pointing to the project reference.

I usually get a different error in these cases.

My solution was to delete the named assembly anywhere it was referenced and add it back. Once I worked through the project, ths problem disappeared. Before doing this, I tried cleaning the solution as well as making sure none of the projects were signed.

hope it helps someone...

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

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

So it should work fine.

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

See also: Maximum request length exceeded

Problem in running .net framework 4.0 website on iis 7.0

If you don't have ISAPI and CGI Restrictions option listed, here is how to add it. How to add ISAPI and CGI Restrictions

enter image description here

What and When to use Tuple?

Tuple classes allow developers to be 'quick and lazy' by not defining a specific class for a specific use.

The property names are Item1, Item2, Item3 ..., which may not be meaningful in some cases or without documentation.

Tuple classes have strongly typed generic parameters. Still users of the Tuple classes may infer from the type of generic parameters.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

What's new in .NET Framework 4 Client Profile RTM explains many of the differences:

When to use NET4 Client Profile and when to use NET4 Full Framework?
NET4 Client Profile:
Always target NET4 Client Profile for all your client desktop applications (including Windows Forms and WPF apps).

NET4 Full framework:
Target NET4 Full only if the features or assemblies that your app need are not included in the Client Profile. This includes:

  • If you are building Server apps. Such as:
    o ASP.Net apps
    o Server-side ASMX based web services
  • If you use legacy client scenarios. Such as:
    o Use System.Data.OracleClient.dll which is deprecated in NET4 and not included in the Client Profile.
    o Use legacy Windows Workflow Foundation 3.0 or 3.5 (WF3.0 , WF3.5)
  • If you targeting developer scenarios and need tool such as MSBuild or need access to design assemblies such as System.Design.dll

However, as stated on MSDN, this is not relevant for >=4.5:

Starting with the .NET Framework 4.5, the Client Profile has been discontinued and only the full redistributable package is available. Optimizations provided by the .NET Framework 4.5, such as smaller download size and faster deployment, have eliminated the need for a separate deployment package. The single redistributable streamlines the installation process and simplifies your app's deployment options.

Razor View Engine : An expression tree may not contain a dynamic operation

In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.: @model MyNamespace.Models.MyModel

Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M").

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

Other alternatives to an installer and gacutil are GUI tools like Gac Manager or GACAdmin. Or if you like PowerShell you could use PowerShell GAC from which I am the author.

How can I get a web site's favicon?

Sometimes we can't get the favicon image with the purposed solution as some websites use .png or other image extensions. Here is the working solution.

  1. Open your website with a firefox browser.
  2. Right-click on the website and click the "View page info" option from the list.
  3. It will open up a dialog and click on the "Media" tab.
  4. In that tab you will see all the images including favicon.
  5. Select the favicon.ico image or click through the images to see which image is used as favicon. Some websites use .png images as well.
  6. Then click on the "Save As" button and you should be good to go.

thanks!

How to abort a Task like aborting a Thread (Thread.Abort method)?

You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.

(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

This answer may be late reply but it will be useful for seeing this topic in future.

The features of .NET framework 4.5 can be seen in the following link.

To summarize:

  • Installation

    .NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.

  • Support for Arrays Larger than 2 GB on 64-bit Platforms
  • Enhanced Background Server Garbage Collection
  • Support for Timeouts in Regular Expression Evaluations
  • Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
  • Simple Default Culture Definition for an Application Domain
  • Internationalized Domain Names in Windows 8 Apps

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

How to easily initialize a list of Tuples?

Old question, but this is what I typically do to make things a bit more readable:

Func<int, string, Tuple<int, string>> tc = Tuple.Create;

var tupleList = new List<Tuple<int, string>>
{
    tc( 1, "cow" ),
    tc( 5, "chickens" ),
    tc( 1, "airplane" )
};

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

Where is GACUTIL for .net Framework 4.0 in windows 7?

VS 2012/13 Win 7 64 bit gacutil.exe is located in

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

I have a .NET 4.0 dll project that is being called by a .NET 2.0 project. Is there a way to reconcile the difference in framework?

Not that way round, no. The .NET 4 CLR can load .NET 2 assemblies (usually - there are a few exceptions for mixed-mode assemblies, IIRC), but not vice versa.

You'll either have to upgrade the .NET 2 project to .NET 4, or downgrade the .NET 4 project to .NET 3.5 (or earlier).

How can I run PowerShell with the .NET 4 runtime?

If you only need to execute a single command, script block, or script file in .NET 4, try using Activation Configuration Files from .NET 4 to start only a single instance of PowerShell using version 4 of the CLR.

Full details:

http://blog.codeassassin.com/2011/03/23/executing-individual-powershell-commands-using-net-4/

An example PowerShell module:

https://gist.github.com/882528

What is the best way to implement a "timer"?

Use the Timer class.

public static void Main()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000;
    aTimer.Enabled = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read() != 'q');
}

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify. In the example above, it is OnTimedEvent.

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

Is it possible to run a .NET 4.5 app on XP?

Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.

see there: https://download.mono-project.com/archive/4.3.2/windows-installer/

How do I check if a property exists on a dynamic anonymous type in c#?

None of the solutions above worked for dynamic that comes from Json, I however managed to transform one with Try catch (by @user3359453) by changing exception type thrown (KeyNotFoundException instead of RuntimeBinderException) into something that actually works...

public static bool HasProperty(dynamic obj, string name)
    {
        try
        {
            var value = obj[name];
            return true;
        }
        catch (KeyNotFoundException)
        {
            return false;
        }
    }

enter image description here

Hope this saves you some time.

Convert month int to month name

var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);

You can try this one as well

Maximum value of maxRequestLength?

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

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

Exception: "URI formats are not supported"

I solved the same error with the Path.Combine(MapPath()) to get the physical file path instead of the http:/// www one.

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I ran into this issue when we changed to Visual Studio 2015. None of the above answers worked for us. In the end we got it working by adding the following config file to ALL sgen.exe executables on the machine

<?xml version ="1.0"?>
    <configuration>
        <startup useLegacyV2RuntimeActivationPolicy="true">
            <supportedRuntime version="v4.0" />
        </startup>    
</configuration>

Particularly in this location, even when we were targeting .NET 4.0:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools

ASP.NET MVC on IIS 7.5

For me, the solution was to add the NuGet package Microsoft.AspNet.WebPages (plus it's Razor and Infrastructure dependencies) to my web project.

Infrastructure had to be forcefully reinstalled as it was not added as a reference at first.

read string from .resx file in C#

Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.

.NET console application as Windows service

Firstly I embed the console application solution into the windows service solution and reference it.

Then I make the console application Program class public

/// <summary>
/// Hybrid service/console application
/// </summary>
public class Program
{
}

I then create two functions within the console application

    /// <summary>
    /// Used to start as a service
    /// </summary>
    public void Start()
    {
        Main();
    }

    /// <summary>
    /// Used to stop the service
    /// </summary>
    public void Stop()
    {
       if (Application.MessageLoop)
            Application.Exit();   //windows app
        else
            Environment.Exit(1);  //console app
    }

Then within the windows service itself I instantiate the Program and call the Start and Stop functions added within the OnStart and OnStop. See below

class WinService : ServiceBase
{
    readonly Program _application = new Program();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] servicesToRun = { new WinService() };
        Run(servicesToRun);
    }

    /// <summary>
    /// Set things in motion so your service can do its work.
    /// </summary>
    protected override void OnStart(string[] args)
    {
        Thread thread = new Thread(() => _application.Start());
        thread.Start();
    }

    /// <summary>
    /// Stop this service.
    /// </summary>
    protected override void OnStop()
    {
        Thread thread = new Thread(() => _application.Stop());
        thread.Start();
    }
}

This approach can also be used for a windows application / windows service hybrid

How can I send a file document to the printer and have it print?

The following code snippet is an adaptation of Kendall Bennett's code for printing pdf files using the PdfiumViewer library. The main difference is that a Stream is used rather than a file.

public bool PrintPDF(
    string printer,
    string paperName,
    int copies, Stream stream)
        {
            try
            {
                // Create the printer settings for our printer
                var printerSettings = new PrinterSettings
                {
                    PrinterName = printer,
                    Copies = (short)copies,
                };

            // Create our page settings for the paper size selected
            var pageSettings = new PageSettings(printerSettings)
            {
                Margins = new Margins(0, 0, 0, 0),
            };
            foreach (PaperSize paperSize in printerSettings.PaperSizes)
            {
                if (paperSize.PaperName == paperName)
                {
                    pageSettings.PaperSize = paperSize;
                    break;
                }
            }

            // Now print the PDF document
            using (var document = PdfiumViewer.PdfDocument.Load(stream))
            {
                using (var printDocument = document.CreatePrintDocument())
                {
                    printDocument.PrinterSettings = printerSettings;
                    printDocument.DefaultPageSettings = pageSettings;
                    printDocument.PrintController = new StandardPrintController();
                    printDocument.Print();
                }
            }
            return true;
        }
        catch (System.Exception e)
        {
            return false;
        }
    }

In my case I am generating the PDF file using a library called PdfSharp and then saving the document to a Stream like so:

        PdfDocument pdf = PdfGenerator.GeneratePdf(printRequest.html, PageSize.A4);
        pdf.AddPage();

        MemoryStream stream = new MemoryStream();
        pdf.Save(stream);
        MemoryStream stream2 = new MemoryStream(stream.ToArray());

One thing that I want to point out that might be helpful to other developers is that I had to install the 32 bit version of the pdfuim native dll in order for the printing to work even though I am running Windows 10 64 bit. I installed the following two NuGet packages using the NuGet package manager in Visual Studio:

  • PdfiumViewer
  • PdfiumViewer.Native.x86.v8-xfa

How do I run msbuild from the command line using Windows SDK 7.1?

Using the "Developer Command Prompt for Visual Studio 20XX" instead of "cmd" will set the path for msbuild automatically without having to add it to your environment variables.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

How can I reverse a NSArray in Objective-C?

There is a easy way to do it.

    NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
    NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
    for(int i=0; i<[myNewArray count]; i++){
        [myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
    }
    //other way to do it
    for(NSString *eachValue in myArray){
        [myNewArray insertObject:eachValue atIndex:0];
    }

    //in both cases your new array will look like this
    NSLog(@"myNewArray: %@", myNewArray);
    //[@"1",@"2",@"3",@"4",@"5"]

I hope this helps.

How to run .sh on Windows Command Prompt?

Personally I used this batch file, but it does require CygWin installed (64-bit as shown). Just associate the file type .SH with this batchfile (ExecSH.BAT in my case) and you can double-click on the .SH and it runs.

@echo off
setlocal

if not exist "%~dpn1.sh" echo Script "%~dpn1.sh" not found & goto :eof

set _CYGBIN=C:\cygwin64\bin
if not exist "%_CYGBIN%" echo Couldn't find Cygwin at "%_CYGBIN%" & goto :eof

:: Resolve ___.sh to /cygdrive based *nix path and store in %_CYGSCRIPT%
for /f "delims=" %%A in ('%_CYGBIN%\cygpath.exe "%~dpn1.sh"') do set _CYGSCRIPT=%%A
for /f "delims=" %%A in ('%_CYGBIN%\cygpath.exe "%CD%"') do set _CYGPATH=%%A

:: Throw away temporary env vars and invoke script, passing any args that were passed to us
endlocal & %_CYGBIN%\mintty.exe -e /bin/bash -l -c 'cd %_CYGPATH%;  %_CYGSCRIPT% %*'

Based on this original work.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

Add System.IO.Compression.ZipFile as nuget reference it is working

Are Git forks actually Git clones?

"Fork" in this context means "Make a copy of their code so that I can add my own modifications". There's not much else to say. Every clone is essentially a fork, and it's up to the original to decide whether to pull the changes from the fork.

How to remove item from list in C#?

... or just resultlist.RemoveAt(1) if you know exactly the index.

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

How can I access "static" class variables within class methods in Python?

Define class method:

class Foo(object):
    bar = 1
    @classmethod
    def bah(cls):    
        print cls.bar

Now if bah() has to be instance method (i.e. have access to self), you can still directly access the class variable.

class Foo(object):
    bar = 1
    def bah(self):    
        print self.bar

Model summary in pytorch

Simplest to remember (not as pretty as Keras):

print(model)

This also work:

repr(model)

If you just want the number of parameters:

sum([param.nelement() for param in model.parameters()])

From: Is there similar pytorch function as model.summary() as keras? (forum.PyTorch.org)

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

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

You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments

@app.route('/<name>')
def my_view_func(name):
    return name

How to convert from java.sql.Timestamp to java.util.Date?

Class java.sql.TimeStamp extends from java.util.Date.

You can directly assign a TimeStamp object to Date reference:

TimeStamp timeStamp = //whatever value you have;
Date startDate = timestampValue;

Open another application from your own (intent)

Use following:

String packagename = "com.example.app";
startActivity(getPackageManager().getLaunchIntentForPackage(packagename));

Difference between nVidia Quadro and Geforce cards?

The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.

The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:

enter image description here

Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.

If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.

Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.

Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.


So to sum up:

The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).

Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.

That's about it, price-vise the Quadros or FirePros are artificially overpriced.

CSS: center element within a <div> element

First of all you can do it with left:50% to center it relative to parent div but for that you need to learn CSS positioning.

One possible solution from many is to do something like

    div.parent { text-align:center; }    //will center align every thing in this div as well as in the children element
    div.parent div { text-align:left;}   //to restore so every thing would start from left

if your your div to be centered is positioned relatively, you can just do

    .mydiv { position:relative; margin:0 auto; } 

The page cannot be displayed because an internal server error has occurred on server

I've fixed it. I had the following section in web.config :

httpErrors existingResponse="PassThrough"

When I remove it, I got a real error

Why do we need virtual functions in C++?

Are you familiar with function pointers? Virtual functions are a similar idea, except you can easily bind data to virtual functions (as class members). It is not as easy to bind data to function pointers. To me, this is the main conceptual distinction. A lot of other answers here are just saying "because... polymorphism!"

How do I remove a file from the FileList

I know this is an old question but it's ranking high on search engines in regards to this issue.

properties in the FileList object cannot be deleted but at least on Firefox they can be changed. My workaround this issue was to add a property IsValid=true to those files that passed check and IsValid=false to those that didn't.

then I just loop through the list to make sure that only the properties with IsValid=true are added to FormData.

jQuery selector for the label of a checkbox

Another solution could be:

$("#comedyclubs").next()

How to secure RESTful web services?

If choosing between OAuth versions, go with OAuth 2.0.

OAuth bearer tokens should only be used with a secure transport.

OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.

While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.

If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.

Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

How to iterate through a String

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

How to set time to midnight for current day?

Using some of the above recommendations, the following function and code is working for search a date range:

Set date with the time component set to 00:00:00

public static DateTime GetDateZeroTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}

Usage

var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);

var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));

How can I find where I will be redirected using cURL?

Add this line to curl inizialization

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

and use getinfo before curl_close

$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );

es:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
curl_close($ch);

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

How do implement a breadth first traversal?

public void breadthFirstSearch(Node root, Consumer<String> c) {
    List<Node> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()) {
        Node n = queue.remove(0);
        c.accept(n.value);

        if (n.left != null)
            queue.add(n.left);
        if (n.right != null)
            queue.add(n.right);
    }
}

And the Node:

public static class Node {
    String value;
    Node left;
    Node right;

    public Node(final String value, final Node left, final Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

EXEC sp_executesql with multiple parameters

If one need to use the sp_executesql with OUTPUT variables:

EXEC sp_executesql @sql
                  ,N'@p0 INT'
                  ,N'@p1 INT OUTPUT'
                  ,N'@p2 VARCHAR(12) OUTPUT' 
                  ,@p0
                  ,@p1 OUTPUT
                  ,@p2 OUTPUT;

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

React.js inline style best practices

There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.

There are a number of approaches that vary wildly: React inline-style lib comparison chart

All or nothing?

What we refer to as "style" actually includes quite a few concepts:

  • Layout — how an element/component looks in relationship to others
  • Appearance — the characteristics of an element/component
  • Behavior and state — how an element/component looks in a given state

Start with state-styles

React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.

Instead of building components to render with conditional state-classes, consider adding state-styles directly:

// Typical component with state-classes
<li 
 className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />


// Using inline-styles for state
<li className='todo-list__item'
 style={(item.complete) ? styles.complete : {}} />

Note that we're using a class to style appearance but no longer using any .is- prefixed class for state and behavior.

We can use Object.assign (ES6) or _.extend (underscore/lodash) to add support for multiple states:

// Supporting multiple-states with inline-styles
<li 'todo-list__item'
 style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>

Customization and reusability

Now that we're using Object.assign it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />. Implemented like this:

<li 'todo-list__item'
 style={Object.assign({},
         item.due && styles.due,
         item.due && this.props.dueStyles)}>

Layout

Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.

That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.

// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
 className="col-xs-12 col-sm-6 col-md-8"
 firstName="Michael"
 lastName="Chan" />

// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
  <UserBadge
   firstName="Michael"
   lastName="Chan" />
</div>

For layout support, I often try to design components to be 100% width and height.

Appearance

This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.

One thing is certain, you'll need the assistance of a library. Browser-states (:hover, :focus), and media-queries are painful in raw React.

I like Radium because the syntax for those hard parts is designed to model that of SASS.

Code organization

Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:

var styles = {
  root: {
    display: "block"
  },
  item: {
    color: "black"

    complete: {
      textDecoration: "line-through"
    },

    due: {
      color: "red"
    }
  },
}

getter functions

Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:

React.createClass({
  getStyles: function () {
    return Object.assign(
      {},
      item.props.complete && styles.complete,
      item.props.due && styles.due,
      item.props.due && this.props.dueStyles
    );
  },

  render: function () {
    return <li style={this.getStyles()}>{this.props.item}</li>
  }
});

Further watching

I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.

I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic

ASP.Net MVC 4 Form with 2 submit buttons/actions

You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:

<form id="myForm">
    <%-- form data inputs here ---%>
    <button id="edit">Edit</button>
    <button id="validate">Validate</button>
</form>

you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):

<script type="text/javascript">
      $("#edit").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Edit","MyController")");
          form.submit();
      });

      $("#validate").click(function() {
          var form = $("form#myForm");
          form.attr("action", "@Url.Action("Validate","MyController")");
          form.submit();
      });
</script>

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

OS X cp command in Terminal - No such file or directory

I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).

I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.

So, as an example:

cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]

vba pass a group of cells as range to function

There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )

The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.

To make this work, your function needs to loop through each of the Areas in the input ranges. For example:

Function calculateIt(Sessions As Range, Customers As Range) As Single

    ' check we passed the same number of areas
    If (Sessions.Areas.Count <> Customers.Areas.Count) Then
        calculateIt = CVErr(xlErrNA)
        Exit Function
    End If

    Dim mySession, myCustomers As Range

    ' run through each area and calculate
    For a = 1 To Sessions.Areas.Count

        Set mySession = Sessions.Areas(a)
        Set myCustomers = Customers.Areas(a)

        ' calculate them...
    Next a

End Function

The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9).

Hope that helps :)

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

Error in Process.Start() -- The system cannot find the file specified

Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message

I.e. this causes an issue with Process.Start() not finding your exe:

PATH="C:\my program\bin";c:\windows\system32

Maybe it helps someone.

Remove certain characters from a string

One issue with REPLACE will be where city names contain the district name. You can use something like.

SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM   dbo.tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004' 

Truncate with condition

No, TRUNCATE is all or nothing. You can do a DELETE FROM <table> WHERE <conditions> but this loses the speed advantages of TRUNCATE.

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Failed binder transaction when putting an bitmap dynamically in a widget

The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.

refer this link

Unable to create migrations after upgrading to ASP.NET Core 2.0

In my case setting the StartUp project in init helps. You can do this by executing

dotnet ef migrations add init -s ../StartUpProjectName

Failed to build gem native extension (installing Compass)

In order to install Compass on Yosemite you need to set up the Ruby environment and to install the Xcode Command Line Tools. But, most important thing, after updating Xcode, be sure to launch the Xcode application and accept the Apple license terms. It will complete the installation of the components. After that, you can install Compass: sudo gem install compass

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

How to find third or n?? maximum salary from salary table?

Refer following query for getting nth highest salary. By this way you get nth highest salary in MYSQL. If you want get nth lowest salary only you need to replace DESC by ASC in the query. nth highest salary

Mvn install or Mvn package

From the Lifecycle reference, install will run the project's integration tests, package won't.

If you really need to not install the generated artifacts, use at least verify.

Reload nginx configuration

Maybe you're not doing it as root?

Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx.

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality. In fact, both do this:

return this.Add(new SqlParameter(parameterName, value));

The reason they deprecated the old one in favor of AddWithValue is to add additional clarity, as well as because the second parameter is object, which makes it not immediately obvious to some people which overload of Add was being called, and they resulted in wildly different behavior.

Take a look at this example:

 SqlCommand command = new SqlCommand();
 command.Parameters.Add("@name", 0);

At first glance, it looks like it is calling the Add(string name, object value) overload, but it isn't. It's calling the Add(string name, SqlDbType type) overload! This is because 0 is implicitly convertible to enum types. So these two lines:

 command.Parameters.Add("@name", 0);

and

 command.Parameters.Add("@name", 1);

Actually result in two different methods being called. 1 is not convertible to an enum implicitly, so it chooses the object overload. With 0, it chooses the enum overload.

Send POST data using XMLHttpRequest

Minimal use of FormData to submit an AJAX request

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){ alert (xhr.responseText); } // success case
  xhr.onerror = function(){ alert (xhr.responseText); } // failure case
  xhr.open (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;
}
</script>
</head>

<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
  <input type="hidden" value="person"   name="user" />
  <input type="hidden" value="password" name="pwd" />
  <input type="hidden" value="place"    name="organization" />
  <input type="hidden" value="key"      name="requiredkey" />
  <input type="submit" value="post request"/>
</form>
</body>
</html>

Remarks

  1. This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.

  2. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.

  3. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.

Hibernate dialect for Oracle Database 11g?

Use the Oracle 10g dialect. Also Hibernate 3.3.2+ is required for recent JDBC drivers (the internal class structure changed - symptoms will be whining about an abstract class).

Dialect of Oracle 11g is same as Oracle 10g (org.hibernate.dialect.Oracle10gDialect). Source: http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/session-configuration.html#configuration-optional-dialects

how to change any data type into a string in python

Use the str built-in:

x = str(something)

Examples:

>>> str(1)
'1'
>>> str(1.0)
'1.0'
>>> str([])
'[]'
>>> str({})
'{}'

...

From the documentation:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

What does a bitwise shift (left or right) do and what is it used for?

Yes, I think performance-wise you might find a difference as bitwise left and right shift operations can be performed with a complexity of o(1) with a huge data set.

For example, calculating the power of 2 ^ n:

int value = 1;
while (exponent<n)
    {
       // Print out current power of 2
        value = value *2; // Equivalent machine level left shift bit wise operation
        exponent++;
         }
    }

Similar code with a bitwise left shift operation would be like:

value = 1 << n;

Moreover, performing a bit-wise operation is like exacting a replica of user level mathematical operations (which is the final machine level instructions processed by the microcontroller and processor).

How many bytes is unsigned long long?

Executive summary: it's 64 bits, or larger.

unsigned long long is the same as unsigned long long int. Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits. There was no long long in C89, but apparently even MSVC supports it, so it's quite portable.

In the current C++ standard (issued in 2003), there is no long long, though many compilers support it as an extension. The upcoming C++0x standard will support it and its size will be the same as in C, so at least 64 bits.

You can get the exact size, in bytes (8 bits on typical platforms) with the expression sizeof(unsigned long long). If you want exactly 64 bits, use uint64_t, which is defined in the header <stdint.h> along with a bunch of related types (available in C99, C++11 and some current C++ compilers).

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

Function not defined javascript

There are a couple of things to check:

  • In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
  • You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
  • One thing you may try is removing the space around the @type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">

How do I concatenate two strings in Java?

you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).

How do I get the APK of an installed app without root access?

List PackageManager.getInstalledApplications() will give you a list of the installed applications, and ApplicationInfo.sourceDir is the path to the .apk file.

// in oncreate
   PackageManager pm = getPackageManager(); 
   for (ApplicationInfo app : pm.getInstalledApplications(0)) {
 Log.d("PackageList", "package: " + app.packageName + ", sourceDir: " + app.sourceDir);
 }

//output is something like
D/PackageList(5010): package: com.example.xmlparse, sourceDir: /data/app   /com.example.xmlparse-2.apk
D/PackageList(5010): package: com.examples.android.calendar, sourceDir: /data/app/com.examples.android.calendar-2.apk
D/PackageList(5010): package: com.facebook.katana, sourceDir: /data/app/com.facebook.katana-1.apk
D/PackageList(5010): package: com.facebook.samples.profilepicture, sourceDir: /data/app/com.facebook.samples.profilepicture-1.apk
D/PackageList(5010): package: com.facebook.samples.sessionlogin, sourceDir: /data/app/com.facebook.samples.sessionlogin-1.apk
D/PackageList(5010): package: com.fitworld, sourceDir: /data/app/com.fitworld-2.apk
D/PackageList(5010): package: com.flipkart.android, sourceDir: /data/app/com.flipkart.android-1.apk
D/PackageList(5010): package: com.fmm.dm, sourceDir: /system/app/FmmDM.apk
D/PackageList(5010): package: com.fmm.ds, sourceDir: /system/app/FmmDS.apk

Angular Material: mat-select not selecting default

As already mentioned in Angular 6 using ngModel in reactive forms is deprecated (and removed in Angular 7), so I modified the template and the component as following.

The template:

<mat-form-field>
    <mat-select [formControl]="filter" multiple 
                [compareWith]="compareFn">
        <mat-option *ngFor="let v of values" [value]="v">{{v.label}}</mat-option>
    </mat-select>
</mat-form-field>

The main parts of the component (onChanges and other details are omitted):

interface SelectItem {
    label: string;
    value: any;
}

export class FilterComponent implements OnInit {
    filter = new FormControl();

    @Input
    selected: SelectItem[] = [];

    @Input()
    values: SelectItem[] = [];

    constructor() { }

    ngOnInit() {
        this.filter.setValue(this.selected);
    }

    compareFn(v1: SelectItem, v2: SelectItem): boolean {
        return compareFn(v1, v2);
    }
}

function compareFn(v1: SelectItem, v2: SelectItem): boolean {
    return v1 && v2 ? v1.value === v2.value : v1 === v2;
}

Note this.filter.setValue(this.selected) in ngOnInit above.

It seems to work in Angular 6.

How to only get file name with Linux 'find'?

Use -execdir which automatically holds the current file in {}, for example:

find . -type f -execdir echo '{}' ';'

You can also use $PWD instead of . (on some systems it won't produce an extra dot in the front).

If you still got an extra dot, alternatively you can run:

find . -type f -execdir basename '{}' ';'

-execdir utility [argument ...] ;

The -execdir primary is identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file.

When used + instead of ;, then {} is replaced with as many pathnames as possible for each invocation of utility. In other words, it'll print all filenames in one line.

Where does application data file actually stored on android device?

This is a simple way to identify the application related storage paths of a particular app.

Steps:

  1. Have the android device connected to your mac or android emulator open
  2. Open the terminal
  3. adb shell
  4. find .

The "find ." command will list all the files with their paths in the terminal.

./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....

After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.

Can I prevent text in a div block from overflowing?

It's now the css property:

word-break: break-all

Viewing localhost website from mobile device

Try this https://ngrok.com/docs#expose

Just run ngrok 3000 , 3000 is the port number you want to expose to the internet. You can insert the port number which you want to expose, for rails its 3000. This will tunnel your localhost to the internet and you will be able to view your local host from anywhere

How to kill/stop a long SQL query immediately?

If you cancel and see that run

 sp_who2 'active'

(Activity Monitor won't be available on old sql server 2000 FYI )

Spot the SPID you wish to kill e.g. 81

Kill 81

Run the sp_who2 'active' again and you will probably notice it is sleeping ... rolling back

To get the STATUS run again the KILL

Kill 81 

Then you will get a message like this

 SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.

What is best way to start and stop hadoop ecosystem, with command line?

From Hadoop page,

start-all.sh 

This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.

start-dfs.sh

This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh to separately start the job tracker

start-all.sh/stop-all.sh has to be run on the master node

You would use start-all.sh on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).

In multi-node setup,

You will use start-all.sh on the master node and would start what is necessary on the slaves as well.

Alternatively,

Use start-dfs.sh on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.

Use start-mapred.sh on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.

hadoop-daemon.sh as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.

Have a look at this start-all.sh it call config followed by dfs and mapred

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.

If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.

Using GregorianCalendar with SimpleDateFormat

A SimpleDateFormat, as its name indicates, formats Dates. Not a Calendar. So, if you want to format a GregorianCalendar using a SimpleDateFormat, you must convert the Calendar to a Date first:

dateFormat.format(calendar.getTime());

And what you see printed is the toString() representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple)DateFormat.

Finally, to convert from a String to a Date, you should also use a (Simple)DateFormat (its parse() method), rather than splitting the String as you're doing. This will give you a Date object, and you can create a Calendar from the Date by instanciating it (Calendar.getInstance()) and setting its time (calendar.setTime()).

My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.

How to print a single backslash?

A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

>>> print(chr(92))
\

Is there a color code for transparent in HTML?

Yeah I think the best way to transparent the background colour (make opacity only for the background) is using

.style{
        background-color: rgba(100, 100, 100, 0.5);
}

Above statement 0.5 is the opacity value.

It only apply the opacity changes to the background colour (not all elements')

The "opacity" attribute in the CSS will transparent all the elements in the block.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

How can I perform static code analysis in PHP?

There a new tool called nWire for PHP. It is a code exploration plugin for Eclipse PDT and Zend Studio 7.x. It enables real-time code analysis for PHP and provides the following tools:

  • Code visualization - interactive graphical representation of components and associations.
  • Code navigation - unique navigation view shows all the associations and works with you while you write or read code.
  • Quick search - search as you type for methods, fields, file, etc.

What equivalents are there to TortoiseSVN, on Mac OSX?

My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.

Subversion client releases for Windows and Macintosh

Wiki - Subversion clients comparison table

Select Multiple Fields from List in Linq

You can make it a KeyValuePair, so it will return a "IEnumerable<KeyValuePair<string, string>>"

So, it will be like this:

.Select(i => new KeyValuePair<string, string>(i.category_id, i.category_name )).Distinct();

How to get CRON to call in the correct PATHs

Setting PATH right before the command line in my crontab worked for me:

* * * * * PATH=$PATH:/usr/local/bin:/path/to/some/thing

swift 3.0 Data to String?

let urlString = baseURL + currency

    if let url = URL(string: urlString){
        let session = URLSession(configuration: .default)        
        let task = session.dataTask(with: url){ (data, reponse, error) in
            if error != nil{
                print(error)
                return
            }


            let dataString = String(data: data!, encoding: .utf8)
            print(dataString)

        }

        task.resume()

    }

How to get all elements which name starts with some string?

A quick and easy way is to use jQuery and do this:

var $eles = $(":input[name^='q1_']").css("color","yellow");

That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:

var DOMeles = $eles.get();

see http://api.jquery.com/attribute-starts-with-selector/

In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:

var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].name.indexOf('q1_') == 0) {
        eles.push(inputs[i]);
    }
}

How to scroll to top of a div using jQuery?

This is my solution to scroll to the top on a button click.

$(".btn").click(function () {
if ($(this).text() == "Show options") {
$(".tabs").animate(
  {
    scrollTop: $(window).scrollTop(0)
  },
  "slow"
 );
 }
});

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Lowercase and Uppercase with jQuery

Try this:

var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();

Possible duplicate with: How do I use jQuery to ignore case when selecting

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

Android: How to rotate a bitmap on a center point

I hope the following sequence of code will help you:

Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, config);
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(source, matrix, new Paint());

If you check the following method from ~frameworks\base\graphics\java\android\graphics\Bitmap.java

public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
        Matrix m, boolean filter)

this would explain what it does with rotation and translate.

tsconfig.json: Build:No inputs were found in config file

I got the same error and in my case it was because vscode couldn't recognize .ts file.

It was seeing it as text file and I had to rename it to remove one letter and add it back to make it work.

How to trigger checkbox click event even if it's checked through Javascript code?

Trigger function from jQuery could be your answer.

jQuery docs says: Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user

Thus best one line solution should be:

$('.selector_class').trigger('click');

//or

$('#foo').click();

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

javascript createElement(), style problem

I found this page when I was trying to set the backgroundImage attribute of a div, but hadn't wrapped the backgroundImage value with url(). This worked fine:

for (var i=0; i<20; i++) {
  // add a wrapper around an image element
  var wrapper = document.createElement('div');
  wrapper.className = 'image-cell';

  // add the image element
  var img = document.createElement('div');
  img.className = 'image';
  img.style.backgroundImage = 'url(http://via.placeholder.com/350x150)';

  // add the image to its container; add both to the body
  wrapper.appendChild(img);
  document.body.appendChild(wrapper);
}

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

String strip() for JavaScript?

Here's the function I use.

function trim(s){ 
  return ( s || '' ).replace( /^\s+|\s+$/g, '' ); 
}

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

AJAX Mailchimp signup form integration

As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.

You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.

All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.

This simply works. Thanks MailChimp!

Rename specific column(s) in pandas

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

The rename show that it accepts a dict as a param for columns so you just pass a dict with a single entry.

Also see related

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

datetime dtypes in pandas read_csv

You might try passing actual types instead of strings.

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

But it's going to be really hard to diagnose this without any of your data to tinker with.

And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:

pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)

'\r': command not found - .bashrc / .bash_profile

folks who use notepad++(6.8.1) to ship shell scripts from windows to linux.

set the following in notepad ++ Edit -> EOL Conversion -> Unix/OSX format

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Then NumPy sum function takes an optional axis argument that specifies along which axis you would like the sum performed:

>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])

Or, equivalently:

>>> numpy.sum(a, 0)
array([18, 22, 26])

Converting Java objects to JSON with Jackson

Just follow any of these:

  • For jackson it should work:

          ObjectMapper mapper = new ObjectMapper();  
          return mapper.writeValueAsString(object);
          //will return json in string
    
  • For gson it should work:

        Gson gson = new Gson();
        return Response.ok(gson.toJson(yourClass)).build();
    

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

How to get the version of ionic framework?

ionic info

This will give you the ionic version,node, npm and os.

If you need only ionic version use ionic -v.

If your project's development ionic version and your global versions are different then check them by using the below commands.

To check the globally installed ionic version ionic -g and to check the project's ionic version use ionic -g.

To check the project's ionic version use ionic -v in your project path or else ionic info to get the details of ionic and its dependencies.

Python JSON dump / append to .txt with each variable on new line

Your question is a little unclear. If you're generating hostDict in a loop:

with open('data.txt', 'a') as outfile:
    for hostDict in ....:
        json.dump(hostDict, outfile)
        outfile.write('\n')

If you mean you want each variable within hostDict to be on a new line:

with open('data.txt', 'a') as outfile:
    json.dump(hostDict, outfile, indent=2)

When the indent keyword argument is set it automatically adds newlines.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

I'm not sure if this would work, but you could try creating a UINavigationController with the default settings to create the button, find the button in the navigation controller's subview hierarchy, call removeFromSuperview on it, destroy the navigation controller, and then add the button as a subview of your toolbar. You may also need to retain and the button before calling removeFromSuperview (and then release it after adding it as subview of your toolbar) to avoid it being deallocated during the process.

lvalue required as left operand of assignment error when using C++

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

You cannot use:

10 = 20;

since 10 does not evaluate to an lvalue.

You can use:

int i;
i = 20;

since i does evaluate to an lvalue.

You cannot use:

int i;
i + 1 = 20;

since i + 1 does not evaluate to an lvalue.

In your case, p + 1 does not evaluate to an lavalue. Hence, you cannot use

p + 1 = p;

Combining two Series into a DataFrame in pandas

If I may answer this.

The fundamentals behind converting series to data frame is to understand that

1. At conceptual level, every column in data frame is a series.

2. And, every column name is a key name that maps to a series.

If you keep above two concepts in mind, you can think of many ways to convert series to data frame. One easy solution will be like this:

Create two series here

import pandas as pd

series_1 = pd.Series(list(range(10)))

series_2 = pd.Series(list(range(20,30)))

Create an empty data frame with just desired column names

df = pd.DataFrame(columns = ['Column_name#1', 'Column_name#1'])

Put series value inside data frame using mapping concept

df['Column_name#1'] = series_1

df['Column_name#2'] = series_2

Check results now

df.head(5)

Download file of any type in Asp.Net MVC using FileResult?

GetFile should be closing the file (or opening it within a using). Then you can delete the file after conversion to bytes-- the download will be done on that byte buffer.

    byte[] GetFile(string s)
    {
        byte[] data;
        using (System.IO.FileStream fs = System.IO.File.OpenRead(s))
        {
            data = new byte[fs.Length];
            int br = fs.Read(data, 0, data.Length);
            if (br != fs.Length)
                throw new System.IO.IOException(s);
        }
        return data;
    }

So in your download method...

        byte[] fileBytes = GetFile(file);
        // delete the file after conversion to bytes
        System.IO.File.Delete(file);
        // have the file download dialog only display the base name of the file            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(file));

PHP: Get key from array?


$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

How to add colored border on cardview?

my solution:

create a file card_view_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white_background"/>
<stroke android:width="2dp" 
    android:color="@color/red" />
<corners android:radius="20dip"/>
</shape>

and set programmatically

cardView.setBackgroundResource(R.drawable.card_view_border);

Unable to compile simple Java 10 / Java 11 project with Maven

Specify maven.compiler.source and target versions.

1) Maven version which supports jdk you use. In my case JDK 11 and maven 3.6.0.

2) pom.xml

<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>

As an alternative, you can fully specify maven compiler plugin. See previous answers. It is shorter in my example :)

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>
    </plugins>
</build>

3) rebuild the project to avoid compile errors in your IDE.

4) If it still does not work. In Intellij Idea I prefer using terminal instead of using terminal from OS. Then in Idea go to file -> settings -> build tools -> maven. I work with maven I downloaded from apache (by default Idea uses bundled maven). Restart Idea then and run mvn clean install again. Also make sure you have correct Path, MAVEN_HOME, JAVA_HOME environment variables.

I also saw this one-liner, but it does not work.

<maven.compiler.release>11</maven.compiler.release>

I made some quick starter projects, which I re-use in other my projects, feel free to check:

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

How can I change the size of a Bootstrap checkbox?

<div id="rr-element">
   <label for="rr-1">
      <input type="checkbox" value="1" id="rr-1" name="rr[]">
      Value 1
   </label>
</div>
//do this on the css
div label input { margin-right:100px; }

Zip folder in C#

"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"

You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.

Finally you'll need to add it as a using statement in whatever files you want to use it in.

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

How to convert a string Date to long millseconds

Easiest way is used the Date Using Date() and getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

pandas read_csv and filter columns with usecols

If your csv file contains extra data, columns can be deleted from the DataFrame after import.

import pandas as pd
from StringIO import StringIO

csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""

df = pd.read_csv(StringIO(csv),
        index_col=["date", "loc"], 
        usecols=["dummy", "date", "loc", "x"],
        parse_dates=["date"],
        header=0,
        names=["dummy", "date", "loc", "x"])
del df['dummy']

Which gives us:

                x
date       loc
2009-01-01 a    1
2009-01-02 a    3
2009-01-03 a    5
2009-01-01 b    1
2009-01-02 b    3
2009-01-03 b    5

How do I find which process is leaking memory?

I suggest the use of htop, as a better alternative to top.

MVC 4 Razor File Upload

View Page

@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
 { 
   <input type="file" name="file" />
   <input type="submit" value="Upload" class="save" id="btnid" />
 }

script file

$(document).on("click", "#btnid", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: "json"
        }
        $("#formid").ajaxSubmit(fileOptions);
    });

In Controller

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }

Enable the display of line numbers in Visual Studio

Are you talking about seeing the line numbers or knowing the total number of lines in a project? Here is the 1st one

Jquery- Get the value of first td in table

This should work:

$(".hit").click(function(){    
   var value=$(this).closest('tr').children('td:first').text();
   alert(value);    
});

Explanation:

  • .closest('tr') gets the nearest ancestor that is a <tr> element (so in this case the row where the <a> element is in).
  • .children('td:first') gets all the children of this element, but with the :first selector we reduce it to the first <td> element.
  • .text() gets the text inside the element

As you can see from the other answers, there is more than only one way to do this.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You are returning an Observable where as your code returns just a boolean. So you need to use as below

.map(response => <boolean>response.json())

If you are using another common service checkservice in your case, you can simply use

this.service.getData().subscribe(data=>console.log(data));

This will make your checkLogin() function with return type as void

 checkLogin():void{
      this.service.getData()
            .map(response => {  
                           this.data = response;                            
                           this.checkservice=true;
             }).subscribe(data=>{ });

and you can use of this.checkService to check your condition

Error in contrasts when defining a linear model in R

It appears that at least one of your predictors ,x1, x2, or x3, has only one factor level and hence is a constant.

Have a look at

lapply(dataframe.df[c("x1", "x2", "x3")], unique)

to find the different values.

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

Javascript: Fetch DELETE and PUT requests

For put method we have:

const putMethod = {
 method: 'PUT', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 body: JSON.stringify(someData) // We send data in JSON format
}

// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

Example for someData, we can have some input fields or whatever you need:

const someData = {
 title: document.querySelector(TitleInput).value,
 body: document.querySelector(BodyInput).value
}

And in our data base will have this in json format:

{
 "posts": [
   "id": 1,
   "title": "Some Title", // what we typed in the title input field
   "body": "Some Body", // what we typed in the body input field
 ]
}

For delete method we have:

const deleteMethod = {
 method: 'DELETE', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 // No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod) 
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

In the url we need to type the id of the of deletion: https://www.someapi/id

What is the difference between a URI, a URL and a URN?

First of all get your mind out of confusion and take it simple and you will understand.

URI => Uniform Resource Identifier Identifies a complete address of resource i-e location, name or both.

URL => Uniform Resource Locator Identifies location of the resource.

URN => Uniform Resource Name Identifies the name of the resource

Example

We have address https://www.google.com/folder/page.html where,

URI(Uniform Resource Identifier) => https://www.google.com/folder/page.html

URL(Uniform Resource Locator) => https://www.google.com/

URN(Uniform Resource Name) => /folder/page.html

URI => (URL + URN) or URL only or URN only

How to add buttons dynamically to my form?

First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick:

  for (int i = 0; i < 10; ++i)
  {
      var button = new Button();
      button.Location = new Point(button.Width * i + 4, 0);
      Controls.Add(button);
  }

Retrieving the first digit of a number

Integer.parseInt will take a string and return a int.

Removing u in list

You don't "remove the character 'u' from a list", you encode Unicode strings. In fact the strings you have are perfectly fine for most uses; you will just need to encode them appropriately before outputting them.

Ruby replace string with captured regex pattern

$ variables are only set to matches into the block:

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { "#{ $1.strip }" }

This is also the only way to call a method on the match. This will not change the match, only strip "\1" (leaving it unchanged):

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1".strip)

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

Let JSON object accept bytes or let urlopen output strings

This will stream the byte data into json.

import io

obj = json.load(io.TextIOWrapper(response))

io.TextIOWrapper is preferred to the codec's module reader. https://www.python.org/dev/peps/pep-0400/

Stick button to right side of div

<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
    <div style="clear:both;"></div>
</div>

css

div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-right:10px;

}

Remove all elements contained in another array

I just implemented as:

Array.prototype.exclude = function(list){
        return this.filter(function(el){return list.indexOf(el)<0;})
}

Use as:

myArray.exclude(toRemove);

Django, creating a custom 500/404 error page

Try moving your error templates to .../Django/mysite/templates/ ?

I'm note sure about this one, but i think these need to be "global" to the website.

How to have click event ONLY fire on parent DIV, not children?

There's another way that works if you don't mind only targeting newer browsers. Just add the CSS

pointer-events: none;

to any children of the div you want to capture the click. Here's the support tables

http://caniuse.com/#feat=pointer-events

How could I create a list in c++?

If you are going to use std::list, you need to pass a type parameter:

list<int> intList;  
list<int>* intListPtr = new list<int>;

If you want to know how lists work, I recommending googling for some C/C++ tutorials to gain an understanding of that subject. Next step would then be learning enough C++ to create a list class, and finally a list template class.

If you have more questions, ask back here.

What does [object Object] mean?

As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?

That is because there are different types of objects in Javascript!

  • Function objects:
    stringify(function (){}) -> [object Function]
  • Array objects:
    stringify([]) -> [object Array]
  • RegExp objects
    stringify(/x/) -> [object RegExp]
  • Date objects
    stringify(new Date) -> [object Date]
  • several more
  • and Object objects!
    stringify({}) -> [object Object]

That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.

Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.

where stringify should look like this:

function stringify (x) {
    console.log(Object.prototype.toString.call(x));
}

Converting time stamps in excel to dates

If your file is really big try to use following formula: =A1 / 86400 + 25569

A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.

Get the size of the screen, current web page and browser window

This has everything you need to know: Get viewport/window size

but in short:

var win = window,
    doc = document,
    docElem = doc.documentElement,
    body = doc.getElementsByTagName('body')[0],
    x = win.innerWidth || docElem.clientWidth || body.clientWidth,
    y = win.innerHeight|| docElem.clientHeight|| body.clientHeight;
alert(x + ' × ' + y);

Fiddle

Please stop editing this answer. It's been edited 22 times now by different people to match their code format preference. It's also been pointed out that this isn't required if you only want to target modern browsers - if so you only need the following:

const width  = window.innerWidth || document.documentElement.clientWidth || 
document.body.clientWidth;
const height = window.innerHeight|| document.documentElement.clientHeight|| 
document.body.clientHeight;

console.log(width, height);

How do I find the install time and date of Windows?

You can simply check the creation date of Windows Folder (right click on it and check properties) :)

SQL Server: how to create a stored procedure

To Create SQL server Store procedure in SQL server management studio

  • Expand your database
  • Expand programmatically
  • Right-click on Stored-procedure and Select "new Stored Procedure"

Now, Write your Store procedure, for example, it can be something like below

USE DatabaseName;  
GO  
CREATE PROCEDURE ProcedureName 
 @LastName nvarchar(50),   
 @FirstName nvarchar(50)   
AS   

SET NOCOUNT ON;  
 
//Your SQL query here, like
Select  FirstName, LastName, Department  
FROM HumanResources.vEmployeeDepartmentHistory  
WHERE FirstName = @FirstName AND LastName = @LastName  
GO  

Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (@LastName and @FirstName) and type = parameter type example nvarchar(50) etc.

Source: Stored procedure in sql server (With Example)

To Execute the above stored procedure you can use sample query as below

EXECUTE ProcedureName @FirstName = N'Pilar', @LastName = N'Ackerman';  

Find an element in a list of tuples

if you want to search tuple for any number which is present in tuple then you can use

a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)

print(result)

You can also use if i==j[0] or i==j[index] if you want to search a number in particular index

Find the number of employees in each department - SQL Oracle

Try to do this:

SQL> select dept,count(*) "no of emp" from employee group by dept;

DEPT                  no of emp
-------------------- ----------
HR                            2
Account                       2
Admin                         3

How do I tell Python to convert integers into words

This does the job without any library. Used recursion and it is Indian style. -- Ravi.

def spellNumber(no):
    # str(no) will result in  56.9 for 56.90 so we used the method which is given below.
    strNo = "%.2f" %no
    n = strNo.split(".")
    rs = numberToText(int(n[0])).strip()
    ps =""
    if(len(n)>=2):
        ps = numberToText(int(n[1])).strip()
        rs = "" + ps+ " paise"  if(rs.strip()=="") else  (rs + " and " + ps+ " paise").strip()
    return rs
print(spellNumber(0.67))
print(spellNumber(5858.099))
print(spellNumber(5083754857380.50))    

def numberToText(no):
    ones = " ,one,two,three,four,five,six,seven,eight,nine,ten,eleven,tweleve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty".split(',')
    tens = "ten,twenty,thirty,fourty,fifty,sixty,seventy,eighty,ninety".split(',')
    text = ""
    if len(str(no))<=2:
        if(no<20):
            text = ones[no]
        else:
            text = tens[no//10-1] +" " + ones[(no %10)]
    elif len(str(no))==3:
        text = ones[no//100] +" hundred " + numberToText(no- ((no//100)* 100))
    elif len(str(no))<=5:
        text = numberToText(no//1000) +" thousand " + numberToText(no- ((no//1000)* 1000))
    elif len(str(no))<=7:
        text = numberToText(no//100000) +" lakh " + numberToText(no- ((no//100000)* 100000))
    else:
        text = numberToText(no//10000000) +" crores " + numberToText(no- ((no//10000000)* 10000000))
    return text

Why does configure say no C compiler found when GCC is installed?

I had the same issue with mind. I tried using sudo apt-get install build-essential It still won't work. I simply created a hardlink to the gcc-x binary in the /usr/bin/ folder. sudo ls /usr/bin/gcc-x /usr/bin/gcc

That worked for me!

Upload failed You need to use a different version code for your APK because you already have one with version code 2

In Android Studio 1.1.0, change versionCode in build.gradle for Module: app and don't necessarily change versionName:

android {
...
    defaultConfig {
...
        versionCode 3
        versionName "1.0"
    }
...
}

PHP - Failed to open stream : No such file or directory

  1. Look at the exact error

My code worked fine on all machines but only on this one started giving problem (which used to work find I guess). Used echo "document_root" path to debug and also looked closely at the error, found this

Warning: include(D:/MyProjects/testproject//functions/connections.php): failed to open stream:

You can easily see where the problems are. The problems are // before functions

$document_root = $_SERVER['DOCUMENT_ROOT'];
echo "root: $document_root";
include($document_root.'/functions/connections.php');

So simply remove the lading / from include and it should work fine. What is interesting is this behaviors is different on different versions. I run the same code on Laptop, Macbook Pro and this PC, all worked fine untill. Hope this helps someone.

  1. Copy past the file location in the browser to make sure file exists. Sometimes files get deleted unexpectedly (happened with me) and it was also the issue in my case.

How to write JUnit test with Spring Autowire?

Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

Also this looks wierd to me :

@ContextConfiguration("classpath*:conf/components.xml")

Here is an example that works fine for me :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {

    @Autowired
    OwnerService ownerService;

    @Before
    public void setup() {

        ownerService.cleanList();

    }

    @Test
    public void testOwners() {

        Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
        owner = ownerService.createOwner(owner);
        assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
        assertTrue("Check that Id exist: ", owner.getId() > 0);

        owner.setLastName("Larsson");
        ownerService.updateOwner(owner);
        owner = ownerService.getOwner(owner.getId());
        assertEquals("Name is changed", "Larsson", owner.getLastName());

    }

Difference between webdriver.Dispose(), .Close() and .Quit()

My understanding is driver.close(); will close the current browser, and driver.quit(); will terminate all the browser that.

How to get certain commit from GitHub project

First, clone the repository using git, e.g. with:

git clone git://github.com/facebook/facebook-ios-sdk.git

That downloads the complete history of the repository, so you can switch to any version. Next, change into the newly cloned repository:

cd facebook-ios-sdk

... and use git checkout <COMMIT> to change to the right commit:

git checkout 91f25642453

That will give you a warning, since you're no longer on a branch, and have switched directly to a particular version. (This is known as "detached HEAD" state.) Since it sounds as if you only want to use this SDK, rather than actively develop it, this isn't something you need to worry about, unless you're interested in finding out more about how git works.

Nth word in a string variable

STRING=(one two three four)
echo "${STRING[n]}"

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

This makes me wonder, when is it advisable to use the EntityManager.getReference() method instead of the EntityManager.find() method?

EntityManager.getReference() is really an error prone method and there is really very few cases where a client code needs to use it.
Personally, I never needed to use it.

EntityManager.getReference() and EntityManager.find() : no difference in terms of overhead

I disagree with the accepted answer and particularly :

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

It is not the behavior that I get with Hibernate 5 and the javadoc of getReference() doesn't say such a thing :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

EntityManager.getReference() spares a query to retrieve the entity in two cases :

1) if the entity is stored in the Persistence context, that is the first level cache.
And this behavior is not specific to EntityManager.getReference(), EntityManager.find() will also spare a query to retrieve the entity if the entity is stored in the Persistence context.

You can check the first point with any example.
You can also rely on the actual Hibernate implementation.
Indeed, EntityManager.getReference() relies on the createProxyIfNecessary() method of the org.hibernate.event.internal.DefaultLoadEventListener class to load the entity.
Here is its implementation :

private Object createProxyIfNecessary(
        final LoadEvent event,
        final EntityPersister persister,
        final EntityKey keyToLoad,
        final LoadEventListener.LoadType options,
        final PersistenceContext persistenceContext) {
    Object existing = persistenceContext.getEntity( keyToLoad );
    if ( existing != null ) {
        // return existing object or initialized proxy (unless deleted)
        if ( traceEnabled ) {
            LOG.trace( "Entity found in session cache" );
        }
        if ( options.isCheckDeleted() ) {
            EntityEntry entry = persistenceContext.getEntry( existing );
            Status status = entry.getStatus();
            if ( status == Status.DELETED || status == Status.GONE ) {
                return null;
            }
        }
        return existing;
    }
    if ( traceEnabled ) {
        LOG.trace( "Creating new proxy for entity" );
    }
    // return new uninitialized proxy
    Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
    persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey( keyToLoad );
    persistenceContext.addProxy( keyToLoad, proxy );
    return proxy;
}

The interesting part is :

Object existing = persistenceContext.getEntity( keyToLoad );

2) If we don't effectively manipulate the entity, echoing to the lazily fetched of the javadoc.
Indeed, to ensure the effective loading of the entity, invoking a method on it is required.
So the gain would be related to a scenario where we want to load a entity without having the need to use it ? In the frame of applications, this need is really uncommon and in addition the getReference() behavior is also very misleading if you read the next part.

Why favor EntityManager.find() over EntityManager.getReference()

In terms of overhead, getReference() is not better than find() as discussed in the previous point.
So why use the one or the other ?

Invoking getReference() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.
It means that if we invoke getReference() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable. For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.

It means that the throw of EntityNotFoundException that is the main reason to use getReference() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

EntityManager.find() doesn't have the ambition of throwing EntityNotFoundException if the entity is not found. Its behavior is both simple and clear. You will never have surprise as it returns always a loaded entity or null (if the entity is not found) but never an entity under the shape of a proxy that may not be effectively loaded.
So EntityManager.find() should be favored in the very most of cases.

How do I use method overloading in Python?

Python 3.x includes standard typing library which allows for method overloading with the use of @overload decorator. Unfortunately, this is to make the code more readable, as the @overload decorated methods will need to be followed by a non-decorated method that handles different arguments. More can be found here here but for your example:

from typing import overload
from typing import Any, Optional
class A(object):
    @overload
    def stackoverflow(self) -> None:    
        print('first method')
    @overload
    def stackoverflow(self, i: Any) -> None:
        print('second method', i)
    def stackoverflow(self, i: Optional[Any] = None) -> None:
        if not i:
            print('first method')
        else:
            print('second method', i)

ob=A()
ob.stackoverflow(2)

PHP 7: Missing VCRUNTIME140.dll

Installing vc_redist.x86.exe works for me even though you have a 64-bit machine.

What is the maximum length of a valid email address?

320

And the segments look like this

{64}@{255}

64 + 1 + 255 = 320

You should also read this if you are validating emails

http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

How to execute a shell script in PHP?

Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.

I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.

I would recommend moving the shell script to outside of the webroot

    <?php
      $tempFolder = '/tmp';
      $webRootFolder = '/var/www';
      $scriptName = 'myscript.sh';
      $moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
      $output = shell_exec($moveCommand);
    ?>

In regards to the:

i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works

You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.

Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.

ie:

sudo su apache (or www-data)
cd /var/www
sh ./myscript

Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file

... voila

Playing sound notifications using Javascript?

I wrote a small function that can do it, with the Web Audio API...

var beep = function(duration, type, finishedCallback) {

    if (!(window.audioContext || window.webkitAudioContext)) {
        throw Error("Your browser does not support Audio Context.");
    }

    duration = +duration;

    // Only 0-4 are valid types.
    type = (type % 5) || 0;

    if (typeof finishedCallback != "function") {
        finishedCallback = function() {};   
    }

    var ctx = new (window.audioContext || window.webkitAudioContext);
    var osc = ctx.createOscillator();

    osc.type = type;

    osc.connect(ctx.destination);
    osc.noteOn(0);

    setTimeout(function() {
        osc.noteOff(0);
        finishedCallback();
    }, duration);

};

How do I do top 1 in Oracle?

select * from (
    select FName from MyTbl
)
where rownum <= 1;

Horizontal ListView in Android?

For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:

<HorizontalScrollView 
        android:id="@+id/photo_scroll"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:scrollbars="horizontal"
        android:visibility="gone">

        <LinearLayout 
            android:id="@+id/imageview_holder"
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:layout_height="match_parent">

        </LinearLayout>
    </HorizontalScrollView>

An this works perfectly fine for me. In the activity all I have to do is something like the code below:

LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2); 

As I said that works for me, and I hope it helps somebody looking to achieve this as well.

Stop Excel from automatically converting certain text values to dates

CSV - comma separated values. Just create/edit through text editor instead of xls/xlsx/exel. In editing you can set date in required format and it must be kept intact. This is assuming same file is then getting processed programatically.

Why doesn't height: 100% work to expand divs to the screen height?

Alternatively, if you use position: absolute then height: 100% will work just fine.

mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

jQuery.post( ) .done( ) and success:

From the doc:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

The point it is just an alternative for success callback option, and jqXHR.success() is deprecated.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Another reason why an undefined index notice will be thrown, would be that a column was omitted from a database query.

I.e.:

$query = "SELECT col1 FROM table WHERE col_x = ?";

Then trying to access more columns/rows inside a loop.

I.e.:

print_r($row['col1']);
print_r($row['col2']); // undefined index thrown

or in a while loop:

while( $row = fetching_function($query) ) {

    echo $row['col1'];
    echo "<br>";
    echo $row['col2']; // undefined index thrown
    echo "<br>";
    echo $row['col3']; // undefined index thrown

}

Something else that needs to be noted is that on a *NIX OS and Mac OS X, things are case-sensitive.

Consult the followning Q&A's on Stack:

How to capitalize the first letter in a String in Ruby

You can use mb_chars. This respects umlaute:

class String

  # Only capitalize first letter of a string
  def capitalize_first
    self[0] = self[0].mb_chars.upcase
    self
  end

end

Example:

"ümlaute".capitalize_first
#=> "Ümlaute"

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

No restricted globals

Use react-router-dom library.

From there, import useLocation hook if you're using functional components:

import { useLocation } from 'react-router-dom';

Then append it to a variable:

Const location = useLocation();

You can then use it normally:

location.pathname

P.S: the returned location object has five properties only:

{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

Function or sub to add new row and data to table

I needed this same solution, but if you use the native ListObject.Add() method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design tab of the ribbon, in Excel 2013 at least: enter image description here

Example code for a table with three columns:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

How to install SQL Server Management Studio 2008 component only

For any of you still having problems as of Sept. 2012, go here: http://support.microsoft.com/kb/2527041 ...and grab the SQLManagementStudio_x(32|64)_ENU.exe (if you've already installed SQL Server 2008 Express R2), or SQL Server 2008 Express R2 with Tools, i.e. SQLEXPRWT_x64_ENU.exe or SQLEXPRWT_x32_ENU.exe (if you haven't).

From there, follow similar instructions as above (i.e. use the "Perform new installation and add shared features" selection, as "Management Tools - Basic" is considered a "shared feature"), if you've already installed SQL Server Express 2008 R2 (as I had). And if you haven't done that yet, then of course you're going to follow this way as you need to install the new instance anyway.

This solved things for me, and hopefully it will for you, too!

load external URL into modal jquery ui dialog

Modals always load the content into an element on the page, which more often than not is a div. Think of this div as the iframe equivalent when it comes to jQuery UI Dialogs. Now it depends on your requirements whether you want static content that resides within the page or you want to fetch the content from some other location. You may use this code and see if it works for you:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.23.custom.css"/>

</head>

<body>

    <p>First open a modal <a href="http://ibm.com" class="example"> dialog</a></p>
    <div id="dialog"></div>
</body>

<!--jQuery-->
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script src="js/jquery-ui-1.8.23.custom.min.js"></script>

<script type="text/javascript">

$(function(){
//modal window start
$(".example").unbind('click');
$(".example").bind('click',function(){
    showDialog();
    var titletext=$(this).attr("title");
    var openpage=$(this).attr("href");
    $("#dialog").dialog( "option", "title", titletext );
    $("#dialog").dialog( "option", "resizable", false );
    $("#dialog").dialog( "option", "buttons", { 
        "Close": function() { 
            $(this).dialog("close");
            $(this).dialog("destroy");
        } 
    });
    $("#dialog").load(openpage);
    return false;
});

//modal window end

//Modal Window Initiation start

function showDialog(){
    $("#dialog").dialog({
        height: 400,
        width: 500,
        modal: true 
    }
</script>

</html>

There are, however, a few things which you should keep in mind. You will not be able to load remote URL's on your local system, you need to upload to a server if you want to load remote URL. Even then, you may only load URL's which belong to the same domain; e.g. if you upload this file to 'www.example.com' you may only access files hosted on 'www.example.com'. For loading external links this might help. All this information you will find in the link as suggested by @Robin.

How to hide elements without having them take space on the page?

Thanks to this question. I wanted the exact opposite, i.e a hidden div should still occupy its space on the browser. So, I used visibility: hidden instead of display: none.

Efficient way to insert a number into a sorted array of numbers?

Just as a single data point, for kicks I tested this out inserting 1000 random elements into an array of 100,000 pre-sorted numbers using the two methods using Chrome on Windows 7:

First Method:
~54 milliseconds
Second Method:
~57 seconds

So, at least on this setup, the native method doesn't make up for it. This is true even for small data sets, inserting 100 elements into an array of 1000:

First Method:
1 milliseconds
Second Method:
34 milliseconds

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

Why is it not advisable to have the database and web server on the same machine?

On the other hand, referring to a different blogging Scott (Watermasyck, of Telligent) - they found that most users could speed up the websites (using Telligent's Community Server), by putting the database on the same machine as the web site. However, in their customer's case, usually the db & web server are the only applications on that machine, and the website isn't straining the machine that much. Then, the efficiency of not having to send data across the network more that made up for the increased strain.

Check if option is selected with jQuery, if not select a default

I already came across the texotela plugin mentioned, which let me solve it like this:

$(document).ready(function(){
    if ( $("#context").selectedValues() == false) {
    $("#context").selectOptions("71");
    }
});

GetFiles with multiple extensions

You can use LINQ Union method:

dir.GetFiles("*.txt").Union(dir.GetFiles("*.jpg")).ToArray();

max value of integer

In C range for __int32 is –2147483648 to 2147483647. See here for full ranges.

unsigned short 0 to 65535
signed short –32768 to 32767
unsigned long 0 to 4294967295
signed long –2147483648 to 2147483647

There are no guarantees that an 'int' will be 32 bits, if you want to use variables of a specific size, particularly when writing code that involves bit manipulations, you should use the 'Standard Integer Types'.

In Java

The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

Maven 3 warnings about build.plugins.plugin.version

Add a <version> element after the <plugin> <artifactId> in your pom.xml file. Find the following text:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

Add the version tag to it:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>

The warning should be resolved.

Regarding this:

'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version> tag as shown above.

To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---

Take that version number (as in the 2.3.2 above) and add it to your POM, as shown.

How to initialize struct?

  1. Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.

  2. To get the syntax you asked for, you can implement an "implicit" operator like so:

    static implicit operator MyStruct(string s) {
        return new MyStruct(...);
    }
    
  3. The implicit operator will work, regardless of whether you make your struct mutable or not.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

Check if value is in select list with JQuery

_x000D_
_x000D_
if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){_x000D_
//do stuff_x000D_
}
_x000D_
_x000D_
_x000D_

Unknown Column In Where Clause

May be it helps.

You can

SET @somevar := '';
SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john";

It works.

BUT MAKE SURE WHAT YOU DO!

  • Indexes are NOT USED here
  • There will be scanned FULL TABLE - you hasn't specified the LIMIT 1 part
  • So, - THIS QUERY WILL BE SLLLOOOOOOW on huge tables.

But, may be it helps in some cases

How does a PreparedStatement avoid or prevent SQL injection?

I guess it will be a string. But the input parameters will be sent to the database & appropriate cast/conversions will be applied prior to creating an actual SQL statement.

To give you an example, it might try and see if the CAST/Conversion works.
If it works, it could create a final statement out of it.

   SELECT * From MyTable WHERE param = CAST('10; DROP TABLE Other' AS varchar(30))

Try an example with a SQL statement accepting a numeric parameter.
Now, try passing a string variable (with numeric content that is acceptable as numeric parameter). Does it raise any error?

Now, try passing a string variable (with content that is not acceptable as numeric parameter). See what happens?

How to convert date format to DD-MM-YYYY in C#

From C# 6.0 onwards (Visual Studio 2015 and newer), you can simply use an interpolated string with formatting:

var date = new DateTime(2017, 8, 3);
var formattedDate = $"{date:dd-MM-yyyy}";

MySQL's now() +1 day

INSERT INTO `table` ( `data` , `date` ) VALUES('".$data."',NOW()+INTERVAL 1 DAY);

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

When to choose mouseover() and hover() function?

.hover() function accepts two function arguments, one for mouseenter event and one for mouseleave event.

Stripping non printable characters from a string in python

This function uses list comprehensions and str.join, so it runs in linear time instead of O(n^2):

from curses.ascii import isprint

def printable(input):
    return ''.join(char for char in input if isprint(char))

Git fatal: protocol 'https' is not supported

Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

Concatenating date with a string in Excel

Don't know if it's the best way but I'd do this:

=A1 & TEXT(A2,"mm/dd/yyyy")

That should format your date into your desired string.

Edit: That funny number you saw is the number of days between December 31st 1899 and your date. That's how Excel stores dates.

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Spring Boot - Handle to Hibernate SessionFactory

You can accomplish this with:

SessionFactory sessionFactory = 
    entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

package net.andreaskluth.hibernatesample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SomeService {

  private SessionFactory hibernateFactory;

  @Autowired
  public SomeService(EntityManagerFactory factory) {
    if(factory.unwrap(SessionFactory.class) == null){
      throw new NullPointerException("factory is not a hibernate factory");
    }
    this.hibernateFactory = factory.unwrap(SessionFactory.class);
  }

}

Java URLConnection Timeout

I have used similar code for downloading logs from servers. I debug my code and discovered that implementation of URLConnection which is returned is sun.net.www.protocol.http.HttpURLConnection.

Abstract class java.net.URLConnection have two attributes connectTimeout and readTimeout and setters are in abstract class. Believe or not implementation sun.net.www.protocol.http.HttpURLConnection have same attributes connectTimeout and readTimeout without setters and attributes from implementation class are used in getInputStream method. So there is no use of setting connectTimeout and readTimeout because they are never used in getInputStream method. In my opinion this is bug in sun.net.www.protocol.http.HttpURLConnection implementation.

My solution for this was to use HttpClient and Get request.

Disable button in WPF?

By code:

btn_edit.IsEnabled = true;

By XAML:

<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />

Checking if float is an integer

This deals with computational round-off. You set the epsilon as desired:

bool IsInteger(float value)
{
    return fabs(ceilf(value) - value) < EPSILON;
}