Programs & Examples On #.net

The .NET framework is a software framework designed mainly for the Microsoft Windows operating system. It includes an implementation of the Base Class Library, Common Language Runtime (commonly referred to as CLR), Common Type System (commonly referred to as CTS) and Dynamic Language Runtime. It supports many programming languages, including C#, VB.NET, F# and C++/CLI. Do NOT use for questions about .NET Core.

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));

Shortest way to check for null and assign another value if not

I use extention method SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Then use like

string a = null;
"A".SC(ref a);

Differences between Microsoft .NET 4.0 full Framework and Client Profile

You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.

Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Try this

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@id", con);
cmd.Parameters.AddWithValue("id", id.Text);

Populating a ComboBox using C#

Simple way is:

Dictionary<string, string> dict = new Dictionary<string, string>()
{
    {"English ","En" },
    {"Italian  ","It" },
    {"Spainish  ","Sp " }
};

combo.DataSource = new BindingSource(dict, null);
combo.DisplayMember = "Key";
combo.ValueMember = "Value";

Bring a window to the front in WPF

To show ANY currently opened window import those DLL:

public partial class Form1 : Form
{
    [DllImportAttribute("User32.dll")]
    private static extern int FindWindow(String ClassName, String WindowName);
    [DllImportAttribute("User32.dll")]
    private static extern int SetForegroundWindow(int hWnd);

and in program We search for app with specified title (write title without first letter (index > 0))

  foreach (Process proc in Process.GetProcesses())
                {
                    tx = proc.MainWindowTitle.ToString();
                    if (tx.IndexOf("Title of Your app WITHOUT FIRST LETTER") > 0)
                    {
                        tx = proc.MainWindowTitle;
                        hWnd = proc.Handle.ToInt32(); break;
                    }
                }
                hWnd = FindWindow(null, tx);
                if (hWnd > 0)
                {
                    SetForegroundWindow(hWnd);
                }

Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

Authentication failed because remote party has closed the transport stream

I ran into the same error message while using the ChargifyNET.dll to communicate with the Chargify API. Adding chargify.ProtocolType = SecurityProtocolType.Tls12; to the configuration solved the problem for me.

Here is the complete code snippet:

public ChargifyConnect GetChargifyConnect()
{
    var chargify = new ChargifyConnect();
    chargify.apiKey = ConfigurationManager.AppSettings["Chargify.apiKey"];
    chargify.Password = ConfigurationManager.AppSettings["Chargify.apiPassword"];
    chargify.URL = ConfigurationManager.AppSettings["Chargify.url"];

    // Without this an error will be thrown.
    chargify.ProtocolType = SecurityProtocolType.Tls12;

    return chargify;
}

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

We had a very similar issue whereby a client's website was trying to connect to our Web API service and getting that same message. This started happening completely out of the blue when there had been no code changes or Windows updates on the server where IIS was running.

In our case it turned out that the calling website was using a version of .Net that only supported TLS 1.0 and for some reason the server where our IIS was running stopped appeared to have stopped accepting TLS 1.0 calls. To diagnose that we had to explicitly enable TLS via the registry on the IIS's server and then restart that server. These are the reg keys:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:


    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

My answer to another question here has this powershell script that we used to add the entries:

NOTE: Enabling old security protocols is not a good idea, the right answer in our case was to get the client website to update it's code to use TLS 1.2, but the registry entries above can help diagnose the issue in the first place.

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);
        }
    }

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

Wait until a process ends

I had a case where Process.HasExited didn't change after closing the window belonging to the process. So Process.WaitForExit() also didn't work. I had to monitor Process.Responding that went to false after closing the window like that:

while (!_process.HasExited && _process.Responding) {
  Thread.Sleep(100);
}
...

Perhaps this helps someone.

Difference between web reference and service reference?

Another point to take in consideration is that the new UI for Service Interface will give you much more flexibility on how you want to create your proxy class. For example, it will allow you to map data contracts to existing dlls, if they match (actually this is the default behaviour).

How can I create a temp file with a specific extension with .NET?

Try this function ...

public static string GetTempFilePathWithExtension(string extension) {
  var path = Path.GetTempPath();
  var fileName = Guid.NewGuid().ToString() + extension;
  return Path.Combine(path, fileName);
}

It will return a full path with the extension of your choice.

Note, it's not guaranteed to produce a unique file name since someone else could have technically already created that file. However the chances of someone guessing the next guid produced by your app and creating it is very very low. It's pretty safe to assume this will be unique.

powershell - extract file name and extension

just do it:

$file=Get-Item "C:\temp\file.htm"
$file.Basename 
$file.Extension

How to catch SQLServer timeout exceptions

When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15

In C#, how to check if a TCP port is available?

If I'm not very much mistaken, you can use System.Network.whatever to check.

However, this will always incur a race condition.

The canonical way of checking is try to listen on that port. If you get an error that port wasn't open.

I think this is part of why bind() and listen() are two separate system calls.

Create normal zip file programmatically

Here are a few resources you might consider: Creating Zip archives in .NET (without an external library like SharpZipLib)

Zip Your Streams with System.IO.Packaging

My recommendation and preference would be to use system.io.packacking. This keeps your dependencies down (just the framework). Jgalloway’s post (the first reference) provides a good example of adding two files to a zip file. Yes, it is more verbose, but you can easily create a façade (to a degree his AddFileToZip does that).

HTH

How can I add a hint text to WPF textbox?

Another solution is to use a WPF toolkit like MahApps.Metro. It has many nice features, like a text box watermark:

Controls:TextBoxHelper.Watermark="Search..."

See http://mahapps.com/controls/textbox.html

How can I ignore a property when serializing using the DataContractSerializer?

In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.

This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

It could be hardware. It could be something complicated...but I'd take a stab at suggesting that somewhere your threading code is not protecting some collection (such as a dictionary) with an appropriate lock.

What OS and service pack are you running?

Convert String (UTF-16) to UTF-8 in C#

If you want a UTF8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the followed:

public static string Utf16ToUtf8(string utf16String)
{
   /**************************************************************
    * Every .NET string will store text with the UTF16 encoding, *
    * known as Encoding.Unicode. Other encodings may exist as    *
    * Byte-Array or incorrectly stored with the UTF16 encoding.  *
    *                                                            *
    * UTF8 = 1 bytes per char                                    *
    *    ["100" for the ansi 'd']                                *
    *    ["206" and "186" for the russian '?']                   *
    *                                                            *
    * UTF16 = 2 bytes per char                                   *
    *    ["100, 0" for the ansi 'd']                             *
    *    ["186, 3" for the russian '?']                          *
    *                                                            *
    * UTF8 inside UTF16                                          *
    *    ["100, 0" for the ansi 'd']                             *
    *    ["206, 0" and "186, 0" for the russian '?']             *
    *                                                            *
    * We can use the convert encoding function to convert an     *
    * UTF16 Byte-Array to an UTF8 Byte-Array. When we use UTF8   *
    * encoding to string method now, we will get a UTF16 string. *
    *                                                            *
    * So we imitate UTF16 by filling the second byte of a char   *
    * with a 0 byte (binary 0) while creating the string.        *
    **************************************************************/

    // Storage for the UTF8 string
    string utf8String = String.Empty;

    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Fill UTF8 bytes inside UTF8 string
    for (int i = 0; i < utf8Bytes.Length; i++)
    {
        // Because char always saves 2 bytes, fill char with 0
        byte[] utf8Container = new byte[2] { utf8Bytes[i], 0 };
        utf8String += BitConverter.ToChar(utf8Container, 0);
    }

    // Return UTF8
    return utf8String;
}

In my case the DLL request is a UTF8 string too, but unfortunately the UTF8 string must be interpreted with UTF16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 has to be converted to the UTF16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf16ToUtf8(string utf16String)
{
    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Return UTF8 bytes as ANSI string
    return Encoding.Default.GetString(utf8Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 WideCharToMultiByte(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPWStr)] String lpWideCharStr, Int32 cchWideChar, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpMultiByteStr, Int32 cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);

public static string Utf16ToUtf8(string utf16String)
{
    Int32 iNewDataLen = WideCharToMultiByte(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf16String, utf16String.Length, null, 0, IntPtr.Zero, IntPtr.Zero);
    if (iNewDataLen > 1)
    {
        StringBuilder utf8String = new StringBuilder(iNewDataLen);
        WideCharToMultiByte(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf16String, -1, utf8String, utf8String.Capacity, IntPtr.Zero, IntPtr.Zero);

        return utf8String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf8ToUtf16. Hope I could be of help.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

My problem was that I had the wrong MS Sync FrameWork version (1.0) in my project References. After update to the version 2.1, the error was gone and life is good again.

Use of Finalize/Dispose method in C#

Pattern from msdn

public class BaseResource: IDisposable
{
   private IntPtr handle;
   private Component Components;
   private bool disposed = false;
   public BaseResource()
   {
   }
   public void Dispose()
   {
      Dispose(true);      
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing)
   {
      if(!this.disposed)
      {        
         if(disposing)
         {
            Components.Dispose();
         }         
         CloseHandle(handle);
         handle = IntPtr.Zero;
       }
      disposed = true;         
   }
   ~BaseResource()      
   {      Dispose(false);
   }
   public void DoSomething()
   {
      if(this.disposed)
      {
         throw new ObjectDisposedException();
      }
   }
}
public class MyResourceWrapper: BaseResource
{
   private ManagedResource addedManaged;
   private NativeResource addedNative;
   private bool disposed = false;
   public MyResourceWrapper()
   {
   }
   protected override void Dispose(bool disposing)
   {
      if(!this.disposed)
      {
         try
         {
            if(disposing)
            {             
               addedManaged.Dispose();         
            }
            CloseHandle(addedNative);
            this.disposed = true;
         }
         finally
         {
            base.Dispose(disposing);
         }
      }
   }
}

How to create/make rounded corner buttons in WPF?

Well the best way to get round corners fast and with standard animation is to create a copy of the control template with Blend. Once you get a copy set the corner radius on the Grid tag and you should be able to have your control with full animation functionality and applyable to any button control. look this is the code:

<ControlTemplate x:Key="ButtonControlTemplate" TargetType="Button">        
    <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"
          CornerRadius="8,8,8,8">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <Storyboard>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="PointerOver">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerDownThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Disabled">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <!--<Border CornerRadius="8,8,8,8"
                        Background="#002060"
                        BorderBrush="Red"
                        BorderThickness="2">-->
            <ContentPresenter x:Name="ContentPresenter"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}"
                              Content="{TemplateBinding Content}"
                              ContentTransitions="{TemplateBinding ContentTransitions}"
                              ContentTemplate="{TemplateBinding ContentTemplate}"
                              Padding="{TemplateBinding Padding}"
                              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                              AutomationProperties.AccessibilityView="Raw"/>
        <!--</Border>-->
    </Grid>        
</ControlTemplate>

I also edited the VisualState="PointerOver" specifically at Storyboard.TargetName="BorderBrush", because its ThemeResource get squared corners whenever PointerOver triggers.

Then you should be able to apply it to your control style like this:

<Style TargetType="ContentControl" x:Key="ButtonLoginStyle"
       BasedOn="{StaticResource CommonLoginStyleMobile}">
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Background" Value="#002060"/>
    <Setter Property="Template" Value="{StaticResource ButtonControlTemplate}"/>        
</Style>

So you can apply your styles to any Button.

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

Interesting, I didn't have any references to stdole in my project, but I had a user still receiving the error. I had to add the reference, then change the setting to include. Hopefully that will work.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

The answer in my view is related to whether you have a tangible problem to solve or if you just want to learn for example to be prepared for a possible new job. If you have a problem then you are in better shape. You can start by looking around and seeing how other people went about solving that problem. Languages in general you should be able to pick up fairly quickly (after all you hold an MS in EE, no small feat IMO).

What you need to be on the lookout for is good programming practices. You'll probably see yourself asking "why is this method so small", "why is this method empty and what the heck is this abstract word doing here". That will give you perspective beyond syntax towards good writing.

How do you UrlEncode without using System.Web?

System.Net.WebUtility.HtmlDecode

Binding an enum to a WinForms combo box, and then setting it

public Form1()
{
    InitializeComponent();
    comboBox.DataSource = EnumWithName<SearchType>.ParseEnum();
    comboBox.DisplayMember = "Name";
}

public class EnumWithName<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public static EnumWithName<T>[] ParseEnum()
    {
        List<EnumWithName<T>> list = new List<EnumWithName<T>>();

        foreach (object o in Enum.GetValues(typeof(T)))
        {
            list.Add(new EnumWithName<T>
            {
                Name = Enum.GetName(typeof(T), o).Replace('_', ' '),
                Value = (T)o
            });
        }

        return list.ToArray();
    }
}

public enum SearchType
{
    Value_1,
    Value_2
}

Difference between the System.Array.CopyTo() and System.Array.Clone()

Array.Clone() would perform technically deep copy, when pass the array of int or string to a method as a reference.

For example

int[] numbers = new int[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 }; 

SortByAscending(numbers); // Sort the array in ascending order by clone the numbers array to local new array.
SortByDescending(numbers); // Same as Ascending order Clone

Even if the methods sort the array of numbers but it wont affect the actual reference passed to the sorting methods.i.e the number array will be in same unsorted initial format in line no 1.

Note: The Clone should be done in the sorting methods.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

How to set null value to int in c#?

 public static int? Timesaday { get; set; } = null;

OR

 public static Nullable<int> Timesaday { get; set; }

or

 public static int? Timesaday = null;

or

 public static int? Timesaday

or just

 public static int? Timesaday { get; set; } 


    static void Main(string[] args)
    {


    Console.WriteLine(Timesaday == null);

     //you also can check using 
     Console.WriteLine(Timesaday.HasValue);

        Console.ReadKey();
    }

The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null https://en.wikipedia.org/wiki/Null

How to set radio button selected value using jquery

  <asp:RadioButtonList ID="rblRequestType">
        <asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
        <asp:ListItem Value="Value2">Value2</asp:ListItem>
  </asp:RadioButtonList>

You can set checked like this.

var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");

radio0.checked = true;
radio1.checked = true;

get the titles of all open windows

you should use the EnumWindow API.

there are plenty of examples on how to use it from C#, I found something here:

Get Application's Window Handles

Issue with EnumWindows

How to create a simple proxy in C#?

Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.

If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.

If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.

How do I group Windows Form radio buttons?

Look at placing your radio buttons in a GroupBox.

What is the difference between String and string in C#?

There is no difference between the two. You can use either of them in your code.

System.String is a class (reference type) defined the mscorlib in the namespace System. In other words, System.String is a type in the CLR.

string is a keyword in C#

How to bind list to dataGridView?

I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.

public class FileName
{        
     public string ThisFieldWorks {get;set;}
     public string ThisFieldDoesNot;
}

How to SELECT a dropdown list item by value programmatically

Please try below:

myDropDown.SelectedIndex = 
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))

Update all objects in a collection using LINQ

Although you specifically asked for a LINQ solution and this question is quite old I post a non-LINQ-solution. This is because LINQ (= language integrated query) is meant to be used for queries on collections. All LINQ-methods don’t modify the underlying collection, they just return a new one (or more precise an iterator to a new collection). Thus whatever you do e.g. with a Select doesn’t effect the underlying collection, you simply get a new one.

Of course you could do it with a ForEach (which isn't LINQ, by the way, but an extension on List<T>). But this literally uses foreach anyway, but with a lambda-expression. Apart from this every LINQ method internally iterates your collection e.g. by using foreach or for, however it simply hides it from the client. I don’t consider this any more readable nor maintainable (think of edit your code while debugging a method containing lambda-expressions).

Having said this shouldn't use LINQ to modify items in your collection. A better way is the solution you already provided in your question. With a classic loop you can easily iterate your collection and update its items. In fact all those solutions relying on List.ForEach are nothing different, but far harder to read from my perspective.

So you shouldn't use LINQ in those cases where you want to update the elements of your collection.

Getting the first and last day of a month, using a given DateTime object

I used this in my script(works for me) but I needed a full date without the need of trimming it to only the date and no time.

public DateTime GetLastDayOfTheMonth()
{
    int daysFromNow = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) - (int)DateTime.Now.Day;
    return DateTime.Now.AddDays(daysFromNow);
}

Most useful NLog configurations

Logging different levels depending on whether or not there is an error

This example allows you to get more information when there is an error in your code. Basically, it buffers messages and only outputs those at a certain log level (e.g. Warn) unless a certain condition is met (e.g. there has been an error, so the log level is >= Error), then it will output more info (e.g. all messages from log levels >= Trace). Because the messages are buffered, this lets you gather trace information about what happened before an Error or ErrorException was logged - very useful!

I adapted this one from an example in the source code. I was thrown at first because I left out the AspNetBufferingWrapper (since mine isn't an ASP app) - it turns out that the PostFilteringWrapper requires some buffered target. Note that the target-ref element used in the above-linked example cannot be used in NLog 1.0 (I am using 1.0 Refresh for a .NET 4.0 app); it is necessary to put your target inside the wrapper block. Also note that the logic syntax (i.e. greater-than or less-than symbols, < and >) has to use the symbols, not the XML escapes for those symbols (i.e. &gt; and &lt;) or else NLog will error.

app.config:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
    </configSections>

    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">
        <variable name="appTitle" value="My app"/>
        <variable name="csvPath" value="${specialfolder:folder=Desktop:file=${appTitle} log.csv}"/>

        <targets async="true">
            <!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
            <wrapper-target xsi:type="BufferingWrapper" name="smartLog">
                <wrapper-target xsi:type="PostFilteringWrapper">
                    <!--<target-ref name="fileAsCsv"/>-->
                    <target xsi:type="File" fileName="${csvPath}"
                    archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence"
                    >
                        <layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
                            <column name="time" layout="${longdate}" />
                            <column name="level" layout="${level:upperCase=true}"/>
                            <column name="message" layout="${message}" />
                            <column name="callsite" layout="${callsite:includeSourcePath=true}" />
                            <column name="stacktrace" layout="${stacktrace:topFrames=10}" />
                            <column name="exception" layout="${exception:format=ToString}"/>
                            <!--<column name="logger" layout="${logger}"/>-->
                        </layout>
                    </target>

                     <!--during normal execution only log certain messages--> 
                    <defaultFilter>level >= LogLevel.Warn</defaultFilter>

                     <!--if there is at least one error, log everything from trace level--> 
                    <when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
                </wrapper-target>
            </wrapper-target>

        </targets>

        <rules>
            <logger name="*" minlevel="Trace" writeTo="smartLog"/>
        </rules>
    </nlog>
</configuration>

Get url parameters from a string in .NET

Use .NET Reflector to view the FillFromString method of System.Web.HttpValueCollection. That gives you the code that ASP.NET is using to fill the Request.QueryString collection.

Using async/await for multiple tasks

I was curious to see the results of the methods provided in the question as well as the accepted answer, so I put it to the test.

Here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        class Worker
        {
            public int Id;
            public int SleepTimeout;

            public async Task DoWork(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart-testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd-workerStart).TotalSeconds.ToString("F2"), (workerEnd-testStart).TotalSeconds.ToString("F2"));
            }
        }

        static void Main(string[] args)
        {
            var workers = new List<Worker>
            {
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },
            };

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            task.Wait();
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            Console.ReadKey();
        }

        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
        {
            Parallel.ForEach(workers, worker => worker.DoWork(testStart).Wait());
        }

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
        {
            Task.WaitAll(workers.Select(worker => worker.DoWork(testStart)).ToArray());
        }

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
        {
            return Task.WhenAll(workers.Select(worker => worker.DoWork(testStart)));
        }
    }
}

And the resulting output:

Starting test: Parallel.ForEach...
Worker 1 started on thread 1, beginning 0.21 seconds after test start.
Worker 4 started on thread 5, beginning 0.21 seconds after test start.
Worker 2 started on thread 3, beginning 0.21 seconds after test start.
Worker 5 started on thread 6, beginning 0.21 seconds after test start.
Worker 3 started on thread 4, beginning 0.21 seconds after test start.
Worker 1 stopped; the worker took 1.90 seconds, and it finished 2.11 seconds after the test start.
Worker 2 stopped; the worker took 3.89 seconds, and it finished 4.10 seconds after the test start.
Worker 3 stopped; the worker took 5.89 seconds, and it finished 6.10 seconds after the test start.
Worker 4 stopped; the worker took 5.90 seconds, and it finished 6.11 seconds after the test start.
Worker 5 stopped; the worker took 8.89 seconds, and it finished 9.10 seconds after the test start.
Test finished after 9.10 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 1, beginning 0.01 seconds after test start.
Worker 2 started on thread 1, beginning 0.01 seconds after test start.
Worker 3 started on thread 1, beginning 0.01 seconds after test start.
Worker 4 started on thread 1, beginning 0.01 seconds after test start.
Worker 5 started on thread 1, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 1, beginning 0.00 seconds after test start.
Worker 2 started on thread 1, beginning 0.00 seconds after test start.
Worker 3 started on thread 1, beginning 0.00 seconds after test start.
Worker 4 started on thread 1, beginning 0.00 seconds after test start.
Worker 5 started on thread 1, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.00 seconds after the test start.
Test finished after 5.00 seconds.

How to write Unicode characters to the console?

Console.OutputEncoding Property

https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding

Note that successfully displaying Unicode characters to the console requires the following:

  • The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.

How to set only time part of a DateTime variable in C#

It isn't possible as DateTime is immutable. The same discussion is available here: How to change time in datetime?

Looping through dictionary object

public class TestModels
{
    public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();

    public TestModels()
    {
        sp.Add(0, new {name="Test One", age=5});
        sp.Add(1, new {name="Test Two", age=7});
    }
}

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

Convert Enum to String

For VB aficionados:

EnumStringValue = System.Enum.GetName(GetType(MyEnum), MyEnumValue)

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Restart IIS- could be a process attached to the debugger

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

How to initialize a List<T> to a given size (as opposed to capacity)?

If you want to initialize the list with N elements of some fixed value:

public List<T> InitList<T>(int count, T initValue)
{
  return Enumerable.Repeat(initValue, count).ToList();
}

WCF service startup error "This collection already contains an address with scheme http"

And in my case it was simple: I used 'Add WCF Service' wizard in Visual Studio, which automatically created corresponding sections in app.config. Then I went on reading How to: Host a WCF Service in a Managed Application. The problem was: I didn't need to specify the url to run the web service.

Replace:

using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))

With:

using (ServiceHost host = new ServiceHost(typeof(HelloWorldService))

And the error is gone.

Generic idea: if you provide base address as a param and specify it in config, you get this error. Most probably, that's not the only way to get the error, thou.

Multiple Where clauses in Lambda expressions

You can include it in the same where statement with the && operator...

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
    && l.InternalName != String.Empty)

You can use any of the comparison operators (think of it like doing an if statement) such as...

List<Int32> nums = new List<int>();

nums.Add(3);
nums.Add(10);
nums.Add(5);

var results = nums.Where(x => x == 3 || x == 10);

...would bring back 3 and 10.

.NET Global exception handler in console application

No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

How can I wrap text in a label using WPF?

The Label control doesn't directly support text wrapping in WPF. You should use a TextBlock instead. (Of course, you can place the TextBlock inside of a Label control, if you wish.)

Sample code:

<TextBlock TextWrapping="WrapWithOverflow">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing
    nulla quis libero egestas lobortis. Duis blandit imperdiet ornare. Nulla
    ac arcu ut purus placerat congue. Integer pretium fermentum gravida.
</TextBlock>

C# adding a character in a string

Inserting Space in emailId field after every 8 characters

public string BreakEmailId(string emailId) {
    string returnVal = string.Empty;
    if (emailId.Length > 8) {           
        for (int i = 0; i < emailId.Length; i += 8) {
            returnVal += emailId.Substring(i, 8) + " ";
        }
    }

    return returnVal;
}

Get the value for a listbox item by index

simply try this 'listBox' is your list and 'yu' is a veriable to which the value on index 0 will be assigned

string yu = listBox1.Items[0].ToString();
MessageBox.Show(yu);

What .NET collection provides the fastest search

If you don't need ordering, try HashSet<Record> (new to .Net 3.5)

If you do, use a List<Record> and call BinarySearch.

Regular expression to extract numbers from a string

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+

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

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

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

... this will avoid the "select new"

Why does visual studio 2012 not find my tests?

From menu bar on top...

Test -> Run -> All Tests

You may also view all tests from Test Explorer (Test -> Windows -> Test Explorer)

Further with VS 2012, if you miss out anything try searching it using Quick Launch bar on top right (Ctrl + Q) "Test"

Hope this helps.

Convert String to SecureString

Here is a cheap linq trick.

            SecureString sec = new SecureString();
            string pwd = "abc123"; /* Not Secure! */
            pwd.ToCharArray().ToList().ForEach(sec.AppendChar);
            /* and now : seal the deal */
            sec.MakeReadOnly();

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

What does "exited with code 9009" mean during this build?

Check the spelling. I was trying to call an executable but had the name misspelled and it gave me the exited with code 9009 message.

Finding element in XDocument?

My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).

In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d457c3b-292c-49e1-9fd4-9b6a950f9010/how-to-get-tag-name-of-xml-by-using-xdocument?forum=csharpgeneral

In short, you can create a GetElement function:

private XElement GetElement(XDocument doc,string elementName)
{
    foreach (XNode node in doc.DescendantNodes())
    {
        if (node is XElement)
        {
            XElement element = (XElement)node;
            if (element.Name.LocalName.Equals(elementName))
                return element;
        }
    }
    return null;
}

Which you can then call like this:

XElement element = GetElement(doc,"Band");

Note that this will return null if no matching element is found.

Enum "Inheritance"

The short answer is no. You can play a bit, if you want:

You can always do something like this:

private enum Base
{
    A,
    B,
    C
}

private enum Consume
{
    A = Base.A,
    B = Base.B,
    C = Base.C,
    D,
    E
}

But, it doesn't work all that great because Base.A != Consume.A

You can always do something like this, though:

public static class Extensions
{
    public static T As<T>(this Consume c) where T : struct
    {
        return (T)System.Enum.Parse(typeof(T), c.ToString(), false);
    }
}

In order to cross between Base and Consume...

You could also cast the values of the enums as ints, and compare them as ints instead of enum, but that kind of sucks too.

The extension method return should type cast it type T.

Cannot find Dumpbin.exe

You probably need to open a command prompt with the PATH set up properly. Look for an icon in the start menu that says something like "Visual C++ 2005 Command Prompt". You should be able to run dumpbin (and all the other command line tools) from there.

Performance of Arrays vs. Lists

In some brief tests I have found a combination of the two to be better in what I would call reasonably intensive Math:

Type: List<double[]>

Time: 00:00:05.1861300

Type: List<List<double>>

Time: 00:00:05.7941351

Type: double[rows * columns]

Time: 00:00:06.0547118

Running the Code:

int rows = 10000;
int columns = 10000;

IMatrix Matrix = new IMatrix(rows, columns);

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();


for (int r = 0; r < Matrix.Rows; r++)
    for (int c = 0; c < Matrix.Columns; c++)
        Matrix[r, c] = Math.E;

for (int r = 0; r < Matrix.Rows; r++)
    for (int c = 0; c < Matrix.Columns; c++)
        Matrix[r, c] *= -Math.Log(Math.E);


stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;

Console.WriteLine(ts.ToString());

I do wish we had some top notch Hardware Accelerated Matrix Classes like the .NET Team have done with the System.Numerics.Vectors Class!

C# could be the best ML Language with a bit more work in this area!

When should I use Lazy<T>?

You should try to avoid using Singletons, but if you ever do need to, Lazy<T> makes implementing lazy, thread-safe singletons easy:

public sealed class Singleton
{
    // Because Singleton's constructor is private, we must explicitly
    // give the Lazy<Singleton> a delegate for creating the Singleton.
    static readonly Lazy<Singleton> instanceHolder =
        new Lazy<Singleton>(() => new Singleton());

    Singleton()
    {
        // Explicit private constructor to prevent default public constructor.
        ...
    }

    public static Singleton Instance => instanceHolder.Value;
}

How can I close a login form and show the main form without my application closing?

This is my solution. Create ApplicationContext to set mainform of application and change mainform when you want to open new form and close current form.

Program.cs

static class Program
{
    static ApplicationContext MainContext = new ApplicationContext();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        MainContext.MainForm = new Authenticate();
        Application.Run(MainContext);
    }

    public static void SetMainForm(Form MainForm)
    {
        MainContext.MainForm = MainForm;
    }

    public static void ShowMainForm()
    {
        MainContext.MainForm.Show();
    }
}

When login process is complete.

private void BtLogin_Click(object sender, EventArgs e)
    {
        //Login Process Here.

        Program.SetMainForm(new Portal());
        Program.ShowMainForm();

        this.Close();
    }

I hope this will help you.

HashSet vs. List performance

A lot of people are saying that once you get to the size where speed is actually a concern that HashSet<T> will always beat List<T>, but that depends on what you are doing.

Let's say you have a List<T> that will only ever have on average 5 items in it. Over a large number of cycles, if a single item is added or removed each cycle, you may well be better off using a List<T>.

I did a test for this on my machine, and, well, it has to be very very small to get an advantage from List<T>. For a list of short strings, the advantage went away after size 5, for objects after size 20.

1 item LIST strs time: 617ms
1 item HASHSET strs time: 1332ms

2 item LIST strs time: 781ms
2 item HASHSET strs time: 1354ms

3 item LIST strs time: 950ms
3 item HASHSET strs time: 1405ms

4 item LIST strs time: 1126ms
4 item HASHSET strs time: 1441ms

5 item LIST strs time: 1370ms
5 item HASHSET strs time: 1452ms

6 item LIST strs time: 1481ms
6 item HASHSET strs time: 1418ms

7 item LIST strs time: 1581ms
7 item HASHSET strs time: 1464ms

8 item LIST strs time: 1726ms
8 item HASHSET strs time: 1398ms

9 item LIST strs time: 1901ms
9 item HASHSET strs time: 1433ms

1 item LIST objs time: 614ms
1 item HASHSET objs time: 1993ms

4 item LIST objs time: 837ms
4 item HASHSET objs time: 1914ms

7 item LIST objs time: 1070ms
7 item HASHSET objs time: 1900ms

10 item LIST objs time: 1267ms
10 item HASHSET objs time: 1904ms

13 item LIST objs time: 1494ms
13 item HASHSET objs time: 1893ms

16 item LIST objs time: 1695ms
16 item HASHSET objs time: 1879ms

19 item LIST objs time: 1902ms
19 item HASHSET objs time: 1950ms

22 item LIST objs time: 2136ms
22 item HASHSET objs time: 1893ms

25 item LIST objs time: 2357ms
25 item HASHSET objs time: 1826ms

28 item LIST objs time: 2555ms
28 item HASHSET objs time: 1865ms

31 item LIST objs time: 2755ms
31 item HASHSET objs time: 1963ms

34 item LIST objs time: 3025ms
34 item HASHSET objs time: 1874ms

37 item LIST objs time: 3195ms
37 item HASHSET objs time: 1958ms

40 item LIST objs time: 3401ms
40 item HASHSET objs time: 1855ms

43 item LIST objs time: 3618ms
43 item HASHSET objs time: 1869ms

46 item LIST objs time: 3883ms
46 item HASHSET objs time: 2046ms

49 item LIST objs time: 4218ms
49 item HASHSET objs time: 1873ms

Here is that data displayed as a graph:

enter image description here

Here's the code:

static void Main(string[] args)
{
    int times = 10000000;


    for (int listSize = 1; listSize < 10; listSize++)
    {
        List<string> list = new List<string>();
        HashSet<string> hashset = new HashSet<string>();

        for (int i = 0; i < listSize; i++)
        {
            list.Add("string" + i.ToString());
            hashset.Add("string" + i.ToString());
        }

        Stopwatch timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            list.Remove("string0");
            list.Add("string0");
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item LIST strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");


        timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            hashset.Remove("string0");
            hashset.Add("string0");
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item HASHSET strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
        Console.WriteLine();
    }


    for (int listSize = 1; listSize < 50; listSize+=3)
    {
        List<object> list = new List<object>();
        HashSet<object> hashset = new HashSet<object>();

        for (int i = 0; i < listSize; i++)
        {
            list.Add(new object());
            hashset.Add(new object());
        }

        object objToAddRem = list[0];

        Stopwatch timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            list.Remove(objToAddRem);
            list.Add(objToAddRem);
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item LIST objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");



        timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            hashset.Remove(objToAddRem);
            hashset.Add(objToAddRem);
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item HASHSET objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
        Console.WriteLine();
    }

    Console.ReadLine();
}

What is the fastest way to create a checksum for large files in C#

You're doing something wrong (probably too small read buffer). On a machine of undecent age (Athlon 2x1800MP from 2002) that has DMA on disk probably out of whack (6.6M/s is damn slow when doing sequential reads):

Create a 1G file with "random" data:

# dd if=/dev/sdb of=temp.dat bs=1M count=1024    
1073741824 bytes (1.1 GB) copied, 161.698 s, 6.6 MB/s

# time sha1sum -b temp.dat
abb88a0081f5db999d0701de2117d2cb21d192a2 *temp.dat

1m5.299s

# time md5sum -b temp.dat
9995e1c1a704f9c1eb6ca11e7ecb7276 *temp.dat

1m58.832s

This is also weird, md5 is consistently slower than sha1 for me (reran several times).

Loop through all the resources in a .resx file

You should always use the resource manager and not read files directly to ensure globalization is taken into account.

using System.Collections;
using System.Globalization;
using System.Resources;

...

/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
    new ResourceManager(typeof(Resources));

ResourceSet resourceSet =
    MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
    string resourceKey = entry.Key.ToString();
    object resource = entry.Value;
}

How to make an HTTP POST web request

MSDN has a sample.

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}

Could not load file or assembly '***.dll' or one of its dependencies

This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...

In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.

(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

Read XML Attribute using XmlDocument

You can migrate to XDocument instead of XmlDocument and then use Linq if you prefer that syntax. Something like:

var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Specifically if you want to clear your text box in VB.NET or VB 6.0, write this code:

TextBox1.Items.Clear()

If you are using VBA, then the use this code :

TextBox1.Text = "" or TextBox1.Clear()

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

Make sure the required dlls are exported (or copied manually) to the bin folder when building your application.

Easiest way to compare arrays in C#

For some applications may be better:

string.Join(",", arr1) == string.Join(",", arr2)

NHibernate.MappingException: No persister for: XYZ

Don't forget to specify mapping information in .config file

e.g.

where MyApp.Data is assembly that contains your mappings

Connect to network drive with user name and password

You can use WebClient class to connect to the network driver using credentials. Include the below namespace:

using System.Net;

WebClient request = new WebClient();
request.Credentials = new NetworkCredential("domain\username", "password");
string[] theFolders = Directory.GetDirectories(@"\\computer\share");

best way to create object

Decide if you need an immutable object or not.

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

In that case, having a Person(string name, int age) constructor is not so useful.

The second option is to implement an immutable type. For example:

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

How to pass a variable to the SelectCommand of a SqlDataSource?

Try this instead, remove the SelectCommand property and SelectParameters:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>">

Then in the code behind do this:

SqlDataSource1.SelectParameters.Add("userId", userId.ToString());

SqlDataSource1.SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"

While this worked for me, the following code also works:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:itematConnectionString %>"
    SelectCommand = "SELECT items.name, items.id FROM items INNER JOIN users_items ON items.id = users_items.id WHERE (users_items.user_id = @userId) ORDER BY users_items.date DESC"></asp:SqlDataSource>


SqlDataSource1.SelectParameters.Add("userid", DbType.Guid, userId.ToString());

How to read file using NPOI

Simple read example below:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

//.....

private void button1_Click(object sender, EventArgs e)
{
    HSSFWorkbook hssfwb;
    using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
    {
        hssfwb= new HSSFWorkbook(file);
    }

    ISheet sheet = hssfwb.GetSheet("Arkusz1");
    for (int row = 0; row <= sheet.LastRowNum; row++)
    {
        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
        {
            MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
        }
    }
}  

By the way: on NPOI website here in Download section there is example package - a pack of C# examples. Try it, if you haven't yet. :)

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Framework and .NET Core are both frameworks.

.NET Standard is a standard (in other words, a specification).

You can make an executable project (like a console application, or ASP.NET application) with .NET Framework and .NET Core, but not with .NET Standard.

With .NET Standard you can make only a class library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.

What does "yield break;" do in C#?

Here http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/ is very good example:

public static IEnumerable<int> Range( int min, int max )
{
   while ( true )
   {
      if ( min >= max )
      {
         yield break;
      }
      yield return min++;
   }
}

and explanation, that if a yield break statement is hit within a method, execution of that method stops with no return. There are some time situations, when you don't want to give any result, then you can use yield break.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Read the message:

Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element.

Move the configSections element to the top - just above where system.data is currently.

Find all controls in WPF Window by type

Use the helper classes VisualTreeHelper or LogicalTreeHelper depending on which tree you're interested in. They both provide methods for getting the children of an element (although the syntax differs a little). I often use these classes for finding the first occurrence of a specific type, but you could easily modify it to find all objects of that type:

public static DependencyObject FindInVisualTreeDown(DependencyObject obj, Type type)
{
    if (obj != null)
    {
        if (obj.GetType() == type)
        {
            return obj;
        }

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject childReturn = FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type);
            if (childReturn != null)
            {
                return childReturn;
            }
        }
    }

    return null;
}

How to return value from Action()?

Use Func<T> rather than Action<T>.

Action<T> acts like a void method with parameter of type T, while Func<T> works like a function with no parameters and which returns an object of type T.

If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>.

Copy the entire contents of a directory in C#

Much easier

//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", 
    SearchOption.AllDirectories))
    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));

//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", 
    SearchOption.AllDirectories))
    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);

Decimal precision and scale in EF Code First

KinSlayerUY's custom attribute worked nicely for me but I had issues with ComplexTypes. They were being mapped as entities in the attribute code so couldn't then be mapped as a ComplexType.

I therefore extended the code to allow for this:

public static void OnModelCreating(DbModelBuilder modelBuilder)
    {
        foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
                                   where t.IsClass && t.Namespace == "FA.f1rstval.Data"
                                   select t)
        {
            foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
                   p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
            {

                ParameterExpression param = ParameterExpression.Parameter(classType, "c");
                Expression property = Expression.Property(param, propAttr.prop.Name);
                LambdaExpression lambdaExpression = Expression.Lambda(property, true,
                                                                         new ParameterExpression[] { param });
                DecimalPropertyConfiguration decimalConfig;
                int MethodNum;
                if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    MethodNum = 7;
                }
                else
                {
                    MethodNum = 6;
                }

                //check if complextype
                if (classType.GetCustomAttribute<ComplexTypeAttribute>() != null)
                {
                    var complexConfig = modelBuilder.GetType().GetMethod("ComplexType").MakeGenericMethod(classType).Invoke(modelBuilder, null);
                    MethodInfo methodInfo = complexConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[MethodNum];
                    decimalConfig = methodInfo.Invoke(complexConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
                }
                else
                {
                    var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
                    MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[MethodNum];
                    decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
                }

                decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
            }
        }
    }

How can I auto increment the C# assembly version via our CI platform (Hudson)?

So, we have a project with one solution that contains several projects that have assemblies with different version numbers.

After investigating several of the above methods, I just implemented a build step to run a Powershell script that does a find-and-replace on the AssemblyInfo.cs file. I still use the 1.0.* version number in source control, and Jenkins just manually updates the version number before msbuild runs.

dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }
dir **/Properties/AssemblyInfo.cs | %{ (cat $_) | %{$_ -replace '^(\s*)\[assembly: AssemblyFileVersion\("(.*)\.\*"\)', "`$1[assembly: AssemblyFileVersion(`"`$2.$build`")"} | Out-File $_ -Encoding "UTF8" }

I added the -Encoding "UTF8" option because git started treating the .cs file as binary files if I didn't. Granted, this didn't matter, since I never actually commit the result; it just came up as I was testing.

Our CI environment already has a facility to associate the Jenkins build with the particular git commit (thanks Stash plugin!), so I don't worry that there's no git commit with the version number attached to it.

How to send an HTTPS GET Request in C#

Simple Get Request using HttpClient Class

using System.Net.Http;

class Program
{
   static void Main(string[] args)
    {
        HttpClient httpClient = new HttpClient();
        var result = httpClient.GetAsync("https://www.google.com").Result;
    }

}

How to change TextBox's Background color?

It is txtName.BackColor = System.Drawing.Color.Red;

one can also use txtName.BackColor = Color.Aqua; which is the same as txtName.BackColor = System.Color.Aqua;

Only Problem with System.color is that it does not contain a definition for some basic colors especially white, which is important cause usually textboxes are white;

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

In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.

The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.

There are a several ways to enter the thread pool:

  • with the TPL (Task Parallel Library) like you did
  • by calling ThreadPool.QueueUserWorkItem
  • by calling BeginInvoke on a delegate
  • when you use a BackgroundWorker

Transactions in .net

It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).

I would use something like

SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
    ...
    Do SQL stuff here passing my trans into my various SQL executers
    ...
    trans.Commit  // May not be quite right
}

Any failure will pop you right out of the using and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

This issue could be because of wrong entity framework reference or sometimes the Class name not matching the entity name in database. Make sure the Table name matches with class name.

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

This error message

error: (-215)size.width>0 && size.height>0 in function imshow

simply means that imshow() is not getting video frame from input-device. You can try using

cap = cv2.VideoCapture(1) 

instead of

cap = cv2.VideoCapture(0) 

& see if the problem still persists.

How to run function in AngularJS controller on document ready?

The answer

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

is the only one that works in most scenarios I tested. In a sample page with 4 components all of which build HTML from a template, the order of events was

$document ready
$onInit
$postLink
(and these 3 were repeated 3 more times in the same order for the other 3 components)
$viewContentLoaded (repeated 3 more times)
$timeout execution (repeated 3 more times)

So a $document.ready() is useless in most cases since the DOM being constructed in angular may be nowhere near ready.

But more interesting, even after $viewContentLoaded fired, the element of interest still could not be found.

Only after the $timeout executed was it found. Note that even though the $timeout was a value of 0, nearly 200 milliseconds elapsed before it executed, indicating that this thread was held off for quite a while, presumably while the DOM had angular templates added on a main thread. The total time from the first $document.ready() to the last $timeout execution was nearly 500 milliseconds.

In one extraordinary case where the value of a component was set and then the text() value was changed later in the $timeout, the $timeout value had to be increased until it worked (even though the element could be found during the $timeout). Something async within the 3rd party component caused a value to take precedence over the text until sufficient time passed. Another possibility is $scope.$evalAsync, but was not tried.

I am still looking for that one event that tells me the DOM has completely settled down and can be manipulated so that all cases work. So far an arbitrary timeout value is necessary, meaning at best this is a kludge that may not work on a slow browser. I have not tried JQuery options like liveQuery and publish/subscribe which may work, but certainly aren't pure angular.

Python speed testing - Time Difference - milliseconds

I know this is late, but I actually really like using:

import time
start = time.time()

##### your timed code here ... #####

print "Process time: " + (time.time() - start)

time.time() gives you seconds since the epoch. Because this is a standardized time in seconds, you can simply subtract the start time from the end time to get the process time (in seconds). time.clock() is good for benchmarking, but I have found it kind of useless if you want to know how long your process took. For example, it's much more intuitive to say "my process takes 10 seconds" than it is to say "my process takes 10 processor clock units"

>>> start = time.time(); sum([each**8.3 for each in range(1,100000)]) ; print (time.time() - start)
3.4001404476250935e+45
0.0637760162354
>>> start = time.clock(); sum([each**8.3 for each in range(1,100000)]) ; print (time.clock() - start)
3.4001404476250935e+45
0.05

In the first example above, you are shown a time of 0.05 for time.clock() vs 0.06377 for time.time()

>>> start = time.clock(); time.sleep(1) ; print "process time: " + (time.clock() - start)
process time: 0.0
>>> start = time.time(); time.sleep(1) ; print "process time: " + (time.time() - start)
process time: 1.00111794472

In the second example, somehow the processor time shows "0" even though the process slept for a second. time.time() correctly shows a little more than 1 second.

How to disable input conditionally in vue.js

You may make a computed property and enable/disable any form type according to its value.

<template>
    <button class="btn btn-default" :disabled="clickable">Click me</button>
</template>
<script>
     export default{
          computed: {
              clickable() {
                  // if something
                  return true;
              }
          }
     }
</script>

Insert current date into a date column using T-SQL?

To insert a new row into a given table (tblTable) :

INSERT INTO tblTable (DateColumn) VALUES (GETDATE())

To update an existing row :

UPDATE tblTable SET DateColumn = GETDATE()
 WHERE ID = RequiredUpdateID

Note that when INSERTing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL constraint - so you may need to provide values for other columns eg...

 INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:

RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’

And from there I ran a restore statement with MOVE using logical names.

RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'

When it was done restoring, I almost wept with joy.

Good luck!

How to list processes attached to a shared memory segment in linux?

I don't think you can do this with the standard tools. You can use ipcs -mp to get the process ID of the last process to attach/detach but I'm not aware of how to get all attached processes with ipcs.

With a two-process-attached segment, assuming they both stayed attached, you can possibly figure out from the creator PID cpid and last-attached PID lpid which are the two processes but that won't scale to more than two processes so its usefulness is limited.

The cat /proc/sysvipc/shm method seems similarly limited but I believe there's a way to do it with other parts of the /proc filesystem, as shown below:

When I do a grep on the procfs maps for all processes, I get entries containing lines for the cpid and lpid processes.

For example, I get the following shared memory segment from ipcs -m:

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 123456     pax        600        1024       2          dest

and, from ipcs -mp, the cpid is 3956 and the lpid is 9999 for that given shared memory segment (123456).

Then, with the command grep 123456 /proc/*/maps, I see:

/proc/3956/maps: blah blah blah 123456 /SYSV000000 (deleted)
/proc/9999/maps: blah blah blah 123456 /SYSV000000 (deleted)

So there is a way to get the processes that attached to it. I'm pretty certain that the dest status and (deleted) indicator are because the creator has marked the segment for destruction once the final detach occurs, not that it's already been destroyed.

So, by scanning of the /proc/*/maps "files", you should be able to discover which PIDs are currently attached to a given segment.

How to perform a real time search and filter on a HTML table

I created these examples.

Simple indexOf search

var $rows = $('#table tr');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});

Demo: http://jsfiddle.net/7BUmG/2/

Regular expression search

More advanced functionality using regular expressions will allow you to search words in any order in the row. It will work the same if you type apple green or green apple:

var $rows = $('#table tr');
$('#search').keyup(function() {

    var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;

    $rows.show().filter(function() {
        text = $(this).text().replace(/\s+/g, ' ');
        return !reg.test(text);
    }).hide();
});

Demo: http://jsfiddle.net/dfsq/7BUmG/1133/

Debounce

When you implement table filtering with search over multiple rows and columns it is very important that you consider performance and search speed/optimisation. Simply saying you should not run search function on every single keystroke, it's not necessary. To prevent filtering to run too often you should debounce it. Above code example will become:

$('#search').keyup(debounce(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    // etc...
}, 300));

You can pick any debounce implementation, for example from Lodash _.debounce, or you can use something very simple like I use in next demos (debounce from here): http://jsfiddle.net/7BUmG/6230/ and http://jsfiddle.net/7BUmG/6231/.

How to execute a shell script from C in Linux?

A simple way is.....

#include <stdio.h>
#include <stdlib.h>


#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate 
  and send to the system(concatenated_string); */

int main()
{
    puts("Will execute sh with the following script :");
    puts(SHELLSCRIPT);
    puts("Starting now:");
    system(SHELLSCRIPT);    //it will run the script inside the c code. 
    return 0;
}

Say thanks to
Yoda @http://www.unix.com/programming/216190-putting-bash-script-c-program.html

Angular ng-if not true

Just use for True:

<li ng-if="area"></li>

and for False:

<li ng-if="area === false"></li>

How do I connect to an MDF database file?

For Visual Studio 2015 the connection string is:

"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True"

How is an HTTP POST request made in node.js?

To Post Rest/JSON Request
We can simply use request package and save the values we have to send in Json variable.

First install the require package in your console by npm install request --save

var request = require('request');

    var options={
                'key':'28',
                'key1':'value',
                'key2':'value'
                }

    request({
             url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?                      
                 minorRev="+options.key+
                 "&cid="+options.key1+
                 "&apiKey="+options.key2,
             method:"POST",
             json:true},function(error,response,body){
                     console.log(body)
               }
    );

How to add include and lib paths to configure/make cycle?

You want a config.site file. Try:

$ mkdir -p ~/local/share
$ cat << EOF > ~/local/share/config.site
CPPFLAGS=-I$HOME/local/include
LDFLAGS=-L$HOME/local/lib
...
EOF

Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.

How to Add Date Picker To VBA UserForm

OFFICE 2013 INSTRUCTIONS:

(For Windows 7 (x64) | MS Office 32-Bit)

Option 1 | Check if ability already exists | 2 minutes

  1. Open VB Editor
  2. Tools -> Additional Controls
  3. Select "Microsoft Monthview Control 6.0 (SP6)" (if applicable)
  4. Use 'DatePicker' control for VBA Userform

Option 2 | The "Monthview" Control doesn't currently exist | 5 minutes

  1. Close Excel
  2. Download MSCOMCT2.cab (it's a cabinet file which extracts into two useful files)
  3. Extract Both Files | the .inf file and the .ocx file
  4. Install | right-click the .inf file | hit "Install"
  5. Move .ocx file | Move from "C:\Windows\system32" to "C:\Windows\sysWOW64"
  6. Run CMD | Start Menu -> Search -> "CMD.exe" | right-click the icon | Select "Run as administrator"
  7. Register Active-X File | Type "regsvr32 c:\windows\sysWOW64\MSCOMCT2.ocx"
  8. Open Excel | Open VB Editor
  9. Activate Control | Tools->References | Select "Microsoft Windows Common Controls 2-6.0 (SP6)"
  10. Userform Controls | Select any userform in VB project | Tools->Additional Controls
  11. Select "Microsoft Monthview Control 6.0 (SP6)"
  12. Use 'DatePicker' control for VBA UserForm

Okay, either of these two steps should work for you if you have Office 2013 (32-Bit) on Windows 7 (x64). Some of the steps may be different if you have a different combo of Windows 7 & Office 2013.

The "Monthview" control will be your fully fleshed out 'DatePicker'. It comes equipped with its own properties and image. It works very well. Good luck.

Site: "bonCodigo" from above (this is an updated extension of his work)
Site: "AMM" from above (this is just an exension of his addition)
Site: Various Microsoft Support webpages

AngularJS - difference between pristine/dirty and touched/untouched

$pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

Here's a CodePen that shows the difference in behavior.

How to tell which disk Windows Used to Boot

You can use WMI to figure this out. The Win32_BootConfiguration class will tell you both the logical drive and the physical device from which Windows boots. Specifically, the Caption property will tell you which device you're booting from.

For example, in powershell, just type gwmi Win32_BootConfiguration to get your answer.

How to select count with Laravel's fluent query builder?

You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:

$query = DB::table('category_issue')
    ->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
    ->where('category_id', '=', 1)
    ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
    ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
    ->group_by('issues.id')
    ->order_by('followers', 'desc')
    ->get();

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

It's recommended to try any or all of the following:

  • Restart Visual Studio

  • Try Running As Administrator (right-click Visual Studio and choose "Run As Administrator")

  • Check for any updates for Visual Studio (download and install them if any are available)

  • Try opening a different solution / project

If problems persist, you might try the following options:

  • Restart your local machine

  • Attempt to reset Visual Studio to System Defaults (this can be done from the options within Visual Studio)

  • Attempt to repair your Visual Studio installation

Getting the array length of a 2D array in Java

Consider

public static void main(String[] args) {

    int[][] foo = new int[][] {
        new int[] { 1, 2, 3 },
        new int[] { 1, 2, 3, 4},
    };

    System.out.println(foo.length); //2
    System.out.println(foo[0].length); //3
    System.out.println(foo[1].length); //4
}

Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.

What are database normal forms and can you give examples?

1NF: Only one value per column

2NF: All the non primary key columns in the table should depend on the entire primary key.

3NF: All the non primary key columns in the table should depend DIRECTLY on the entire primary key.

I have written an article in more detail over here

What is the most accurate way to retrieve a user's correct IP address in PHP?

My answer is basically just a polished, fully-validated, and fully-packaged, version of @AlixAxel's answer:

<?php

/* Get the 'best known' client IP. */

if (!function_exists('getClientIP'))
    {
        function getClientIP()
            {
                if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) 
                    {
                        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
                    };

                foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
                    {
                        if (array_key_exists($key, $_SERVER)) 
                            {
                                foreach (explode(',', $_SERVER[$key]) as $ip)
                                    {
                                        $ip = trim($ip);

                                        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
                                            {
                                                return $ip;
                                            };
                                    };
                            };
                    };

                return false;
            };
    };

$best_known_ip = getClientIP();

if(!empty($best_known_ip))
    {
        $ip = $clients_ip = $client_ip = $client_IP = $best_known_ip;
    }
else
    {
        $ip = $clients_ip = $client_ip = $client_IP = $best_known_ip = '';
    };

?>

Changes:

  • It simplifies the function name (with 'camelCase' formatting style).

  • It includes a check to make sure the function isn't already declared in another part of your code.

  • It takes into account 'CloudFlare' compatibility.

  • It initializes multiple "IP-related" variable names to the returned value, of the 'getClientIP' function.

  • It ensures that if the function doesn't return a valid IP address, all the variables are set to a empty string, instead of null.

  • It's only (45) lines of code.

Zooming MKMapView to fit annotation pins?

Apple has added a new method for IOS 7 to simplify life a bit.

[mapView showAnnotations:yourAnnotationArray animated:YES];

You can easily pull from an array stored in the map view:

yourAnnotationArray = mapView.annotations;

and quickly adjust the camera too!

mapView.camera.altitude *= 1.4;

this won't work unless the user has iOS 7+ or OS X 10.9+ installed. check out custom animation here

Error: Segmentation fault (core dumped)

There is one more reason for such failure which I came to know when mine failed

  • You might be working with a lot of data and your RAM is full

This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.

How do I check form validity with angularjs?

form

  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Mongo lets you update nested documents using a . convention. Take a look: Updating nested documents in mongodb. Here's another question from the past about a merge update, like the one you're looking for I believe: MongoDB atomic update via 'merge' document

How to change value of a request parameter in laravel

If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().

namespace App\Http\Requests\Admin\Category;
    
class CategoryRequest extends AbstractRequest
{
    protected function prepareForValidation()
    {
        if ( ! $this->get('url')) {
            $this->merge([
                'url' => $this->get('name'),
            ]);
        }
        $this->merge([
            'url'    => \Str::slug($this->get('url')),
            'active' => (int)$this->get('active'),
        ]);
    }
}

I hope this information will be useful to somebody.

How to get current date in jquery?

you can use this code:

var nowDate     = new Date();
var nowDay      = ((nowDate.getDate().toString().length) == 1) ? '0'+(nowDate.getDate()) : (nowDate.getDate());
var nowMonth    = ((nowDate.getMonth().toString().length) == 1) ? '0'+(nowDate.getMonth()+1) : (nowDate.getMonth()+1);
var nowYear     = nowDate.getFullYear();
var formatDate  = nowDay + "." + nowMonth + "." + nowYear;

you can find a working demo here

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

This Might help as reference

I had the same issue, after multiple trial of suggested solution on this site and others, I found a solution for my scenario. The account was locked out How to Check if the account is Locked out... Login to the server using higher privileged account (like SA or admin rights) Expand security ==> select the login name ==>open the property window of the login ==> select the status page on the property window

Make sure This 3 Things 1, permission to connect database is GRANTED 2, Login is ENABLED 3, Status SQL server authentication Login is not locked out (Uncheck the box)

Thanks Tsige

Check whether a table contains rows or not sql server 2005

For what purpose?

  • Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
  • For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
  • For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

Why use deflate instead of gzip for text files served by Apache?

There shouldn't be any difference in gzip & deflate for decompression. Gzip is just deflate with a few dozen byte header wrapped around it including a checksum. The checksum is the reason for the slower compression. However when you're precompressing zillions of files you want those checksums as a sanity check in your filesystem. In addition you can utilize commandline tools to get stats on the file. For our site we are precompressing a ton of static data (the entire open directory, 13,000 games, autocomplete for millions of keywords, etc.) and we are ranked 95% faster than all websites by Alexa. Faxo Search. However, we do utilize a home grown proprietary web server. Apache/mod_deflate just didn't cut it. When those files are compressed into the filesystem not only do you take a hit for your file with the minimum filesystem block size but all the unnecessary overhead in managing the file in the filesystem that the webserver could care less about. Your concerns should be total disk footprint and access/decompression time and secondarily speed in being able to get this data precompressed. The footprint is important because even though disk space is cheap you want as much as possible to fit in the cache.

How to convert String to Date value in SAS?

Try

data _null_; 
   monyy = '05May2013'; 
   date = input(substr(strip(monyy),1,9),date9.);
   put date=date9.; 
   run;

"You have mail" message in terminal, os X

If you don't want the hassle of using mail, you can read the mail with

cat /var/mail/<username>

and delete the mail with

sudo rm /var/mail/<username>

CSS Selector for <input type="?"

You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...

Why is my JavaScript function sometimes "not defined"?

Use an anonymous function to protect your local symbol table. Something like:

(function() {
    function copyArray(pa) {
        // Details
    }

    Function.prototype.bind = function ( po ) {
        __args = copyArray( arguments );
    }
})();

This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.

How to quickly and conveniently disable all console.log statements in my code?

I found this thread after figuring it out myself. Here's my solution:

const testArray = {
  a: 1,
  b: 2
};
const verbose = true; //change this to false to turn off all comments
const consoleLog = (...message) => {
  return verbose ? console.log(...message) : null;
};

console.log("from console.log", testArray);
consoleLog("from consoleLog", testArray);
// use consoleLog() for the comments you want to be able to toggle.

Get and Set Screen Resolution

For retrieving the screen resolution, you're going to want to use the System.Windows.Forms.Screen class. The Screen.AllScreens property can be used to access a collection of all of the displays on the system, or you can use the Screen.PrimaryScreen property to access the primary display.

The Screen class has a property called Bounds, which you can use to determine the resolution of the current instance of the class. For example, to determine the resolution of the current screen:

Rectangle resolution = Screen.PrimaryScreen.Bounds;

For changing the resolution, things get a little more complicated. This article (or this one) provides a detailed implementation and explanation. Hope this helps.

Arithmetic overflow error converting numeric to data type numeric

My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2) or decimal(10,2) or whatever.

You can test this by commenting out the insert #temp and see what numbers the select statement is giving you and see if they are bigger than your column can handle.

How to unset (remove) a collection element after fetching it?

Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

If you have the key already you can just use PHP unset.

I prefer this, because it clearly modifies the collection in place, and is easy to remember.

foreach ($collection as $key => $value) {
    unset($collection[$key]);
}

How do I get the position selected in a RecyclerView?

I think the most correct way to get item position is

View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override public void onClick(View v) {
      View view = v;
      View parent = (View) v.getParent();
      while (!(parent instanceof RecyclerView)){
        view=parent;
        parent = (View) parent.getParent();
      }
      int position = recyclerView.getChildAdapterPosition(view);
}

Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);

Simple way to change the position of UIView?

UIView's also have a center property. If you just want to move the position rather than resize, you can just change that - eg:

aView.center = CGPointMake(50, 200);

Otherwise you would do it the way you posted.

PHP cURL custom headers

Use the following Syntax

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.5',
    'Cache-Control: no-cache',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Host: www.example.com',
    'Referer: http://www.example.com/index.php', //Your referrer address
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
    'X-MicrosoftAjax: Delta=true'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

What's the best way to add a full screen background image in React Native

The width and height with value null doesn't work for me, then I thought to use top, bottom, left, and right position and it worked. Example:

bg: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        resizeMode: 'stretch',
},

And the JSX:

<Image style={styles.bg} source={{uri: 'IMAGE URI'}} />

What is the difference between XAMPP or WAMP Server & IIS?

WAMP is an acronym for Windows (OS), Apache (web-server), MySQL (database), PHP (language).

XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people. There are also other WAMPs such as UniformServer. And there are commercial WAMPs such as WampDeveloper (what I use).

Their differences are in the format/structure of the package, the configurations, and the included management applications.

IIS is a web-server application just like Apache is, except it's made by Microsoft and is Windows only (Apache runs on both Windows and Linux). IIS is also more geared towards using ASP.NET (vs. PHP) and "SQL Server" (vs. MySQL), though it can use PHP and MySQL too.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

this one works for me (plain javascript)

var fixScroll = function (className, border) {  // className = class of scrollElement(s), border: borderTop + borderBottom, due to offsetHeight
var reg = new RegExp(className,"i"); var off = +border + 1;
function _testClass(e) { var o = e.target; while (!reg.test(o.className)) if (!o || o==document) return false; else o = o.parentNode; return o;}
document.ontouchmove  = function(e) { var o = _testClass(e); if (o) { e.stopPropagation(); if (o.scrollTop == 0) { o.scrollTop += 1; e.preventDefault();}}}
document.ontouchstart = function(e) { var o = _testClass(e); if (o && o.scrollHeight >= o.scrollTop + o.offsetHeight - off) o.scrollTop -= off;}
}

fixScroll("fixscroll",2); // assuming I have a 1px border in my DIV

html:

<div class="fixscroll" style="border:1px gray solid">content</div>

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

This error just means that myapp.views.home is not something that can be called, like a function. It is a string in fact. While your solution works in django 1.9, nevertheless it throws a warning saying this will deprecate from version 1.10 onwards, which is exactly what has happened. The previous solution by @Alasdair imports the necessary view functions into the script through either from myapp import views as myapp_views or from myapp.views import home, contact

How to create a file with a given size in Linux?

Please, modern is easier, and faster. On Linux, (pick one)

truncate -s 10G foo
fallocate -l 5G bar

It needs to be stated that truncate on a file system supporting sparse files will create a sparse file and fallocate will not. A sparse file is one where the allocation units that make up the file are not actually allocated until used. The meta-data for the file will however take up some considerable space but likely no where near the actual size of the file. You should consult resources about sparse files for more information as there are advantages and disadvantages to this type of file. A non-sparse file has its blocks (allocation units) allocated ahead of time which means the space is reserved as far as the file system sees it. Also fallocate nor truncate will not set the contents of the file to a specified value like dd, instead the contents of a file allocated with fallocate or truncate may be any trash value that existed in the allocated units during creation and this behavior may or may not be desired. The dd is the slowest because it actually writes the value or chunk of data to the entire file stream as specified with it's command line options.

This behavior could potentially be different - depending on file system used and conformance of that file system to any standard or specification. Therefore it is advised that proper research is done to ensure that the appropriate method is used.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

The solutions posted here did not work well for me, so I did a mixture of the ones of this question and the following question: Is it possible to create multi-level ordered list in HTML?

/* Numbered lists like 1, 1.1, 2.2.1... */
ol li {display:block;} /* hide original list counter */
ol > li:first-child {counter-reset: item;} /* reset counter */
ol > li {counter-increment: item; position: relative;} /* increment counter */
ol > li:before {content:counters(item, ".") ". "; position: absolute; margin-right: 100%; right: 10px;} /* print counter */

Result:

screenshot

Note: the screenshot, if you wish to see the source code or whatever is from this post: http://estiloasertivo.blogspot.com.es/2014/08/introduccion-running-lean-y-lean.html

How to find whether MySQL is installed in Red Hat?

Type mysql --version to see if it is installed.

To find location use find -name mysql.

How does the ARM architecture differ from x86?

ARM is a RISC (Reduced Instruction Set Computing) architecture while x86 is a CISC (Complex Instruction Set Computing) one.

The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.

So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.

About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86 isn't specially designed to work with a keyboard neither ARM for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.

If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:

An ARM processor is a Reduced Instruction Set Computer (RISC) processor.

Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).

RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.

ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.

An example comparing instruction set architecture:

For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86

repe cmpsb         /* repeat while equal compare string bytewise */

while on ARM shortest form might look like (without error checking etc.)

top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2    /* subtract r2 from r3 and put result into r2      */
beq  top           /* branch(/jump) if result is zero                 */

which should give you a hint on how RISC and CISC instruction sets differ in complexity.

How do I update a Tomcat webapp without restarting the entire service?

Have you tried to use Tomcat's Manager application? It allows you to undeploy / deploy war files with out shutting Tomcat down.

If you don't want to use the Manager application, you can also delete the war file from the webapps directory, Tomcat will undeploy the application after a short period of time. You can then copy a war file back into the directory, and Tomcat will deploy the war file.

If you are running Tomcat on Windows, you may need to configure your Context to not lock various files.

If you absolutely can't have any downtime, you may want to look at Tomcat 7's Parallel deployments You may deploy multiple versions of a web application with the same context path at the same time. The rules used to match requests to a context version are as follows:

  • If no session information is present in the request, use the latest version.
  • If session information is present in the request, check the session manager of each version for a matching session and if one is found, use that version.
  • If session information is present in the request but no matching session can be found, use the latest version.

JCheckbox - ActionListener and ItemListener?

I've been testing this myself, and looking at all the answers on this post and I don't think they answer this question very well. I experimented myself in order to get a good answer (code below). You CAN fire either event with both ActionListener and ItemListener 100% of the time when a state is changed in either a radio button or a check box, or any other kind of Swing item I'm assuming since it is type Object. The ONLY difference I can tell between these two listeners is the type of Event Object that gets returned with the listener is different. AND you get a better event type with a checkbox using an ItemListener as opposed to an ActionListener.

The return types of an ActionEvent and an ItemEvent will have different methods stored that may be used when an Event Type gets fired. In the code below the comments show the difference in .get methods for each Class returned Event type.

The code below sets up a simple JPanel with JRadioButtons, JCheckBoxes, and a JLabel display that changes based on button configs. I set all the RadioButtons and CheckBoxes up with both an Action Listener and an Item Listener. Then I wrote the Listener classes below with ActionListener fully commented because I tested it first in this experiment. You will notice that if you add this panel to a frame and display, all radiobuttons and checkboxes always fire regardless of the Listener type, just comment out the methods in one and try the other and vice versa.

Return Type into the implemented methods is the MAIN difference between the two. Both Listeners fire events the same way. Explained a little better in comment above is the reason a checkbox should use an ItemListener over ActionListener due to the Event type that is returned.

package EventHandledClasses;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RadioButtonsAndCheckBoxesTest extends JPanel{
JLabel display;
String funny, serious, political;
JCheckBox bold,italic;
JRadioButton funnyQuote, seriousQuote, politicalQuote;
ButtonGroup quotes;

    public RadioButtonsAndCheckBoxesTest(){
        funny = "You are not ugly, you were just born... different";
        serious = "Recommend powdered soap in prison!";
        political = "Trump can eat a little Bernie, but will choke on his     Birdie";

        display = new JLabel(funny);
        Font defaultFont = new Font("Ariel",Font.PLAIN,20);
        display.setFont(defaultFont);

        bold = new JCheckBox("Bold",false);
        bold.setOpaque(false);
        italic = new JCheckBox("Italic",false);
        italic.setOpaque(false);

        //Color itemBackground =

        funnyQuote = new JRadioButton("Funny",true);
        funnyQuote.setOpaque(false);
        seriousQuote = new JRadioButton("Serious");
        seriousQuote.setOpaque(false);
        politicalQuote = new JRadioButton("Political");
        politicalQuote.setOpaque(false);

        quotes = new ButtonGroup();
        quotes.add(funnyQuote);
        quotes.add(seriousQuote);
        quotes.add(politicalQuote);

        JPanel primary = new JPanel();
        primary.setPreferredSize(new Dimension(550, 100));

        Dimension standard = new Dimension(500, 30);

        JPanel radioButtonsPanel = new JPanel();
        radioButtonsPanel.setPreferredSize(standard);
        radioButtonsPanel.setBackground(Color.green);
        radioButtonsPanel.add(funnyQuote);
        radioButtonsPanel.add(seriousQuote);
        radioButtonsPanel.add(politicalQuote);

        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.setPreferredSize(standard);
        checkBoxPanel.setBackground(Color.green);
        checkBoxPanel.add(bold);
        checkBoxPanel.add(italic);

        primary.add(display);
        primary.add(radioButtonsPanel);
        primary.add(checkBoxPanel);

        //Add Action Listener To test Radio Buttons
        funnyQuote.addActionListener(new ActionListen());
        seriousQuote.addActionListener(new ActionListen());
        politicalQuote.addActionListener(new ActionListen());

        //Add Item Listener to test Radio Buttons
        funnyQuote.addItemListener(new ItemListen());
        seriousQuote.addItemListener(new ItemListen());
        politicalQuote.addItemListener(new ItemListen());

        //Add Action Listener to test Check Boxes
        bold.addActionListener(new ActionListen());
        italic.addActionListener(new ActionListen());

        //Add Item Listener to test Check Boxes
        bold.addItemListener(new ItemListen());
        italic.addItemListener(new ItemListen());

        //adds primary JPanel to this JPanel Object
        add(primary);   
    }

    private class ActionListen implements ActionListener{

        public void actionPerformed(ActionEvent e) {

         /*
         Different Get Methods from  ItemEvent 
         e.getWhen()
         e.getModifiers()
         e.getActionCommand()*/

            /*int font=Font.PLAIN;
            if(bold.isSelected()){
                font += Font.BOLD;
            }
            if(italic.isSelected()){
                font += Font.ITALIC;
            }
            display.setFont(new Font("Ariel",font,20));

            if(funnyQuote.isSelected()){
                display.setText(funny);
            }
            if(seriousQuote.isSelected()){
                display.setText(serious);
            }
            if(politicalQuote.isSelected()){
                display.setText(political);
            }*/
        }
    }
    private class ItemListen implements ItemListener {

        public void itemStateChanged(ItemEvent arg0) {

            /*
            Different Get Methods from ActionEvent
            arg0.getItemSelectable()
            arg0.getStateChange()
            arg0.getItem()*/


            int font=Font.PLAIN;
            if(bold.isSelected()){
                font += Font.BOLD;
            }
            if(italic.isSelected()){
                font += Font.ITALIC;
            }
            display.setFont(new Font("Ariel",font,20));

            if(funnyQuote.isSelected()){
                display.setText(funny);
            }
            if(seriousQuote.isSelected()){
                display.setText(serious);
            }
            if(politicalQuote.isSelected()){
                display.setText(political);
            }

        }

    }
}

Gradle - Could not find or load main class

If you're using Spring Boot, this might be the issue: https://github.com/gradle/gradle/issues/2489.

Basically, the output directories changed in Gradle 4.0, so if you have them hardcoded the execution will fail.

The solution is to replace:

bootRun {
   dependsOn pathingJar
   doFirst {
      classpath = files("$buildDir/classes/main", "$buildDir/resources/main", pathingJar.archivePath)
   }
}

by:

bootRun {
   dependsOn pathingJar
   doFirst {
      classpath = files(sourceSets.main.output.files, pathingJar.archivePath)
   }
}

ActiveX component can't create object

I had the same issue with Excel, I was trying to use a 32 COM DLL with an Excel 64 bits version and I got this error. I rebuild the COM dll to a 64 bits version and the error disappears. So be sure that your COM dll has the same architecture (x86 vs x64) than your application.

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

How to make an Android Spinner with initial text "Select One"?

I think the easiest way is creating a dummy item on index 0 saying "select one" and then on saving maybe check that selection is not 0.

What is the most efficient string concatenation method in python?

For python 3.8.6/3.9, I had to do some dirty hacks, because perfplot was giving out some errors. Here assume that x[0] is a a and x[1] is b: Performance

The plot is nearly same for large data. For small data, Performance 2

Taken by perfplot and this is the code, large data == range(8), small data == range(4).

import perfplot

from random import choice
from string import ascii_lowercase as letters

def generate_random(x):
    data = ''.join(choice(letters) for i in range(x))
    sata = ''.join(choice(letters) for i in range(x))
    return [data,sata]

def fstring_func(x):
    return [ord(i) for i in f'{x[0]}{x[1]}']

def format_func(x):
    return [ord(i) for i in "{}{}".format(x[0], x[1])]

def replace_func(x):
    return [ord(i) for i in "|~".replace('|', x[0]).replace('~', x[1])]

def join_func(x):
    return [ord(i) for i in "".join([x[0], x[1]])]

perfplot.show(
    setup=lambda n: generate_random(n),
    kernels=[
        fstring_func,
        format_func,
        replace_func,
        join_func,
    ],
    n_range=[int(k ** 2.5) for k in range(4)],
)

When medium data is there, and 4 strings are there x[0], x[1], x[2], x[3] instead of 2 string:

def generate_random(x):
    a =  ''.join(choice(letters) for i in range(x))
    b =  ''.join(choice(letters) for i in range(x))
    c =  ''.join(choice(letters) for i in range(x))
    d =  ''.join(choice(letters) for i in range(x))
    return [a,b,c,d]

Performance 3 Better to stick with fstrings

How to round the minute of a datetime object

General function to round a datetime at any time lapse in seconds:

def roundTime(dt=None, roundTo=60):
   """Round a datetime object to any time lapse in seconds
   dt : datetime.datetime object, default now.
   roundTo : Closest number of seconds to round to, default 1 minute.
   Author: Thierry Husson 2012 - Use it as you want but don't blame me.
   """
   if dt == None : dt = datetime.datetime.now()
   seconds = (dt.replace(tzinfo=None) - dt.min).seconds
   rounding = (seconds+roundTo/2) // roundTo * roundTo
   return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)

Samples with 1 hour rounding & 30 minutes rounding:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=30*60)
2012-12-31 23:30:00

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

How do I create a pause/wait function using Qt?

To use the standard sleep function add the following in your .cpp file:

#include <unistd.h>

As of Qt version 4.8, the following sleep functions are available:

void QThread::msleep(unsigned long msecs)
void QThread::sleep(unsigned long secs)
void QThread::usleep(unsigned long usecs)

To use them, simply add the following in your .cpp file:

#include <QThread>

Reference: QThread (via Qt documentation): http://doc.qt.io/qt-4.8/qthread.html

Otherwise, perform these steps...

Modify the project file as follows:

CONFIG += qtestlib

Note that in newer versions of Qt you will get the following error:

Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.

... so, instead modify the project file as follows:

QT += testlib

Then, in your .cpp file, be sure to add the following:

#include <QtTest>

And then use one of the sleep functions like so:

usleep(100);

Is there an easy way to add a border to the top and bottom of an Android View?

Simplest way to add borders to inset the borders using InsetDrawable,following will show top border only :

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetBottom="-2dp"
    android:insetLeft="-2dp"
    android:insetRight="-2dp">
    <shape android:shape="rectangle">

        <solid android:color="@color/light_gray" />
        <stroke
            android:width=".5dp"
            android:color="@color/dark_gray" />
    </shape>
</inset>

Difference between margin and padding?

Padding

Padding is a CSS property that defines the space between an element content and its border (if it has a border). If an element has a border around it, padding will give space from that border to the element content which appears in that border. If an element does not have a border around it, then adding padding has no effect at all on that element, because there is no border to give space from.

Margin

Margin is a CSS property that defines the space of outside of an element to its next outside element.

Margin affects elements that both have or do not have borders. If an element has a border, margin defines the space from this border to the next outer element. If an element does not have a border, then margin defines the space from the element content to the next outer element.

Difference Between Padding and Margin

So the difference between margin and padding is that while padding deals with the inner space, margin deals with the outer space to the next outer element.

How do I collapse sections of code in Visual Studio Code for Windows?

Collapsing is now supported in release 1.0:

Source Code Folding Shortcuts

There are new folding actions to collapse source code regions based on their folding level.

There are actions to fold level 1 (Ctrl+K Ctrl+1) to level 5 (Ctrl+K Ctrl+5). To unfold, use Unfold All (Ctrl+Shift+Alt+]).

The level folding actions do not apply to region containing the current cursor.

I had a problem finding the ] button on my keyboard (Norwegian layout), and in my case it was the Å button. (Or two buttons left and one down starting from the backspace button.)

How to center absolute div horizontally using CSS?

This doesn't work in IE8 but might be an option to consider. It is primarily useful if you do not want to specify a width.

.element
{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

How to convert a string to JSON object in PHP

To convert a valid JSON string back, you can use the json_decode() method.

To convert it back to an object use this method:

$jObj = json_decode($jsonString);

And to convert it to a associative array, set the second parameter to true:

$jArr = json_decode($jsonString, true);

By the way to convert your mentioned string back to either of those, you should have a valid JSON string. To achieve it, you should do the following:

  1. In the Coords array, remove the two " (double quote marks) from the start and end of the object.
  2. The objects in an array are comma seprated (,), so add commas between the objects in the Coords array..

And you will have a valid JSON String..

Here is your JSON String I converted to a valid one: http://pastebin.com/R16NVerw

How to download a file from a website in C#

Use WebClient.DownloadFile:

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}

Jquery resizing image

$(document).ready(function(){
    $('img').each(function(){
        var maxWidth = 660;
        var ratio = 0;
        var img = $(this);

        if(img.width() > maxWidth){
            ratio = img.height() / img.width();
            img.attr('width', maxWidth);
            img.attr('height', (maxWidth*ratio));   
        }
    });
});

that will do the magic trick for everyone using latest jquery. Be sure you set your selector right (I used $('img') but that can be different in your case). This only works for landscape mode. But if you look at it, only a few things have to be done to set it to portrait, aka, if img.height() > maxHeight) stuff

How to make a JTable non-editable

If you are creating the TableModel automatically from a set of values (with "new JTable(Vector, Vector)"), perhaps it is easier to remove editors from columns:

JTable table = new JTable(my_rows, my_header);

for (int c = 0; c < table.getColumnCount(); c++)
{
    Class<?> col_class = table.getColumnClass(c);
    table.setDefaultEditor(col_class, null);        // remove editor
}

Without editors, data will be not editable.

Disable all table constraints in Oracle

This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)

WITH qry0 AS
       (SELECT    'ALTER TABLE '
               || child_tname
               || ' DISABLE CONSTRAINT '
               || child_cons_name
                 disable_fk
              ,   'ALTER TABLE '
               || parent_tname
               || ' DISABLE CONSTRAINT '
               || parent.parent_cons_name
                 disable_pk
          FROM (SELECT a.table_name child_tname
                      ,a.constraint_name child_cons_name
                      ,b.r_constraint_name parent_cons_name
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
                GROUP BY a.table_name, a.constraint_name
                        ,b.r_constraint_name) child
              ,(SELECT a.constraint_name parent_cons_name
                      ,a.table_name parent_tname
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
                GROUP BY a.table_name, a.constraint_name) parent
         WHERE child.parent_cons_name = parent.parent_cons_name
           AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
  FROM qry0
UNION
SELECT DISTINCT disable_fk
  FROM qry0;

works like a charm

Visual Studio displaying errors even if projects build

Here's a collection of popular answers. Upvote the OP of the answer if it helped you:

Option 1: Clean, Build and Refresh (@Mike Fuchs option)

As @Mike Fuchs mentioned, try the following operations:

In menu, Build > Clean Solution

And

In menu, Build > Build Solution

and select the project in question, and click on the refresh button:

Refresh Button

Option 2: Clean, Close, Restart and Build (@Pixel option)

As @Pixel mentioned, try the following sequence of operations:

  1. Clean the solution
  2. Close Visual Studio
  3. Open Visual Studio
  4. Build solution

Option 3: Clear ReSharper cache (@GammaOmega option)

If you have ReSharper, try emptying the ReSharper cache:

In menu, ReSharper > Options > Environment > General > Clear Caches

and disabling and re-enabling ReSharper:

In menu, Tools > Options > ReSharper > General > Suspend / Restore

Option 4: Delete the .suo file (@Neolisk option)

As @Neolisk mentioned, deleting the .suo file might solve your problem. For Visual Studio 2015, the file is located in:

[Path of Solution]/.vs/[Solution Name]/v14/.suo

And for Visual Studio 2017:

[Path of Solution]/.vs/[Solution Name]/v15/.suo

Note that the .vs directory is hidden.

Option 5: Unload and Reload Project (@TTT option)

As @TTT mentioned, try unloading the project that causes problems:

In Solution Explorer, right-click on project, Unload Project.

And re-loading it

In Solution Explorer, right-click on project, Reload Project.

Option 6: Remove and add Microsoft.CSharp reference (@Guilherme option)

As @Guilherme mentioned, try removing and adding the reference to "Microsoft.CSharp" from the projects that have problems.

In Solution Explorer, expand the project, expand "References", right-click on "Microsoft.CSharp" and Remove.

Then, right-click on References > Add Reference, select "Microsoft.CSharp" from the list and click OK

Last non-empty cell in a column

Ive tried all the non-volatile versions but Not one version given above has worked.. excel 2003/2007update. Surely this can be done in excel 2003. Not as an array nor standard formula. I either get just a blank, 0 or #value error. So I resort to the volatile methods .. This worked..

=LOOKUP(2,1/(T4:T369<>""),T4:T369)

@Julian Kroné .. Using ";" instead of "," does NOT work! I think you are using Libre Office not MS excel? LOOKUP is so annoyingly volitile I use it as a last resort only

Delayed function calls

This will work either on older versions of .NET
Cons: will execute in its own thread

class CancelableDelay
    {
        Thread delayTh;
        Action action;
        int ms;

        public static CancelableDelay StartAfter(int milliseconds, Action action)
        {
            CancelableDelay result = new CancelableDelay() { ms = milliseconds };
            result.action = action;
            result.delayTh = new Thread(result.Delay);
            result.delayTh.Start();
            return result;
        }

        private CancelableDelay() { }

        void Delay()
        {
            try
            {
                Thread.Sleep(ms);
                action.Invoke();
            }
            catch (ThreadAbortException)
            { }
        }

        public void Cancel() => delayTh.Abort();

    }

Usage:

var job = CancelableDelay.StartAfter(1000, () => { WorkAfter1sec(); });  
job.Cancel(); //to cancel the delayed job

How to get just numeric part of CSS property with jQuery?

Should remove units while preserving decimals.

var regExp = new RegExp("[a-z][A-Z]","g");
parseFloat($(this).css("property").replace(regExp, ""));

How can I get an HTTP response body as a string?

How about just this?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));

How to recursively delete an entire directory with PowerShell 2.0?

Really simple:

remove-item -path <type in file or directory name>, press Enter

CSS background-image - What is the correct usage?

1) putting quotes is a good habit

2) it can be relative path for example:

background-image: url('images/slides/background.jpg');

will look for images folder in the folder from which css is loaded. So if images are in another folder or out of the CSS folder tree you should use absolute path or relative to the root path (starting with /)

3) you should use complete declaration for background-image to make it behave consistently across standards compliant browsers like:

background:blue url('/images/clouds.jpg') no-repeat scroll left center;

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

I encountered this issue in the JetBrains Rider IDE.

Full Error

INSTALL_PARSE_FAILED_NO_CERTIFICATES: Failed to collect certificates from /data/app/vmdl1252907876.tmp/base.apk: Attempt to get length of null array

The problem was a result of using JDK8. Switching to JDK11 solved the issue.

enter image description here

How to Convert Int to Unsigned Byte and Back

The Integer.toString(size) call converts into the char representation of your integer, i.e. the char '5'. The ASCII representation of that character is the value 65.

You need to parse the string back to an integer value first, e.g. by using Integer.parseInt, to get back the original int value.

As a bottom line, for a signed/unsigned conversion, it is best to leave String out of the picture and use bit manipulation as @JB suggests.

Convert form data to JavaScript object with jQuery

I coded a form to a multidimensional JavaScript object myself to use it in production. The result is https://github.com/serbanghita/formToObject.js.

How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

  1. Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.

  2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

CardView Corner Radius

You need to do 2 things :

1) Call setPreventCornerOverlap(false) on your CardView.

2) Put rounded Imageview inside CardView

About rounding your imageview, I had the same problem so I made a library that you can set different radii on each corner. Finally I got the result what I wanted like below.

https://github.com/pungrue26/SelectableRoundedImageView

Rounded ImageView inside CardView

Set an environment variable in git bash

If you want to set environment variables permanently in Git-Bash, you have two options:

  1. Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.

  2. Set up env variables in .bash_profile file.

.bash_profile is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile. You can change the path to the bash home folder by setting HOME Windows environment variable.

.bash_profile file uses the regular Bash syntax and commands

# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir

# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"

Read more information about Bash configurations files.

how to loop through json array in jquery?

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
   alert(data[i].PageName);
});?

$.each(data, function(i, item) {
  alert(item.PageName);
});?

Or else You can try this method

var data = jQuery.parseJSON(response);
$.each(data, function(key,value) {
   alert(value.Id);    //It will shows the Id values
}); 

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

You need to use kill -9 59780 with 59780 replaced with found PID number (use lsof -wni tcp:3000 to see which process used 3000 port and get the process PID).

Or you can just modify your puma config change the tcp port tcp://127.0.0.1:3000 from 3000 to 9292 or other port that not been used.

Or you can start your rails app by using:

bundle exec puma -C config/puma.rb -b tcp://127.0.0.1:3001

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.

String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";


SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);

Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);

This worked. Thanks.

Initializing select with AngularJS and ng-repeat

As suggested you need to use ng-options and unfortunately I believe you need to reference the array element for a default (unless the array is an array of strings).

http://jsfiddle.net/FxM3B/3/

The JavaScript:

function AppCtrl($scope) {


    $scope.operators = [
        {value: 'eq', displayName: 'equals'},
        {value: 'neq', displayName: 'not equal'}
     ]

    $scope.filterCondition={
        operator: $scope.operators[0]
    }
}

The HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator.value}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.displayName for operator in operators">
</select>
</body>

PHP - find entry by object property from an array of objects

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using it the way you wanted would be something like:

ArrayUtils::objArraySearch($array,'ID',$v);

How to access to the parent object in c#

something like this:

  public int PowerRating
    {
       get { return base.PowerRating; } // if power inherits from meter...
    }

How do I center this form in css?

body { text-align: center; }
     /* center all items within body, this property is inherited */
body > * { text-align: left; }
     /* left-align the CONTENTS all items within body, additionally
        you can add this text-align: left property to all elements
        manually */
form { display: inline-block; }
     /* reduces the width of the form to only what is necessary */

?

http://jsfiddle.net/sqdBr/4/

Works & tested in Chrome/IE/FF

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

How to pattern match using regular expression in Scala?

String.matches is the way to do pattern matching in the regex sense.

But as a handy aside, word.firstLetter in real Scala code looks like:

word(0)

Scala treats Strings as a sequence of Char's, so if for some reason you wanted to explicitly get the first character of the String and match it, you could use something like this:

"Cat"(0).toString.matches("[a-cA-C]")
res10: Boolean = true

I'm not proposing this as the general way to do regex pattern matching, but it's in line with your proposed approach to first find the first character of a String and then match it against a regex.

EDIT: To be clear, the way I would do this is, as others have said:

"Cat".matches("^[a-cA-C].*")
res14: Boolean = true

Just wanted to show an example as close as possible to your initial pseudocode. Cheers!

How to enable/disable bluetooth programmatically in android

try this:

//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            // Bluetooth is not enable :)
            return false;
        }
        else{
            return true;
        }

    }

//method to enable bluetooth
    public static void enableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

//method to disable bluetooth
    public static void disableBluetooth(){
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
        }
    }

Add these permissions in manifest

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

What is polymorphism, what is it for, and how is it used?

Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

Here is an example in C#. Create four classes within a console application:

public abstract class Vehicle
{
    public abstract int Wheels;
}

public class Bicycle : Vehicle
{
    public override int Wheels()
    {
        return 2;
    }
}

public class Car : Vehicle
{
    public override int Wheels()
    {
        return 4;
    }
}

public class Truck : Vehicle
{
    public override int Wheels()
    {
        return 18;
    }
}

Now create the following in the Main() of the module for the console application:

public void Main()
{
    List<Vehicle> vehicles = new List<Vehicle>();

    vehicles.Add(new Bicycle());
    vehicles.Add(new Car());
    vehicles.Add(new Truck());

    foreach (Vehicle v in vehicles)
    {
        Console.WriteLine(
            string.Format("A {0} has {1} wheels.",
                v.GetType().Name, v.Wheels));
    }
}

In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.

We then add a Bicycle, Car and Truck to the list.

Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

I hope that this helps you.

How to check if an integer is within a range?

Using comparison operators is way, way faster than calling any function. I'm not 100% sure if this exists, but I think it doesn't.

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

File uploading with Express 4.0: req.files undefined

1) Make sure that your file is really sent from the client side. For example you can check it in Chrome Console: screenshot

2) Here is the basic example of NodeJS backend:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

app.use(fileUpload()); // Don't forget this line!

app.post('/upload', function(req, res) {
   console.log(req.files);
   res.send('UPLOADED!!!');
});

Convert base class to derived class

That's not possible. but you can use an Object Mapper like AutoMapper

Example:

class A
{
    public int IntProp { get; set; }
}
class B
{
    public int IntProp { get; set; }
    public string StrProp { get; set; }
}

In global.asax or application startup:

AutoMapper.Mapper.CreateMap<A, B>();

Usage:

var b = AutoMapper.Mapper.Map<B>(a);

It's easily configurable via a fluent API.

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;
}

django change default runserver port

Actually the easiest way to change (only) port in development Django server is just like:

python manage.py runserver 7000

that should run development server on http://127.0.0.1:7000/

php REQUEST_URI

I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

How do I find ' % ' with the LIKE operator in SQL Server?

I would use

WHERE columnName LIKE '%[%]%'

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'

Shows 457 logical reads for the first query and 33,335 for the second.

Rails 4: how to use $(document).ready() with turbo-links

Tested so many solution finally came to this. This many your code is definitely not called twice.

_x000D_
_x000D_
      var has_loaded=false;_x000D_
      var ready = function() {_x000D_
        if(!has_loaded){_x000D_
          has_loaded=true;_x000D_
           _x000D_
          // YOURJS here_x000D_
        }_x000D_
      }_x000D_
_x000D_
      $(document).ready(ready);_x000D_
      $(document).bind('page:change', ready);
_x000D_
_x000D_
_x000D_

Type Checking: typeof, GetType, or is?

1.

Type t = typeof(obj1);
if (t == typeof(int))

This is illegal, because typeof only works on types, not on variables. I assume obj1 is a variable. So, in this way typeof is static, and does its work at compile time instead of runtime.

2.

if (obj1.GetType() == typeof(int))

This is true if obj1 is exactly of type int. If obj1 derives from int, the if condition will be false.

3.

if (obj1 is int)

This is true if obj1 is an int, or if it derives from a class called int, or if it implements an interface called int.

How to align an image dead center with bootstrap

Twitter Bootstrap v3.0.3 has a class: center-block

Center content blocks

Set an element to display: block and center via margin. Available as a mixin and class.

Just need to add a class .center-block in the img tag, looks like this

<div class="container">
  <div class="row">
    <div class="span4"></div>
    <div class="span4"><img class="center-block" src="logo.png" /></div>
    <div class="span4"></div>
  </div>
</div>

In Bootstrap already has css style call .center-block

.center-block {
    display: block;
    margin-left: auto;
    margin-right: auto;
 }

You can see a sample from here

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

I used this approach to perform the same operation in my app.

var varDate = $("#dateStart").val(); 

var DateinISO = $.datepicker.parseDate('mm/dd/yy', varDate); 

var DateNewFormat = $.datepicker.formatDate( "yy-mm-dd", new Date( DateinISO ) );

$("#dateStartNewFormat").val(DateNewFormat);

CSS3 transform: rotate; in IE9

I also had problems with transformations in IE9, I used -ms-transform: rotate(10deg) and it didn't work. Tried everything I could, but the problem was in browser mode, to make transformations work, you need to set compatibility mode to "Standard IE9".

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));

Interactive shell using Docker Compose

You need to include the following lines in your docker-compose.yml:

version: "3"
services:
  app:
    image: app:1.2.3
    stdin_open: true # docker run -i
    tty: true        # docker run -t

The first corresponds to -i in docker run and the second to -t.

scale Image in an UIButton to AspectFit?

This can now be done through IB's UIButton properties. The key is to set your image as a the background, otherwise it won't work.

enter image description here

How to write one new line in Bitbucket markdown?

It's possible, as addressed in Issue #7396:

When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return or Enter.

Multiple glibc libraries on a single host

This question is old, the other answers are old. "Employed Russian"s answer is very good and informative, but it only works if you have the source code. If you don't, the alternatives back then were very tricky. Fortunately nowadays we have a simple solution to this problem (as commented in one of his replies), using patchelf. All you have to do is:

$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 --set-rpath /path/to/newglibc/ myapp

And after that, you can just execute your file:

$ ./myapp

No need to chroot or manually edit binaries, thankfully. But remember to backup your binary before patching it, if you're not sure what you're doing, because it modifies your binary file. After you patch it, you can't restore the old path to interpreter/rpath. If it doesn't work, you'll have to keep patching it until you find the path that will actually work... Well, it doesn't have to be a trial-and-error process. For example, in OP's example, he needed GLIBC_2.3, so you can easily find which lib provides that version using strings:

$ strings /lib/i686/libc.so.6 | grep GLIBC_2.3
$ strings /path/to/newglib/libc.so.6 | grep GLIBC_2.3

In theory, the first grep would come empty because the system libc doesn't have the version he wants, and the 2nd one should output GLIBC_2.3 because it has the version myapp is using, so we know we can patchelf our binary using that path. If you get a segmentation fault, read the note at the end.

When you try to run a binary in linux, the binary tries to load the linker, then the libraries, and they should all be in the path and/or in the right place. If your problem is with the linker and you want to find out which path your binary is looking for, you can find out with this command:

$ readelf -l myapp | grep interpreter
  [Requesting program interpreter: /lib/ld-linux.so.2]                                                                                                                                                                                   

If your problem is with the libs, commands that will give you the libs being used are:

$ readelf -d myapp | grep Shared
$ ldd myapp 

This will list the libs that your binary needs, but you probably already know the problematic ones, since they are already yielding errors as in OP's case.

"patchelf" works for many different problems that you may encounter while trying to run a program, related to these 2 problems. For example, if you get: ELF file OS ABI invalid, it may be fixed by setting a new loader (the --set-interpreter part of the command) as I explain here. Another example is for the problem of getting No such file or directory when you run a file that is there and executable, as exemplified here. In that particular case, OP was missing a link to the loader, but maybe in your case you don't have root access and can't create the link. Setting a new interpreter would solve your problem.

Thanks Employed Russian and Michael Pankov for the insight and solution!


Note for segmentation fault: you might be in the case where myapp uses several libs, and most of them are ok but some are not; then you patchelf it to a new dir, and you get segmentation fault. When you patchelf your binary, you change the path of several libs, even if some were originally in a different path. Take a look at my example below:

$ ldd myapp
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by ./myapp)
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./myapp)
        linux-vdso.so.1 =>  (0x00007fffb167c000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9a9aad2000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a9a8ce000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a9a6af000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9a9a3ab000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a99fe6000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f9a9adeb000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9a99dcf000)

Note that most libs are in /lib/x86_64-linux-gnu/ but the problematic one (libstdc++.so.6) is on /usr/lib/x86_64-linux-gnu. After I patchelf'ed myapp to point to /path/to/mylibs, I got segmentation fault. For some reason, the libs are not totally compatible with the binary. Since myapp didn't complain about the original libs, I copied them from /lib/x86_64-linux-gnu/ to /path/to/mylibs2, and I also copied libstdc++.so.6 from /path/to/mylibs there. Then I patchelf'ed it to /path/to/mylibs2, and myapp works now. If your binary uses different libs, and you have different versions, it might happen that you can't fix your situation. :( But if it's possible, mixing libs might be the way. It's not ideal, but maybe it will work. Good luck!

WPF Button with Image

<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top"  Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
    <StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
        <Image HorizontalAlignment="Left"  Source="image/bg/Save.png" Height="36" Width="124" />
        <TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
    </StackPanel>
</Button>

Write string to output stream

You may use Apache Commons IO:

try (OutputStream outputStream = ...) {
    IOUtils.write("data", outputStream, "UTF-8");
}

Remove leading zeros from a number in Javascript

regexp:

"014".replace(/^0+/, '')

Bulk Insert to Oracle using .NET

The solution of Rob Stevenson-Legget is slow because he doesn't bind his values but he uses string.Format( ).

When you ask Oracle to execute a sql statement it starts with calculating the has value of this statement. After that it looks in a hash table whether it already knows this statement. If it already knows it statement it can retrieve its execution path from this hash table and execute this statement really fast because Oracle has executed this statement before. This is called the library cache and it doesn't work properly if you don't bind your sql statements.

For example don't do:

int n;

    for (n = 0; n < 100000; n ++)
    {
      mycommand.CommandText = String.Format("INSERT INTO [MyTable] ([MyId]) VALUES({0})", n + 1);
      mycommand.ExecuteNonQuery();
    }

but do:

      OracleParameter myparam = new OracleParameter();
      int n;

      mycommand.CommandText = "INSERT INTO [MyTable] ([MyId]) VALUES(?)";
      mycommand.Parameters.Add(myparam);

      for (n = 0; n < 100000; n ++)
      {
        myparam.Value = n + 1;
        mycommand.ExecuteNonQuery();
      }

Not using parameters can also cause sql injection.

How to define a variable in a Dockerfile?

You can use ARG - see https://docs.docker.com/engine/reference/builder/#arg

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

Send mail via Gmail with PowerShell V2's Send-MailMessage

Here it is:

$filename = “c:\scripts_scott\test9999.xls”
$smtpserver = “smtp.gmail.com”
$msg = New-Object Net.Mail.MailMessage
$att = New-Object Net.Mail.Attachment($filename)
$smtp = New-Object Net.Mail.SmtpClient($smtpServer )
$smtp.EnableSsl = $True
$smtp.Credentials = New-Object System.Net.NetworkCredential(“username”, “password_here”); # Put username without the @GMAIL.com or – @gmail.com
$msg.From = “[email protected]”
$msg.To.Add(”[email protected]”)
$msg.Subject = “Monthly Report”
$msg.Body = “Good MorningATTACHED”
$msg.Attachments.Add($att)
$smtp.Send($msg)

Let me know if it helps you San. Also use the send-mailmessage also at Www.techjunkie.tv

For that way also that I think is way better and pure to use.

How to print to console using swift playground?

for displaying variables only in playground, just mention the variable name without anything

let stat = 100

stat // this outputs the value of stat on playground right window

How to have Android Service communicate with Activity

You may also use LiveData that works like an EventBus.

class MyService : LifecycleService() {
    companion object {
        val BUS = MutableLiveData<Any>()
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        val testItem : Object

        // expose your data
        if (BUS.hasActiveObservers()) {
            BUS.postValue(testItem)
        }

        return START_NOT_STICKY
    }
}

Then add an observer from your Activity.

MyService.BUS.observe(this, Observer {
    it?.let {
        // Do what you need to do here
    }
})

You can read more from this blog.

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Show image using file_get_contents

You can use readfile and output the image headers which you can get from getimagesize like this:

$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);

The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.

Visual Studio: Relative Assembly References Paths

In VS 2017 it is automatic. So just Add Reference as usually.

Note that in Reference Properties absolute path is shown, but in .vbproj/.csproj relative is used.

<Reference Include="NETnetworkmanager">
      <HintPath>..\..\libs\NETnetworkmanager.dll</HintPath>
      <EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>

check if variable empty

empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:

if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}

How do I get the current date and time in PHP?

If you want to get the date like 12-3-2016, separate each day, month, and year value, then copy-paste this code:

$day = date("d");
$month = date("m");
$year = date("y");
print "date" . $day . "-" . $month . "-" . $year;

What is the id( ) function used for?

I'm a little bit late and i will talk about Python3. To understand what id() is and how it (and Python) works, consider next example:

>>> x=1000
>>> y=1000
>>> id(x)==id(y)
False
>>> id(x)
4312240944
>>> id(y)
4312240912
>>> id(1000)
4312241104
>>> x=1000
>>> id(x)
4312241104
>>> y=1000
>>> id(y)
4312241200

You need to think about everything on the right side as objects. Every time you make assignment - you create new object and that means new id. In the middle you can see a "wild" object which is created only for function - id(1000). So, it's lifetime is only for that line of code. If you check the next line - you see that when we create new variable x, it has the same id as that wild object. Pretty much it works like memory address.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

For me only installing from Google drive worked.

How to develop Android app completely using python?

There are two primary contenders for python apps on Android

Chaquopy

https://chaquo.com/chaquopy/

This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

https://pybee.org/

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

convert nan value to zero

For your purposes, if all the items are stored as str and you just use sorted as you are using and then check for the first element and replace it with '0'

>>> l1 = ['88','NaN','67','89','81']
>>> n = sorted(l1,reverse=True)
['NaN', '89', '88', '81', '67']
>>> import math
>>> if math.isnan(float(n[0])):
...     n[0] = '0'
... 
>>> n
['0', '89', '88', '81', '67']

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

How to trigger a file download when clicking an HTML button or JavaScript

Old thread but it's missing a simple js solution:

let a = document.createElement('a')
a.href = item.url
a.download = item.url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

Find where java class is loaded from

This is what we use:

public static String getClassResource(Class<?> klass) {
  return klass.getClassLoader().getResource(
     klass.getName().replace('.', '/') + ".class").toString();
}

This will work depending on the ClassLoader implementation: getClass().getProtectionDomain().getCodeSource().getLocation()

Convert Enum to String

I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.

Java system properties and environment variables

How can I verify if one list is a subset of another?

Here is how I know if one list is a subset of another one, the sequence matters to me in my case.

def is_subset(list_long,list_short):
    short_length = len(list_short)
    subset_list = []
    for i in range(len(list_long)-short_length+1):
        subset_list.append(list_long[i:i+short_length])
    if list_short in subset_list:
        return True
    else: return False

use std::fill to populate vector with increasing numbers

My first choice (even in C++11) would be boost::counting_iterator :

std::vector<int> ivec( boost::counting_iterator<int>( 0 ),
                       boost::counting_iterator<int>( n ) );

or if the vector was already constructed:

std::copy( boost::counting_iterator<int>( 0 ),
           boost::counting_iterator<int>( ivec.size() ),
           ivec.begin() );

If you can't use Boost: either std::generate (as suggested in other answers), or implement counting_iterator yourself, if you need it in various places. (With Boost, you can use a transform_iterator of a counting_iterator to create all sorts of interesting sequences. Without Boost, you can do a lot of this by hand, either in the form of a generator object type for std::generate, or as something you can plug into a hand written counting iterator.)

CSS how to make an element fade in and then fade out?

Try this:

@keyframes animationName {
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-o-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-moz-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}
@-webkit-keyframes animationName{
  0%   { opacity:0; }
  50%  { opacity:1; }
  100% { opacity:0; }
}   
.elementToFadeInAndOut {
   -webkit-animation: animationName 5s infinite;
   -moz-animation: animationName 5s infinite;
   -o-animation: animationName 5s infinite;
    animation: animationName 5s infinite;
}

C# - Simplest way to remove first occurrence of a substring from another string

You could use an extension method for fun. Typically I don't recommend attaching extension methods to such a general purpose class like string, but like I said this is fun. I borrowed @Luke's answer since there is no point in re-inventing the wheel.

[Test]
public void Should_remove_first_occurrance_of_string() {

    var source = "ProjectName\\Iteration\\Release1\\Iteration1";

    Assert.That(
        source.RemoveFirst("\\Iteration"),
        Is.EqualTo("ProjectName\\Release1\\Iteration1"));
}

public static class StringExtensions {
    public static string RemoveFirst(this string source, string remove) {
        int index = source.IndexOf(remove);
        return (index < 0)
            ? source
            : source.Remove(index, remove.Length);
    }
}

jQuery & CSS - Remove/Add display:none

For some reason, toggle didn't work for me, and I received the error uncaught type error toggle is not a function when inspecting the element in browser. So I used the following code and it started working for me.

$(".trigger").click(function () {
    $('.news').attr('style', 'display:none');
})

Used jquery script file jquery-2.1.3.min.js.

How to set the value for Radio Buttons When edit?

This is easier to read for me:

<input type="radio" name="rWF" id="rWF" value=1  <?php if ($WF == '1') {echo ' checked ';} ?> />Water Fall</label>
<input type="radio" name="rWF" id="rWF" value=0 <?php if ($WF == '0') {echo ' checked ';} ?> />nope</label>

How to draw checkbox or tick mark in GitHub Markdown table?

You can use emojis

Done? | Name
:---:| ---
??| Nope
?| Yep

How to convert a huge list-of-vector to a matrix more efficiently?

I think you want

output <- do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))

i.e. combining @BlueMagister's use of do.call(rbind,...) with an lapply statement to convert the individual list elements into 11*10 matrices ...

Benchmarks (showing @flodel's unlist solution is 5x faster than mine, and 230x faster than the original approach ...)

n <- 1000
z <- replicate(n,matrix(1:110,ncol=10,byrow=TRUE),simplify=FALSE)
library(rbenchmark)
origfn <- function(z) {
    output <- NULL 
    for(i in 1:length(z))
        output<- rbind(output,matrix(z[[i]],ncol=10,byrow=TRUE))
}
rbindfn <- function(z) do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
unlistfn <- function(z) matrix(unlist(z), ncol = 10, byrow = TRUE)

##          test replications elapsed relative user.self sys.self 
## 1   origfn(z)          100  36.467  230.804    34.834    1.540  
## 2  rbindfn(z)          100   0.713    4.513     0.708    0.012 
## 3 unlistfn(z)          100   0.158    1.000     0.144    0.008 

If this scales appropriately (i.e. you don't run into memory problems), the full problem would take about 130*0.2 seconds = 26 seconds on a comparable machine (I did this on a 2-year-old MacBook Pro).

How can I compare two lists in python and return matches

Do you want duplicates? If not maybe you should use sets instead:

>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
set([5])

Will using 'var' affect performance?

So, to be clear, it's a lazy coding style. I prefer native types, given the choice; I'll take that extra bit of "noise" to ensure I'm writing and reading exactly what I think I am at code/debug time. * shrug *

XPath to select multiple tags

Not sure if this helps, but with XSL, I'd do something like:

<xsl:for-each select="a/b">
    <xsl:value-of select="c"/>
    <xsl:value-of select="d"/>
    <xsl:value-of select="e"/>
</xsl:for-each>

and won't this XPath select all children of B nodes:

a/b/*

How to sum data.frame column values?

When you have 'NA' values in the column, then

sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)

Convert JSONObject to Map

The best way to convert it to HashMap<String, Object> is this:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));

How can I create a text box for a note in markdown?

What I usually do for putting alert box (e.g. Note or Warning) in markdown texts (not only when using pandoc but also every where that markdown is supported) is surrounding the content with two horizontal lines:

---
**NOTE**

It works with almost all markdown flavours (the below blank line matters).

---

which would be something like this:


NOTE

It works with all markdown flavours (the below blank line matters).


The good thing is that you don't need to worry about which markdown flavour is supported or which extension is installed or enabled.

EDIT: As @filups21 has mentioned in the comments, it seems that a horizontal line is represented by *** in RMarkdown. So, the solution mentioned before does not work with all markdown flavours as it was originally claimed.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had tried uninstalling and then installing "Microsoft Access Database Engine 2010 (English) several times and finally the comment - "Changed option from ANY CPU to x86" and it worked.

Thanks for that comment - I am now back in business after 2 weeks of frustration.

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

How to play videos in android from assets folder or raw folder?

VideoView myVideo = (VideoView) rootView.findViewById(R.id.definition_video_view);

//Set video name (no extension)
String myVideoName = "my_video";

//Set app package
String myAppPackage = "com.myapp";

//Get video URI from raw directory
Uri myVideoUri = Uri.parse("android.resource://"+myAppPackage+"/raw/"+myVideoName);

//Set the video URI
myVideo.setVideoURI(myVideoUri);

//Play the video
myVideo.start();

https://gist.github.com/jrejaud/b5eb1b013c27a1f3ae5f

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

Variable number of arguments in C++?

Using variadic templates, example to reproduce console.log as seen in JavaScript:

Console console;
console.log("bunch", "of", "arguments");
console.warn("or some numbers:", 1, 2, 3);
console.error("just a prank", "bro");

Filename e.g. js_console.h:

#include <iostream>
#include <utility>

class Console {
protected:
    template <typename T>
    void log_argument(T t) {
        std::cout << t << " ";
    }
public:
    template <typename... Args>
    void log(Args&&... args) {
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void warn(Args&&... args) {
        cout << "WARNING: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void error(Args&&... args) {
        cout << "ERROR: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }
};

Exception.Message vs Exception.ToString()

I'd say @Wim is right. You should use ToString() for logfiles - assuming a technical audience - and Message, if at all, to display to the user. One could argue that even that is not suitable for a user, for every exception type and occurance out there (think of ArgumentExceptions, etc.).

Also, in addition to the StackTrace, ToString() will include information you will not get otherwise. For example the output of fusion, if enabled to include log messages in exception "messages".

Some exception types even include additional information (for example from custom properties) in ToString(), but not in the Message.

How to import JSON File into a TypeScript file?

As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:

  1. Add those three lines to compilerOptions in your tsconfig.json file:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
  1. Import your json data:
import myData from '../assets/data/my-data.json';

And that's it. You can now use myDatain your components/services.

Compare two date formats in javascript/jquery

try with new Date(obj).getTime()

if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
{
    alert(fit_start_time + " is greater."); // your code
}
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
{
    alert(fit_end_time + " is greater."); // your code
}
else
{
    alert("both are same!"); // your code
}

How to convert an IPv4 address into a integer in C#?

@Davy Ladman your solution with shift are corrent but only for ip starting with number less or equal 99, infact first octect must be cast up to long.

Anyway convert back with long type is quite difficult because store 64 bit (not 32 for Ip) and fill 4 bytes with zeroes

static uint ToInt(string addr)
{
   return BitConverter.ToUInt32(IPAddress.Parse(addr).GetAddressBytes(), 0);
}

static string ToAddr(uint address)
{
    return new IPAddress(address).ToString();
}

Enjoy!

Massimo

How to make div follow scrolling smoothly with jQuery?

This one is same on facebook:

_x000D_
_x000D_
<script>_x000D_
var valX = $(window).scrollTop();_x000D_
function syncScroll(target){_x000D_
 var valY = $(window).scrollTop();_x000D_
 var difYX = valY - valX;_x000D_
 var targetX = $(target).scrollTop();_x000D_
 if(valY > valX){_x000D_
  $(target).scrollTop(difYX);_x000D_
 }_x000D_
 if(difYX <= 0){_x000D_
  $(target).scrollTop(-20);_x000D_
 }_x000D_
}_x000D_
_x000D_
$(window).scroll(function(){_x000D_
 syncScroll('#demo');_x000D_
})_x000D_
</script>
_x000D_
body{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
}_x000D_
#demo{_x000D_
  position:fixed;_x000D_
  height:100vh;_x000D_
  overflow:hidden;_x000D_
  width:40%;_x000D_
}_x000D_
#content{_x000D_
  position:relative;_x000D_
  float:right;_x000D_
  width:60%;_x000D_
  color:red; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <div id="demo">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
  </div>_x000D_
  <div id="content">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
   </div>   _x000D_
</body
_x000D_
_x000D_
_x000D_

is it possible to update UIButton title/text programmatically?

One more possible cause is this:

If you attempt to set the button's title in the (id)initWithNibName: ... method, then you're button property will still be nil. It hasn't yet been assigned to the UIButton.

You must be sure that you're setting your buttons in a method like (void)viewWillLoad or (void)viewWillAppear, but you probably don't want to set them as late as (void)viewDidAppear.

How to test a variable is null in python

try:
    if val is None: # The variable
        print('It is None')
except NameError:
    print ("This variable is not defined")
else:
    print ("It is defined and has a value")

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

Random "Element is no longer attached to the DOM" StaleElementReferenceException

Just happened to me when trying to send_keys to a search input box - that has autoupdate depending on what you type in. As mentioned by Eero, this can happen if your element does some Ajax updated while you are typing in your text inside the input element. The solution is to send one character at a time and search again for the input element. (Ex. in ruby shown below)

def send_keys_eachchar(webdriver, elem_locator, text_to_send)
  text_to_send.each_char do |char|
    input_elem = webdriver.find_element(elem_locator)
    input_elem.send_keys(char)
  end
end

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

graphing an equation with matplotlib

Your guess is right: the code is trying to evaluate x**3+2*x-4 immediately. Unfortunately you can't really prevent it from doing so. The good news is that in Python, functions are first-class objects, by which I mean that you can treat them like any other variable. So to fix your function, we could do:

import numpy as np  
import matplotlib.pyplot as plt  

def graph(formula, x_range):  
    x = np.array(x_range)  
    y = formula(x)  # <- note now we're calling the function 'formula' with x
    plt.plot(x, y)  
    plt.show()  

def my_formula(x):
    return x**3+2*x-4

graph(my_formula, range(-10, 11))

If you wanted to do it all in one line, you could use what's called a lambda function, which is just a short function without a name where you don't use def or return:

graph(lambda x: x**3+2*x-4, range(-10, 11))

And instead of range, you can look at np.arange (which allows for non-integer increments), and np.linspace, which allows you to specify the start, stop, and the number of points to use.

How do I edit $PATH (.bash_profile) on OSX?

Determine which shell you're using by typing echo $SHELL in Terminal.

Then open/create correct rc file. For Bash it's $HOME/.bash_profile or $HOME/.bashrc. For Z shell it's $HOME/.zshrc.

Add this line to the file end:

export PATH="$PATH:/your/new/path"

To verify, refresh variables by restarting Terminal or typing source $HOME/.<rc file> and then do echo $PATH

How to run a hello.js file in Node.js on windows?

The problem was that you opened the Node.js repl while everyone automatically assumed you were in the command prompt. For what it's worth you can run a javascript file from the repl with the .load command. For example:

.load c:/users/username/documents/script.js

The same command can also be used in the command prompt if you first start node inside the command prompt by entering node with no arguments (assuming node is in PATH).

I find it fascinating that 1)everyone assumed you were in the command prompt rather than repl, 2)no one seems to know about .load, and 3)this has 273 upvotes, proving that a lot of other node.js beginners are similarly confused.

how to stop a loop arduino

The three options that come to mind:

1st) End void loop() with while(1)... or equally as good... while(true)

void loop(){
    //the code you want to run once here, 
    //e.g., If (blah == blah)...etc.

    while(1)        //last line of main loop
}

This option runs your code once and then kicks the Ard into an endless "invisible" loop. Perhaps not the nicest way to go, but as far as outside appearances, it gets the job done.
The Ard will continue to draw current while it spins itself in an endless circle... perhaps one could set up a sort of timer function that puts the Ard to sleep after so many seconds, minutes, etc., of looping... just a thought... there are certainly various sleep libraries out there... see e.g., Monk, Programming Arduino: Next Steps, pgs., 85-100 for further discussion of such.

2nd) Create a "stop main loop" function with a conditional control structure that makes its initial test fail on a second pass.
This often requires declaring a global variable and having the "stop main loop" function toggle the value of the variable upon termination. E.g.,

boolean stop_it = false;         //global variable

void setup(){
    Serial.begin(9600); 
    //blah...
}

boolean stop_main_loop(){        //fancy stop main loop function

    if(stop_it == false){   //which it will be the first time through

        Serial.println("This should print once.");

       //then do some more blah....you can locate all the
       // code you want to run once here....eventually end by 
       //toggling the "stop_it" variable ... 
    }
    stop_it = true; //...like this
    return stop_it;   //then send this newly updated "stop_it" value
                     // outside the function
}

void loop{ 

    stop_it = stop_main_loop();     //and finally catch that updated 
                                    //value and store it in the global stop_it 
                                    //variable, effectively 
                                    //halting the loop  ...
}

Granted, this might not be especially pretty, but it also works.
It kicks the Ard into another endless "invisible" loop, but this time it's a case of repeatedly checking the if(stop_it == false) condition in stop_main_loop() which of course fails to pass every time after the first time through.

3rd) One could once again use a global variable but use a simple if (test == blah){} structure instead of a fancy "stop main loop" function.

boolean start = true;                  //global variable

void setup(){

      Serial.begin(9600);
}

void loop(){

      if(start == true){           //which it will be the first time through



           Serial.println("This should print once.");       

           //the code you want to run once here, 
           //e.g., more If (blah == blah)...etc.

     }

start = false;                //toggle value of global "start" variable
                              //Next time around, the if test is sure to fail.
}

There are certainly other ways to "stop" that pesky endless main loop but these three as well as those already mentioned should get you started.

How to switch databases in psql?

You can select the database when connecting with psql. This is handy when using it from a script:

sudo -u postgres psql -c "CREATE SCHEMA test AUTHORIZATION test;" test

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

Add following codesnippet in your cofig file

<startup useLegacyV2RuntimeActivationPolicy="true">
   <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

When to use IMG vs. CSS background-image?

In regards to animating images using CSS TranslateX/Y (The proper way to animate html) - If you do a Chrome Timeline recording of CSS background-images being animated vs IMG tags being animated you will see the paint times are drastically shorter for the CSS background-images.

How to execute XPath one-liners from shell?

Sorry to be yet another voice in the fray. I tried all the tools in this thread and found none of them to be satisfactory for my needs, so I wrote my own. You can find it here: https://github.com/charmparticle/xpe

It's been uploaded to pypi, so you can easily install it with pip3 like so:

sudo pip3 install xpe

Once installed, you can use it to run xpath expressions against various kinds of input with the same level of flexibility you would get from using xpaths in selenium or javascript. Yeah, you can use xpaths against HTML with this. One caviat: if you run it against xml that has the encoding specified on the first line, it will fail. The solution for now is to pipe it to sed to remove the first line like so:

cat specified_encoding.xml | sed '1d' | xpe '//text()'

I may post an update at some point to address this issue to avoid the need for sed.

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

How do I decompile a .NET EXE into readable C# source code?

Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.

ADDED: My latest favourite is JetBrains' dotPeek.

SQL Query - how do filter by null or not null

Wherever you are trying to check NULL value of a column, you should use

IS NULL and IS NOT NULL

You should not use =NULL or ==NULL


Example(NULL)

select * from user_registration where registered_time IS NULL 

will return the rows with registered_time value is NULL


Example(NOT NULL)

select * from user_registration where registered_time IS NOT NULL 

will return the rows with registered_time value is NOT NULL

Note: The keyword null, not null and is are not case sensitive.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Are arrays passed by value or passed by reference in Java?

Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:

// assuming you allocated the list
public void addItem(Integer[] list, int item) {
    list[1] = item;
}

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:

// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.

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

I had to disable the File Publish Option "Precompile during publishing."

Accessing Session Using ASP.NET Web API

I had this same problem in asp.net mvc, I fixed it by putting this method in my base api controller that all my api controllers inherit from:

    /// <summary>
    /// Get the session from HttpContext.Current, if that is null try to get it from the Request properties.
    /// </summary>
    /// <returns></returns>
    protected HttpContextWrapper GetHttpContextWrapper()
    {
      HttpContextWrapper httpContextWrapper = null;
      if (HttpContext.Current != null)
      {
        httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
      }
      else if (Request.Properties.ContainsKey("MS_HttpContext"))
      {
        httpContextWrapper = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
      }
      return httpContextWrapper;
    }

Then in your api call that you want to access the session you just do:

HttpContextWrapper httpContextWrapper = GetHttpContextWrapper();
var someVariableFromSession = httpContextWrapper.Session["SomeSessionValue"];

I also have this in my Global.asax.cs file like other people have posted, not sure if you still need it using the method above, but here it is just in case:

/// <summary>
/// The following method makes Session available.
/// </summary>
protected void Application_PostAuthorizeRequest()
{
  if (HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api"))
  {
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
  }
}

You could also just make a custom filter attribute that you can stick on your api calls that you need session, then you can use session in your api call like you normally would via HttpContext.Current.Session["SomeValue"]:

  /// <summary>
  /// Filter that gets session context from request if HttpContext.Current is null.
  /// </summary>
  public class RequireSessionAttribute : ActionFilterAttribute
  {
    /// <summary>
    /// Runs before action
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
      if (HttpContext.Current == null)
      {
        if (actionContext.Request.Properties.ContainsKey("MS_HttpContext"))
        {
          HttpContext.Current = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).ApplicationInstance.Context;
        }
      }
    }
  }

Hope this helps.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I also faced the following Error in my system (Mac)

Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

After doing some random browsing, I came across the link "http://maven.apache.org/install.html" that says "JAVA_HOME" should be set to "/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre".

When I changed "JAVA_HOME" as stated above in ".bash_profile", "mvn" command started working but "javac -version" command stopped working.

When I typed "javac -version" command, I got the following error

Unable to locate an executable at "/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/javac" (-1)

Hence I rolled back my "JAVA_HOME" to "/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home" in ".bash_profile" and added the following line at the top in "mvn" script

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre

Now both "mvn" and "javac" commands worked properly, but after careful observation of the mvn script, I could not make the difference between the following commands

/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java -classpath /Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/boot/plexus-classworlds-2.6.0.jar -Dclassworlds.conf=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin/m2.conf -Dmaven.home=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1 -Dlibrary.jansi.path=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/lib/jansi-native -Dmaven.multiModuleProjectDirectory=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin org.codehaus.plexus.classworlds.launcher.Launcher

/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/bin/java -classpath /Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/boot/plexus-classworlds-2.6.0.jar -Dclassworlds.conf=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin/m2.conf -Dmaven.home=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1 -Dlibrary.jansi.path=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/lib/jansi-native -Dmaven.multiModuleProjectDirectory=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1/bin org.codehaus.plexus.classworlds.launcher.Launcher

In the above the first command caused the following error

Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

while the second command worked fine. Please Note that both the above paths have "java" command while one is from "jre" the other is from "jdk"

Other global variables are as following in ".bash_profile"

export M2_HOME=/Users/venkatarajeevmandava/Documents/Maven/apache-maven-3.6.1

export PATH=$PATH:$M2_HOME/bin

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

I had same issue in Android Studio 3. (the project was open) so I closed the current project and the IDE automatically prompted to download the latest components. once its done everything was working correctly.

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

Javascript Error Null is not an Object

Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.

So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.

Then you can add an event listener for document load to execute the function.

That will give you something like:

<script>
  function init() {
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");
    myButton.onclick = function() {
      var userName = myTextfield.value;
      greetUser(userName);
    }
  }

  function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
  }

  document.addEventListener('readystatechange', function() {
    if (document.readyState === "complete") {
      init();
    }
  });

</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="button" id="myButton" value="Go" />
</form>

Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/

How to download files using axios

It's very simple javascript code to trigger a download for the user:

window.open("<insert URL here>")

You don't want/need axios for this operation; it should be standard to just let the browser do it's thing.

Note: If you need authorisation for the download then this might not work. I'm pretty sure you can use cookies to authorise a request like this, provided it's within the same domain, but regardless, this might not work immediately in such a case.


As for whether it's possible... not with the in-built file downloading mechanism, no.

Adding a simple spacer to twitter bootstrap

In Bootstrap 4 you can use classes like mt-5, mb-5, my-5, mx-5 (y for both top and bottom, x for both left and right).

According to their site:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Link: https://getbootstrap.com/docs/4.0/utilities/spacing/

How to write specific CSS for mozilla, chrome and IE

use agent detector and then with your web language create program to create css

for example in python

csscreator()
    useragent = detector()
    if useragent == "Firefox":
         css = "your css"
    ...
    return css

Oracle insert from select into table with more columns

Just add in the '0' in your select.

INSERT INTO table_name (a,b,c,d)
    SELECT
       other_table.a AS a,
       other_table.b AS b,
       other_table.c AS c,
       '0' AS d
    FROM other_table

Rails 3: I want to list all paths defined in my rails application

Update

I later found that, there is an official way to see all the routes, by going to http://localhost:3000/rails/info/routes. Official docs: https://guides.rubyonrails.org/routing.html#listing-existing-routes


Though, it may be late, But I love the error page which displays all the routes. I usually try to go at /routes (or some bogus) path directly from the browser. Rails server automatically gives me a routing error page as well as all the routes and paths defined. That was very helpful :)

So, Just go to http://localhost:3000/routes enter image description here

How do I get the unix timestamp in C as an int?

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}

Are one-line 'if'/'for'-statements good Python style?

Dive into python has a bit where he talks about what he calls the and-or trick, which seems like an effective way to cram complex logic into a single line.

Basically, it simulates the ternary operater in c, by giving you a way to test for truth and return a value based on that. For example:

>>> (1 and ["firstvalue"] or ["secondvalue"])[0]
"firstvalue"
>>> (0 and ["firstvalue"] or ["secondvalue"])[0]
"secondvalue"