Programs & Examples On #Itemtemplate

A WPF/Xaml DataTemplate used to display each item in an ItemsControl.

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

Gridview get Checkbox.Checked value

If you want a method other than findcontrol try the following:

 GridViewRow row = Gridview1.SelectedRow;
 int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
 CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

How to get row data by clicking a button in a row in an ASP.NET gridview

Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.

Mark up

<asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
   <asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
    ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit" 
    CausesValidation="False"  />

      </ItemTemplate>

         <EditItemTemplate>

                    <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" 
                        Text="Update"  Visible="true" ImageUrl="~/images/saveHS.png" 
                        />
                   <asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"   
                        ImageUrl="~/images/Edit_UndoHS.png"  />

                 <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"   
                        ImageUrl="~/images/delete.png"  />

             </EditItemTemplate>


        <ControlStyle BackColor="Transparent" BorderStyle="None" />
               <FooterStyle HorizontalAlign="Center" />
           <ItemStyle HorizontalAlign="Center" />
       </asp:TemplateField>

Code behind

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataBind();

TextBox txtledName =   (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");

 //then do something with the retrieved textbox's text.

}

How to delete row in gridview using rowdeleting event?

If I remember from your previous questions, you're binding to a DataTable. Try this:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    DataTable sourceData = (DataTable)GridView1.DataSource;

    sourceData.Rows[e.RowIndex].Delete();

    GridVie1.DataSource = sourceData;
    GridView1.DataBind();
}

Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.

How to find Control in TemplateField of GridView?

I have done it accessing the controls inside the cell control. Find in all control collections.

 ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;

 Label lbCod = (Label)cc[1];

Get Row Index on Asp.net Rowcommand event

Or, you can use a control class instead of their types:

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

int RowIndex = row.RowIndex; 

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

How to hide a TemplateField column in a GridView

GridView1.Columns[columnIndex].Visible = false;

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

  1. Create / Purchase certificate. Make sure it has a private key.
  2. Import the certificate into the "Local Computer" account. Best to use Certificates MMC. Make sure to check "Allow private key to be exported"
  3. Based upon which, IIS 7.5 Application Pool's identity use one of the following.

    • IIS 7.5 Website is running under ApplicationPoolIdentity. Open MMC => Add Certificates (Local computer) snap-in => Certificates (Local Computer) => Personal => Certificates => Right click the certificate of interest => All tasks => Manage private key => Add IIS AppPool\AppPoolName and grant it Full control. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS)
    • IIS 7.5 Website is running under NETWORK SERVICE. Using Certificates MMC, added "NETWORK SERVICE" to Full Trust on certificate in "Local Computer\Personal".
    • IIS 7.5 Website is running under "MyIISUser" local computer user account. Using Certificates MMC, added "MyIISUser" (a new local computer user account) to Full Trust on certificate in "Local Computer\Personal".

Update based upon @Phil Hale comment:

Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.

Change background color for selected ListBox item

You have to create a new template for item selection like this.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
            <Border
                BorderThickness="{TemplateBinding Border.BorderThickness}"
                Padding="{TemplateBinding Control.Padding}"
                BorderBrush="{TemplateBinding Border.BorderBrush}"
                Background="{TemplateBinding Panel.Background}"
                SnapsToDevicePixels="True">
                <ContentPresenter
                    Content="{TemplateBinding ContentControl.Content}"
                    ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                    HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                    VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
                    SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

WPF binding to Listbox selectedItem

Yocoder is right,

Inside the DataTemplate, your DataContext is set to the Rule its currently handling..

To access the parents DataContext, you can also consider using a RelativeSource in your binding:

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ____Your Parent control here___ }}, Path=DataContext.SelectedRule.Name}" />

More info on RelativeSource can be found here:

http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx

Data binding to SelectedItem in a WPF Treeview

It answers a little more than the OP is expecting... But I hope it could help some one at least.

If you want to execute a ICommand whenever the SelectedItem changed, you can bind a command on an event and the use of a property SelectedItem in the ViewModel isn't needed anymore.

To do so:

1- Add reference to System.Windows.Interactivity

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

2- Bind the command to the event SelectedItemChanged

<TreeView x:Name="myTreeView" Margin="1"
            ItemsSource="{Binding Directories}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectedItemChanged">
            <i:InvokeCommandAction Command="{Binding SomeCommand}"
                                   CommandParameter="
                                            {Binding ElementName=myTreeView
                                             ,Path=SelectedItem}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <TreeView.ItemTemplate>
           <!-- ... -->
    </TreeView.ItemTemplate>
</TreeView>

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

If your items are wider than the ListBox, the other answers here won't help: the items in the ItemTemplate remain wider than the ListBox.

The fix that worked for me was to disable the horizontal scrollbar, which, apparently, also tells the container of all those items to remain only as wide as the list box.

Hence the combined fix to get ListBox items that are as wide as the list box, whether they are smaller and need stretching, or wider and need wrapping, is as follows:

<ListBox HorizontalContentAlignment="Stretch" 
         ScrollViewer.HorizontalScrollBarVisibility="Disabled">

(credits for the scroll bar idea)

Gridview row editing - dynamic binding to a DropDownList

 <asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
            AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
            BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
            OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting">
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <Columns>
            <asp:TemplateField HeaderText="SerialNo">
            <ItemTemplate>
            <%# Container .DataItemIndex+1 %>.&nbsp
            </ItemTemplate>
            </asp:TemplateField>
                <asp:TemplateField HeaderText="RollNo">
                    <ItemTemplate>
                        <%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SName">
                    <ItemTemplate>
                    <%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="C">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
                        <asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cpp">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
                       <asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Java">
                    <ItemTemplate>
                       <%--  <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
                        <asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
                            CommandName="Update"></asp:LinkButton>
                        <asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
                            CommandName="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
                            Text="Edit"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
                <asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
            </Columns>
        </asp:GridView>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
                    <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
                    <asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
                    <asp:TextBox ID="txtc" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
                    <asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
                    <asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
                    <asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
                </td>
            </tr>
        </table>

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

Binding a WPF ComboBox to a custom list

I had a similar issue where the SelectedItem never got updated.

My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.

public override bool Equals(object obj)
{
    return this.Id == (obj as MyCustomObject).Id;
}

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

Formatting DataBinder.Eval data

There is an optional overload for DataBinder.Eval to supply formatting:

<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>

The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:

<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>

What's the difference between StaticResource and DynamicResource in WPF?

  1. StaticResource uses first value. DynamicResource uses last value.
  2. DynamicResource can be used for nested styling, StaticResource cannot.

Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type Grid}">
        <Style.Resources>
            <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
                <Setter Property="Background" Value="Pink"/>
            </Style>
        </Style.Resources>
    </Style>
    <Style TargetType="{x:Type Button}" x:Key="ConflictButton">
        <Setter Property="Background" Value="LightGreen"/>
    </Style>
</ResourceDictionary>

In view:

<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ConflictingStyleWindow" Height="100" Width="100">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Button Style="{DynamicResource ConflictButton}" Content="Test"/>
    </Grid>
</Window>

StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.

StaticResource StaticResource

DynamicResource DynamicResource

Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.

StaticResource will throw an error when the root-level style (LightGreen) is removed.

Getting value from a cell from a gridview on RowDataBound event

protected void gvbind_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";
        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvbind, "Select$" + e.Row.RowIndex);
    }
}

String replacement in Objective-C

You could use the method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement

...to get a new string with a substring replaced (See NSString documentation for others)

Example use

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];

From milliseconds to hour, minutes, seconds and milliseconds

milliseconds = 12884983  // or x milliseconds
hr = 0
min = 0
sec = 0 
day = 0
while (milliseconds >= 1000) {
  milliseconds = (milliseconds - 1000)
  sec = sec + 1
  if (sec >= 60) min = min + 1
  if (sec == 60) sec = 0
  if (min >= 60) hr = hr + 1
  if (min == 60) min = 0
  if (hr >= 24) {
    hr = (hr - 24)
    day = day + 1
  }
}

I hope that my shorter method will help you

Remove a file from the list that will be committed

if you have already pushed your commit then. do

git checkout origin/<remote-branch> <filename>
git commit --amend

AND If you have not pushed the changes on the server you can use

git reset --soft HEAD~1

Cannot assign requested address using ServerSocket.socketBind

As other people have pointed out, it is most likely related to another process using port 9999. On Windows, run the command:

netstat -a -n | grep "LIST"

And it should list anything there that's hogging the port. Of course you'll then have to go and manually kill those programs in Task Manager. If this still doesn't work, replace the line:

serverSocket = new ServerSocket(9999);

With:

InetAddress locIP = InetAddress.getByName("192.168.1.20");
serverSocket = new ServerSocket(9999, 0, locIP);

Of course replace 192.168.1.20 with your actual IP address, or use 127.0.0.1.

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

How to split a string in Java

You can use Split():

import java.io.*;

public class Splitting
{

    public static void main(String args[])
    {
        String Str = new String("004-034556");
        String[] SplittoArray = Str.split("-");
        String string1 = SplittoArray[0];
        String string2 = SplittoArray[1];
    }
}

Else, you can use StringTokenizer:

import java.util.*;
public class Splitting
{
    public static void main(String[] args)
    {
        StringTokenizer Str = new StringTokenizer("004-034556");
        String string1 = Str.nextToken("-");
        String string2 = Str.nextToken("-");
    }
}

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

How can I clear event subscriptions in C#?

You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.

How to access property of anonymous type in C#?

If you're storing the object as type object, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:

Type t = o.GetType();

Then from that you look up a property:

PropertyInfo p = t.GetProperty("Foo");

Then from that you can get a value:

object v = p.GetValue(o, null);

This answer is long overdue for an update for C# 4:

dynamic d = o;
object v = d.Foo;

And now another alternative in C# 6:

object v = o?.GetType().GetProperty("Foo")?.GetValue(o, null);

Note that by using ?. we cause the resulting v to be null in three different situations!

  1. o is null, so there is no object at all
  2. o is non-null but doesn't have a property Foo
  3. o has a property Foo but its real value happens to be null.

So this is not equivalent to the earlier examples, but may make sense if you want to treat all three cases the same.

CSS Disabled scrolling

I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

Eclipse internal error while initializing Java tooling

Close all open projects and exit Eclipse. Now you can open Eclipse without getting the error. Start opening your projects one by one to find which one causes the problem. This is most likely because you deleted a Device profile inside the AVD manager.

Or you can start working on a new workspace, (i.e. change your workspace), then try to import your project from the old workspace

How do you set the max number of characters for an EditText in Android?

   <EditText
        android:id="@+id/edtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter device name"
        android:maxLength="10"
        android:inputType="textFilter"
        android:singleLine="true"/>

InputType has to set "textFilter"

        android:inputType="textFilter"

How to edit binary file on Unix systems

You can also try ghex2 GNOME utilities. This give you the automated hex-to-ASCII on the side, as well as the various character/integer decodes at the bottom. ghex2
(source: googlepages.com)

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.

So in your code you could have:

strFolder = Wscript.Arguments.Item(0) 

Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing

Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.

MS Technet examples

How to get the Display Name Attribute of an Enum member via MVC Razor code?

Building on Todd's great answer which built on Aydin's great answer, here's a generic extension method which doesn't require any type parameters.

/// <summary>
/// Gets human-readable version of enum.
/// </summary>
/// <returns>effective DisplayAttribute.Name of given enum.</returns>
public static string GetDisplayName<T>(this T enumValue) where T : IComparable, IFormattable, IConvertible
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("Argument must be of type Enum");

    DisplayAttribute displayAttribute = enumValue.GetType()
                                                 .GetMember(enumValue.ToString())
                                                 .First()
                                                 .GetCustomAttribute<DisplayAttribute>();

    string displayName = displayAttribute?.GetName();

    return displayName ?? enumValue.ToString();
}

I needed this for my project because something like the below code, where not every member of the enum has a DisplayAttribute, does not work with Todd's solution:

public class MyClass
{
    public enum MyEnum 
    {
        [Display(Name="ONE")]
        One,
        // No DisplayAttribute
        Two
    }
    public void UseMyEnum()
    {
        MyEnum foo = MyEnum.One;
        MyEnum bar = MyEnum.Two;
        Console.WriteLine(foo.GetDisplayName());
        Console.WriteLine(bar.GetDisplayName());
    }
}
// Output:
//
// ONE
// Two

If this is a complicated solution to a simple problem, please let me know, but this was the fix I used.

Accessing the web page's HTTP Headers in JavaScript

Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.

Java: Simplest way to get last word in a string

Get the last word in Kotlin:

String.substringAfterLast(" ")

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 

where

P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

Jump into interface implementation in Eclipse IDE

There's a big productivity boost if you add an Alt + F3 key binding to the Open Implementation feature, and just use F3 to go to interfaces, and Alt + F3 to go to implementations.

Open implementation keybinding

Radio button checked event handling

$("#expires1").click(function(){
     if (this.checked)
        alert("testing....");
});

BigDecimal to string

If you just need to set precision quantity and round the value, the right way to do this is use it's own object for this.

BigDecimal value = new BigDecimal("10.0001");
value = value.setScale(4, RoundingMode.HALF_UP);
System.out.println(value); //the return should be "10.0001"

One of the pillars of Oriented Object Programming (OOP) is "encapsulation", this pillar also says that an object should deal with it's own operations, like in this way:

How to check if a list is empty in Python?

if not myList:
  print "Nothing here"

C# Sort and OrderBy comparison

Darin Dimitrov's answer shows that OrderBy is slightly faster than List.Sort when faced with already-sorted input. I modified his code so it repeatedly sorts the unsorted data, and OrderBy is in most cases slightly slower.

Furthermore, the OrderBy test uses ToArray to force enumeration of the Linq enumerator, but that obviously returns a type (Person[]) which is different from the input type (List<Person>). I therefore re-ran the test using ToList rather than ToArray and got an even bigger difference:

Sort: 25175ms
OrderBy: 30259ms
OrderByWithToList: 31458ms

The code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

class Program
{
    class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, true);
        }
    }

    class Person
    {
        public Person(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
        public override string ToString()
        {
            return Id + ": " + Name;
        }
    }

    private static Random randomSeed = new Random();
    public static string RandomString(int size, bool lowerCase)
    {
        var sb = new StringBuilder(size);
        int start = (lowerCase) ? 97 : 65;
        for (int i = 0; i < size; i++)
        {
            sb.Append((char)(26 * randomSeed.NextDouble() + start));
        }
        return sb.ToString();
    }

    private class PersonList : List<Person>
    {
        public PersonList(IEnumerable<Person> persons)
           : base(persons)
        {
        }

        public PersonList()
        {
        }

        public override string ToString()
        {
            var names = Math.Min(Count, 5);
            var builder = new StringBuilder();
            for (var i = 0; i < names; i++)
                builder.Append(this[i]).Append(", ");
            return builder.ToString();
        }
    }

    static void Main()
    {
        var persons = new PersonList();
        for (int i = 0; i < 100000; i++)
        {
            persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
        } 

        var unsortedPersons = new PersonList(persons);

        const int COUNT = 30;
        Stopwatch watch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            watch.Start();
            Sort(persons);
            watch.Stop();
            persons.Clear();
            persons.AddRange(unsortedPersons);
        }
        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

        watch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            watch.Start();
            OrderBy(persons);
            watch.Stop();
            persons.Clear();
            persons.AddRange(unsortedPersons);
        }
        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);

        watch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            watch.Start();
            OrderByWithToList(persons);
            watch.Stop();
            persons.Clear();
            persons.AddRange(unsortedPersons);
        }
        Console.WriteLine("OrderByWithToList: {0}ms", watch.ElapsedMilliseconds);
    }

    static void Sort(List<Person> list)
    {
        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
    }

    static void OrderBy(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
    }

    static void OrderByWithToList(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToList();
    }
}

How do you make a HTTP request with C++?

Windows code:

#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <vector>
#include <locale>
#include <sstream>
using namespace std;
#pragma comment(lib,"ws2_32.lib")




int main( void ){

WSADATA wsaData;
SOCKET Socket;
SOCKADDR_IN SockAddr;
int lineCount=0;
int rowCount=0;
struct hostent *host;
locale local;
char buffer[10000];
int i = 0 ;
int nDataLength;
string website_HTML;

// website url
string url = "www.google.com";

//HTTP GET
string get_http = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";


    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
        cout << "WSAStartup failed.\n";
        system("pause");
        //return 1;
    }

    Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    host = gethostbyname(url.c_str());

    SockAddr.sin_port=htons(80);
    SockAddr.sin_family=AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

    if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
        cout << "Could not connect";
        system("pause");
        //return 1;
    }

    // send GET / HTTP
    send(Socket,get_http.c_str(), strlen(get_http.c_str()),0 );

    // recieve html
    while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){        
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'){

            website_HTML+=buffer[i];
            i += 1;
        }               
    }

    closesocket(Socket);
    WSACleanup();

    // Display HTML source 
    cout<<website_HTML;

    // pause
    cout<<"\n\nPress ANY key to close.\n\n";
    cin.ignore(); cin.get(); 


 return 0;
}

Here is a much better implementation:

#include <windows.h>
#include <string>
#include <stdio.h>

using std::string;

#pragma comment(lib,"ws2_32.lib")


HINSTANCE hInst;
WSADATA wsaData;
void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename);
SOCKET connectToServer(char *szServerName, WORD portNum);
int getHeaderLength(char *content);
char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut);


int main()
{
    const int bufLen = 1024;
    char *szUrl = "http://stackoverflow.com";
    long fileSize;
    char *memBuffer, *headerBuffer;
    FILE *fp;

    memBuffer = headerBuffer = NULL;

    if ( WSAStartup(0x101, &wsaData) != 0)
        return -1;


    memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);
    printf("returned from readUrl\n");
    printf("data returned:\n%s", memBuffer);
    if (fileSize != 0)
    {
        printf("Got some data\n");
        fp = fopen("downloaded.file", "wb");
        fwrite(memBuffer, 1, fileSize, fp);
        fclose(fp);
         delete(memBuffer);
        delete(headerBuffer);
    }

    WSACleanup();
    return 0;
}


void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
    string::size_type n;
    string url = mUrl;

    if (url.substr(0,7) == "http://")
        url.erase(0,7);

    if (url.substr(0,8) == "https://")
        url.erase(0,8);

    n = url.find('/');
    if (n != string::npos)
    {
        serverName = url.substr(0,n);
        filepath = url.substr(n);
        n = filepath.rfind('/');
        filename = filepath.substr(n+1);
    }

    else
    {
        serverName = url;
        filepath = "/";
        filename = "";
    }
}

SOCKET connectToServer(char *szServerName, WORD portNum)
{
    struct hostent *hp;
    unsigned int addr;
    struct sockaddr_in server;
    SOCKET conn;

    conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (conn == INVALID_SOCKET)
        return NULL;

    if(inet_addr(szServerName)==INADDR_NONE)
    {
        hp=gethostbyname(szServerName);
    }
    else
    {
        addr=inet_addr(szServerName);
        hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
    }

    if(hp==NULL)
    {
        closesocket(conn);
        return NULL;
    }

    server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
    server.sin_family=AF_INET;
    server.sin_port=htons(portNum);
    if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
    {
        closesocket(conn);
        return NULL;
    }
    return conn;
}

int getHeaderLength(char *content)
{
    const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
    char *findPos;
    int ofset = -1;

    findPos = strstr(content, srchStr1);
    if (findPos != NULL)
    {
        ofset = findPos - content;
        ofset += strlen(srchStr1);
    }

    else
    {
        findPos = strstr(content, srchStr2);
        if (findPos != NULL)
        {
            ofset = findPos - content;
            ofset += strlen(srchStr2);
        }
    }
    return ofset;
}

char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
    const int bufSize = 512;
    char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
    char *tmpResult=NULL, *result;
    SOCKET conn;
    string server, filepath, filename;
    long totalBytesRead, thisReadSize, headerLen;

    mParseUrl(szUrl, server, filepath, filename);

    ///////////// step 1, connect //////////////////////
    conn = connectToServer((char*)server.c_str(), 80);

    ///////////// step 2, send GET request /////////////
    sprintf(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
    strcpy(sendBuffer, tmpBuffer);
    strcat(sendBuffer, "\r\n");
    sprintf(tmpBuffer, "Host: %s", server.c_str());
    strcat(sendBuffer, tmpBuffer);
    strcat(sendBuffer, "\r\n");
    strcat(sendBuffer, "\r\n");
    send(conn, sendBuffer, strlen(sendBuffer), 0);

//    SetWindowText(edit3Hwnd, sendBuffer);
    printf("Buffer being sent:\n%s", sendBuffer);

    ///////////// step 3 - get received bytes ////////////////
    // Receive until the peer closes the connection
    totalBytesRead = 0;
    while(1)
    {
        memset(readBuffer, 0, bufSize);
        thisReadSize = recv (conn, readBuffer, bufSize, 0);

        if ( thisReadSize <= 0 )
            break;

        tmpResult = (char*)realloc(tmpResult, thisReadSize+totalBytesRead);

        memcpy(tmpResult+totalBytesRead, readBuffer, thisReadSize);
        totalBytesRead += thisReadSize;
    }

    headerLen = getHeaderLength(tmpResult);
    long contenLen = totalBytesRead-headerLen;
    result = new char[contenLen+1];
    memcpy(result, tmpResult+headerLen, contenLen);
    result[contenLen] = 0x0;
    char *myTmp;

    myTmp = new char[headerLen+1];
    strncpy(myTmp, tmpResult, headerLen);
    myTmp[headerLen] = NULL;
    delete(tmpResult);
    *headerOut = myTmp;

    bytesReturnedOut = contenLen;
    closesocket(conn);
    return(result);
}

Check if a class is derived from a generic class

It might be overkill but I use extension methods like the following. They check interfaces as well as subclasses. It can also return the type that has the specified generic definition.

E.g. for the example in the question it can test against generic interface as well as generic class. The returned type can be used with GetGenericArguments to determine that the generic argument type is "SomeType".

/// <summary>
/// Checks whether this type has the specified definition in its ancestry.
/// </summary>   
public static bool HasGenericDefinition(this Type type, Type definition)
{
    return GetTypeWithGenericDefinition(type, definition) != null;
}

/// <summary>
/// Returns the actual type implementing the specified definition from the
/// ancestry of the type, if available. Else, null.
/// </summary>
public static Type GetTypeWithGenericDefinition(this Type type, Type definition)
{
    if (type == null)
        throw new ArgumentNullException("type");
    if (definition == null)
        throw new ArgumentNullException("definition");
    if (!definition.IsGenericTypeDefinition)
        throw new ArgumentException(
            "The definition needs to be a GenericTypeDefinition", "definition");

    if (definition.IsInterface)
        foreach (var interfaceType in type.GetInterfaces())
            if (interfaceType.IsGenericType
                && interfaceType.GetGenericTypeDefinition() == definition)
                return interfaceType;

    for (Type t = type; t != null; t = t.BaseType)
        if (t.IsGenericType && t.GetGenericTypeDefinition() == definition)
            return t;

    return null;
}

Adding a collaborator to my free GitHub account?

Go to Manage Access page under settings (https://github.com/user/repo/settings/access) and add the collaborators as needed.

Screenshot:

enter image description here

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

Is it not possible to define multiple constructors in Python?

Jack M. is right. Do it this way:

>>> class City:
...     def __init__(self, city=None):
...         self.city = city
...     def __repr__(self):
...         if self.city:  return self.city
...         return ''
...
>>> c = City('Berlin')
>>> print c
Berlin
>>> c = City()
>>> print c

>>>

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

Unable to find valid certification path to requested target - error even after cert imported

Here is the solution , follow the below link Step by Step :

http://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/

JAVA FILE : which is missing from the blog

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



import java.io.*;
import java.net.URL;

import java.security.*;
import java.security.cert.*;

import javax.net.ssl.*;

public class InstallCert {

    public static void main(String[] args) throws Exception {
    String host;
    int port;
    char[] passphrase;
    if ((args.length == 1) || (args.length == 2)) {
        String[] c = args[0].split(":");
        host = c[0];
        port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
        String p = (args.length == 1) ? "changeit" : args[1];
        passphrase = p.toCharArray();
    } else {
        System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
        return;
    }

    File file = new File("jssecacerts");
    if (file.isFile() == false) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP
            + "lib" + SEP + "security");
        file = new File(dir, "jssecacerts");
        if (file.isFile() == false) {
        file = new File(dir, "cacerts");
        }
    }
    System.out.println("Loading KeyStore " + file + "...");
    InputStream in = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();

    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println();
        System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
        System.out.println();
        e.printStackTrace(System.out);
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null) {
        System.out.println("Could not obtain server certificate chain");
        return;
    }

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));

    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        System.out.println
            (" " + (i + 1) + " Subject " + cert.getSubjectDN());
        System.out.println("   Issuer  " + cert.getIssuerDN());
        sha1.update(cert.getEncoded());
        System.out.println("   sha1    " + toHexString(sha1.digest()));
        md5.update(cert.getEncoded());
        System.out.println("   md5     " + toHexString(md5.digest()));
        System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
        System.out.println("KeyStore not changed");
        return;
    }

    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println
        ("Added certificate to keystore 'jssecacerts' using alias '"
        + alias + "'");
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static class SavingTrustManager implements X509TrustManager {

    private final X509TrustManager tm;
    private X509Certificate[] chain;

    SavingTrustManager(X509TrustManager tm) {
        this.tm = tm;
    }

    public X509Certificate[] getAcceptedIssuers() {
        throw new UnsupportedOperationException();
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new UnsupportedOperationException();
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        this.chain = chain;
        tm.checkServerTrusted(chain, authType);
    }
    }

}

Can you set a border opacity in CSS?

As an alternate solution that may work in some cases: change the border-style to dotted.

Having alternating groups of pixels between the foreground color and the background color isn't the same as a continuous line of partially transparent pixels. On the other hand, this requires significantly less CSS and it is much more compatible across every browser without any browser-specific directives.

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

QR Code encoding and decoding using zxing

Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:

// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
                        .setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

HTML 5 video or audio playlist

I optimized the javascript code from cameronjonesweb a little bit. Now you can just add the clips into the array. Everything else is done automatically.

<video autoplay controls id="Player" src="http://www.w3schools.com/html/movie.mp4" onclick="this.paused ? this.play() : this.pause();">Your browser does not support the video tag.</video>

<script>
var nextsrc = ["http://www.w3schools.com/html/movie.mp4","http://www.w3schools.com/html/mov_bbb.mp4"];
var elm = 0; var Player = document.getElementById('Player');
Player.onended = function(){
    if(++elm < nextsrc.length){         
         Player.src = nextsrc[elm]; Player.play();
    } 
}
</script>

How do I format a string using a dictionary in python-3.x?

As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping) (Python 3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

What this means is that you can use for example a defaultdict that would set (and return) a default value for keys that are missing:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

Even if the mapping provided is a dict, not a subclass, this would probably still be slightly faster.

The difference is not big though, given

>>> d = dict(foo='x', bar='y', baz='z')

then

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

is about 10 ns (2 %) faster than

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and


Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

Starting from 3.6 you can use the interpolated strings too:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.

How to set an HTTP proxy in Python 2.7?

cd C:\Python34\Scripts

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

pip.exe install PackageName

Javascript counting number of objects in object

The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.

Then you can use either _.size(object) or _.keys(object).length

For your obj.Data, you could test this with:

console.log( _.size(obj.Data) );

or:

console.log( _.keys(obj.Data).length );

Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)

Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:

function ObjectLength( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
};

You can test this with:

console.log( ObjectLength(obj.Data) );

That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:

function ObjectLength_Modern( object ) {
    return Object.keys(object).length;
}

function ObjectLength_Legacy( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
}

var ObjectLength =
    Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;

and as before, test it with:

console.log( ObjectLength(obj.Data) );

This code uses Object.keys(object).length in modern browsers and falls back to counting in a loop for old browsers.

But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.

I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.

Thanks to Barmar for suggesting Object.keys for newer browsers in his answer.

Write to .txt file?

FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);

I ran into a merge conflict. How can I abort the merge?

I found the following worked for me (revert a single file to pre-merge state):

git reset *currentBranchIntoWhichYouMerged* -- *fileToBeReset*

List supported SSL/TLS versions for a specific OpenSSL build

It's clumsy, but you can get this from the usage messages for s_client or s_server, which are #ifed at compile time to match the supported protocol versions. Use something like

 openssl s_client -help 2>&1 | awk '/-ssl[0-9]|-tls[0-9]/{print $1}' 
 # in older releases any unknown -option will work; in 1.1.0 must be exactly -help

How do I specify the exit code of a console application in .NET?

Just an another way:

public static class ApplicationExitCodes
{
    public static readonly int Failure = 1;
    public static readonly int Success = 0;
}

Nested classes' scope?

In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.

class OuterClass:
    def __init__(self):
        self.outer_var = 1
        self.inner_class = OuterClass.InnerClass(self)
        print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)

    class InnerClass:
        def __init__(self, outer_class):
            self.outer_class = outer_class
            self.inner_var = 2
            print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Please try this:

Sub deleteConn(xlBook)
    For Each Cn In xlBook.Connections
        Cn.Delete
    Next Cn

    For Each xlsheet In xlBook.Worksheets
        For Each Qt In xlsheet.QueryTables
            Qt.Delete
        Next Qt
    Next xlsheet

End Sub

How to give the background-image path in CSS?

The solution (http://expressjs.com/en/starter/static-files.html).

once done this the image folder no longer shalt put it. only be

background-image: url ( "/ image.png");

carpera that the image is already in the static files

matplotlib error - no module named tkinter

Maybe you installed python from source. In this case, you can recompile python with tcl/tk supported.

  1. Complie and install tcl/tk from http://www.tcl.tk/software/tcltk/download.html, I'll suppose you installed python at /home/xxx/local/tcl-tk/.
# install tcl
wget -c https://prdownloads.sourceforge.net/tcl/tcl8.6.9-src.tar.gz
tar -xvzf tcl8.6.9-src.tar.gz
cd tcl8.6.9
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install

# install tk
wget -c https://prdownloads.sourceforge.net/tcl/tk8.6.9.1-src.tar.gz
tar -xvzf tk8.6.9.1-src.tar.gz
cd tk8.6.9.1
./configure --prefix=/home/xxx/local/tcl-tk/
make
make install
  1. Recompile python with tcl/tk supported, for example:
# download the source code of python and decompress it first.

cd <your-python-src-dir>
./configure --prefix=/home/xxx/local/python \
 --with-tcltk-includes=/home/xxx/local/tcl-tk/include \
 --with-tcltk-libs=/home/xxx/local/tcl-tk/lib
make 
make install

PHP string concatenation

I think this code should work fine

while ($personCount < 10) {
$result = $personCount . "people ';
$personCount++;
}
// do not understand why do you need the (+) with the result.
echo $result;

How can I exclude one word with grep?

The -v option will show you all the lines that don't match the pattern.

grep -v ^unwanted_word

How to add click event to a iframe with JQuery

I was trying to find a better answer that was more standalone, so I started to think about how JQuery does events and custom events. Since click (from JQuery) is just any event, I thought that all I had to do was trigger the event given that the iframe's content has been clicked on. Thus, this was my solution

$(document).ready(function () {
    $("iframe").each(function () {
        //Using closures to capture each one
        var iframe = $(this);
        iframe.on("load", function () { //Make sure it is fully loaded
            iframe.contents().click(function (event) {
                iframe.trigger("click");
            });
        });

        iframe.click(function () {
            //Handle what you need it to do
        });
    });
});

Java error - "invalid method declaration; return type required"

As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.

When defining constructors of a class, they should have the same name as its class. Thus the following code

public class Circle
{ 
    //This part is called the constructor and lets us specify the radius of a  
    //particular circle. 
  public Circle(double r) 
  { 
   radius = r; 
  }
 ....
} 

is correct while your code

public class Circle
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public diameter()
    {
       double d = radius * 2;
       return d;
    }
}

is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from

public CircleR(double r) 

to

public Circle(double r)

or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.

So your new class should be

public class CircleR
{
    private double radius;
    public CircleR(double r)
    {
        radius = r;
    }
    public double diameter()
    {
       double d = radius * 2;
       return d;
    }
}

I also added the return type double in your method as pointed out by Froyo and John B.

Refer to this article about constructors.

HTH.

Google Maps shows "For development purposes only"

It seems to me that when it displays the "For development purposes only", one cannot see the map configurations as well while developing(or rather playing around with the configurations). In my case I have not enabled billing to be associated with the API I am using and I am thinking that's the reason why its behaving this way.

Gem Command not found

Are you wanting ruby gems? If so, you need to install libgemplugin-ruby and then the ruby 'gem' program will be in your path:

aptitude install libgemplugin-ruby

Delete everything in a MongoDB database

For Meteor developers.

  1. Open a second terminal window while running your app in localhost:3000.

  2. In your project's folder run, meteor mongo.

    coolName = new Mongo.Collection('yourCollectionName');

  3. Then simply enter db.yourCollectionName.drop();

  4. You'll automatically see the changes in your local server.

For everybody else.

db.yourCollectionName.drop();

Customize list item bullets using CSS

You can wrap the contents of the li in another element such as a span. Then, give the li a larger font-size, and set a normal font-size back on the span:

http://jsfiddle.net/RZr2r/

li {
    font-size: 36px;
}
li span {
    font-size: 18px;
}
<ul>
    <li><span>Item 1</span></li>
    <li><span>Item 2</span></li>
    <li><span>Item 3</span></li>
</ul>

Options for HTML scraping?

For Perl, there's WWW::Mechanize.

Authentication failed to bitbucket

OBSOLETE ANSWER - VERIFIED NOVEMBER 17, 2020


On Mac, I needed to go to Preferences > Accounts, then add a new account as Bitbucket Server and enter my company's bitbucket server URL. Then I had to choose HTTPS as the protocol and enter my username (without @email) and password.

Also I set this new account as the default account by clicking the Set Default... button in the bottom of the Preferences > Account page.

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

You can use:

Bulk collect along with FOR ALL that is called Bulk binding.

Because PL/SQL forall operator speeds 30x faster for simple table inserts.

BULK_COLLECT and Oracle FORALL together these two features are known as Bulk Binding. Bulk Binds are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with INSERT, UPDATE, and DELETE statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with SELECT statements, you include the BULK COLLECT clause in the SELECT statement instead of using INTO.

It improves performance.

Convert sqlalchemy row object to python dict

As per @zzzeek in comments:

note that this is the correct answer for modern versions of SQLAlchemy, assuming "row" is a core row object, not an ORM-mapped instance.

for row in resultproxy:
    row_as_dict = dict(row)

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

TypeError: $(...).modal is not a function with bootstrap Modal

In my case, I use rails framework and require jQuery twice. I think that is a possible reason.

You can first check app/assets/application.js file. If the jquery and bootstrap-sprockets appears, then there is not need for a second library require. The file should be similar to this:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

Then check app/views/layouts/application.html.erb, and remove the script for requiring jquery. For example:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

I think sometimes when newbies use multiple tutorial code examples will cause this issue.

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

How to access ssis package variables inside script component

Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: screenshot of Script Transformation Editor properties page Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:

// Modify as necessary
public override void PreExecute()
{
    base.PreExecute();
    string thePath = Variables.FilePath;
    // Do something ...
}

public override void PostExecute()
{
    base.PostExecute();
    string theNewValue = "";
    // Do something to figure out the new value...
    Variables.FilePath = theNewValue;
}

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    string thePath = Variables.FilePath;
    // Do whatever needs doing here ...
}

One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.

Regarding the code snippet:

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

varCollection is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.

css 'pointer-events' property alternative for IE

Here is another solution that is very easy to implement with 5 lines of code:

  1. Capture the 'mousedown' event for the top element (the element you want to turn off pointer events).
  2. In the 'mousedown' hide the top element.
  3. Use 'document.elementFromPoint()' to get the underlying element.
  4. Unhide the top element.
  5. Execute the desired event for the underlying element.

Example:

//This is an IE fix because pointer-events does not work in IE
$(document).on('mousedown', '.TopElement', function (e) {

    $(this).hide();
    var BottomElement = document.elementFromPoint(e.clientX, e.clientY);
    $(this).show();
    $(BottomElement).mousedown(); //Manually fire the event for desired underlying element

    return false;

});

How do you comment an MS-access Query?

It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Swift 4.x

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        let writingDirection = UIApplication.shared.userInterfaceLayoutDirection
        let factor: CGFloat = writingDirection == .leftToRight ? 1 : -1

        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount*factor, bottom: 0, right: insetAmount*factor)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount*factor, bottom: 0, right: -insetAmount*factor)
        self.contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

Usage:

button.centerTextAndImage(spacing: 10.0)

How to find the process id of a running Java process on Windows? And how to kill the process alone?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.

Then use the Windows task manager to terminate the process. If you want to do it on the command line, use

TASKKILL /PID %PID%

How to store Java Date to Mysql datetime with JPA

Probably because your java date has a different format from mysql format (YYYY-MM-DD HH:MM:SS)

do this

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date));

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

This usually happens when you are using a URI scheme that is not supported by the server in which the app is deployed. So, you might either want to check what all schemes your server supports and modify your request URI accordingly, or, you might want to add the support for that scheme in your server. The scope of your application should help you decide on this.

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

Customize the Authorization HTTP header

This is a bit dated but there may be others looking for answers to the same question. You should think about what protection spaces make sense for your APIs. For example, you may want to identify and authenticate client application access to your APIs to restrict their use to known, registered client applications. In this case, you can use the Basic authentication scheme with the client identifier as the user-id and client shared secret as the password. You don't need proprietary authentication schemes just clearly identify the one(s) to be used by clients for each protection space. I prefer only one for each protection space but the HTTP standards allow both multiple authentication schemes on each WWW-Authenticate header response and multiple WWW-Authenticate headers in each response; this will be confusing for API clients which options to use. Be consistent and clear then your APIs will be used.

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

This function will return a converted SQL date from java date object.

public static java.sql.Date convertFromJAVADateToSQLDate(
            java.util.Date javaDate) {
        java.sql.Date sqlDate = null;
        if (javaDate != null) {
            sqlDate = new Date(javaDate.getTime());
        }
        return sqlDate;
    }

jquery disable form submit on enter

Even shorter:

$('myform').submit(function() {
  return false;
});

Difference between del, remove, and pop on lists

The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

See collections.deque for more details.

The Use of Multiple JFrames: Good or Bad Practice?

It is not a good practice but even though you wish to use it you can use the singleton pattern as its good. I have used the singleton patterns in most of my project its good.

Model Binding to a List MVC 4

~Controller

namespace ListBindingTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<String> tmp = new List<String>();
            tmp.Add("one");
            tmp.Add("two");
            tmp.Add("Three");
            return View(tmp);
        }

        [HttpPost]
        public ActionResult Send(IList<String> input)
        {
            return View(input);
        }    
    }
}

~ Strongly Typed Index View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
    <div>
    @using(Html.BeginForm("Send", "Home", "POST"))
    {
        @Html.EditorFor(x => x)
        <br />
        <input type="submit" value="Send" />
    }
    </div>
</body>
</html>

~ Strongly Typed Send View

@model IList<String>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Send</title>
</head>
<body>
    <div>
    @foreach(var element in @Model)
    {
        @element
        <br />
    }
    </div>
</body>
</html>

This is all that you had to do man, change his MyViewModel model to IList.

Find the files existing in one directory but not in the other

Meld (http://meldmerge.org/) does a great job at comparing directories and the files within.

Meld comparing directories

How do I download a binary file over HTTP?

Expanding on Dejw's answer (edit2):

File.open(filename,'w'){ |f|
  uri = URI.parse(url)
  Net::HTTP.start(uri.host,uri.port){ |http| 
    http.request_get(uri.path){ |res| 
      res.read_body{ |seg|
        f << seg
#hack -- adjust to suit:
        sleep 0.005 
      }
    }
  }
}

where filename and url are strings.

The sleep command is a hack that can dramatically reduce CPU usage when the network is the limiting factor. Net::HTTP doesn't wait for the buffer (16kB in v1.9.2) to fill before yielding, so the CPU busies itself moving small chunks around. Sleeping for a moment gives the buffer a chance to fill between writes, and CPU usage is comparable to a curl solution, 4-5x difference in my application. A more robust solution might examine progress of f.pos and adjust the timeout to target, say, 95% of the buffer size -- in fact that's how I got the 0.005 number in my example.

Sorry, but I don't know a more elegant way of having Ruby wait for the buffer to fill.

Edit:

This is a version that automatically adjusts itself to keep the buffer just at or below capacity. It's an inelegant solution, but it seems to be just as fast, and to use as little CPU time, as it's calling out to curl.

It works in three stages. A brief learning period with a deliberately long sleep time establishes the size of a full buffer. The drop period reduces the sleep time quickly with each iteration, by multiplying it by a larger factor, until it finds an under-filled buffer. Then, during the normal period, it adjusts up and down by a smaller factor.

My Ruby's a little rusty, so I'm sure this can be improved upon. First of all, there's no error handling. Also, maybe it could be separated into an object, away from the downloading itself, so that you'd just call autosleep.sleep(f.pos) in your loop? Even better, Net::HTTP could be changed to wait for a full buffer before yielding :-)

def http_to_file(filename,url,opt={})
  opt = {
    :init_pause => 0.1,    #start by waiting this long each time
                           # it's deliberately long so we can see 
                           # what a full buffer looks like
    :learn_period => 0.3,  #keep the initial pause for at least this many seconds
    :drop => 1.5,          #fast reducing factor to find roughly optimized pause time
    :adjust => 1.05        #during the normal period, adjust up or down by this factor
  }.merge(opt)
  pause = opt[:init_pause]
  learn = 1 + (opt[:learn_period]/pause).to_i
  drop_period = true
  delta = 0
  max_delta = 0
  last_pos = 0
  File.open(filename,'w'){ |f|
    uri = URI.parse(url)
    Net::HTTP.start(uri.host,uri.port){ |http|
      http.request_get(uri.path){ |res|
        res.read_body{ |seg|
          f << seg
          delta = f.pos - last_pos
          last_pos += delta
          if delta > max_delta then max_delta = delta end
          if learn <= 0 then
            learn -= 1
          elsif delta == max_delta then
            if drop_period then
              pause /= opt[:drop_factor]
            else
              pause /= opt[:adjust]
            end
          elsif delta < max_delta then
            drop_period = false
            pause *= opt[:adjust]
          end
          sleep(pause)
        }
      }
    }
  }
end

val() doesn't trigger change() in jQuery

It looks like the events are not bubbling. Try this:

$("#mybutton").click(function(){
  var oldval=$("#mytext").val();
  $("#mytext").val('Changed by button');
  var newval=$("#mytext").val();
  if (newval != oldval) {
    $("#mytext").trigger('change');
  }
});

I hope this helps.

I tried just a plain old $("#mytext").trigger('change') without saving the old value, and the .change fires even if the value didn't change. That is why I saved the previous value and called $("#mytext").trigger('change') only if it changes.

Margin on child element moves parent element

add style display:inline-block to child element

Detect when an image fails to load in Javascript

The answer is nice, but it introduces one problem. Whenever you assign onload or onerror directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.

Let me rewrite the answer a little bit.

function testImage(url) {
    var tester = new Image();
    tester.addEventListener('load', imageFound);
    tester.addEventListener('error', imageNotFound);
    tester.src = url;
}

function imageFound() {
    alert('That image is found and loaded');
}

function imageNotFound() {
    alert('That image was not found.');
}

testImage("http://foo.com/bar.jpg");

Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.

function testImage(url) {

    // Define the promise
    const imgPromise = new Promise(function imgPromise(resolve, reject) {

        // Create the image
        const imgElement = new Image();

        // When image is loaded, resolve the promise
        imgElement.addEventListener('load', function imgOnLoad() {
            resolve(this);
        });

        // When there's an error during load, reject the promise
        imgElement.addEventListener('error', function imgOnError() {
            reject();
        })

        // Assign URL
        imgElement.src = url;

    });

    return imgPromise;
}

testImage("http://foo.com/bar.jpg").then(

    function fulfilled(img) {
        console.log('That image is found and loaded', img);
    },

    function rejected() {
        console.log('That image was not found');
    }

);

How to store values from foreach loop into an array?

Declare the $items array outside the loop and use $items[] to add items to the array:

$items = array();
foreach($group_membership as $username) {
 $items[] = $username;
}

print_r($items);

Why is json_encode adding backslashes?

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);

How to extract the nth word and count word occurrences in a MySQL string?

As others have said, mysql does not provide regex tools for extracting sub-strings. That's not to say you can't have them though if you're prepared to extend mysql with user-defined functions:

https://github.com/mysqludf/lib_mysqludf_preg

That may not be much help if you want to distribute your software, being an impediment to installing your software, but for an in-house solution it may be appropriate.

How do I get a UTC Timestamp in JavaScript?

I want to make clear that new Date().getTime() does in fact return a UTC value, so it is a really helpful way to store and manage dates in a way that is agnostic to localized times.

In other words, don't bother with all the UTC javascript functions. Instead, just use Date.getTime().

More info on the explanation is here: If javascript "(new Date()).getTime()" is run from 2 different Timezones.

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

This still appears to be an issue, causing package installations to be aborted with warnings about optional packages no being installed because of "Unsupported platform".

The problem relates to the "shrinkwrap" or package-lock.json which gets persisted after every package manager execution. Subsequent attempts keep failing as this file is referenced instead of package.json.

Adding these options to the npm install command should allow packages to install again.

   --no-optional argument will prevent optional dependencies from being installed.

   --no-shrinkwrap argument, which will ignore an available package lock or
                   shrinkwrap file and use the package.json instead.

   --no-package-lock argument will prevent npm from creating a package-lock.json file.

The complete command looks like this:

    npm install --no-optional --no-shrinkwrap --no-package-lock

nJoy!

What is the difference between association, aggregation and composition?

In a very simple sentence:
Aggregation and Composition are subsets of association.

  • A uses B -> this is an aggregation

  • A needs B -> is composition.

Read more here.

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

In addition to @Connor Leech's answer.

If you want to create a new custom typography type of your own, define the following in your css file.

.text-foo {
  .text-emphasis-variant(#FFFFFF);
}

The mixin text-emphasis-variant is defined in Bootstrap's mixins.less file.

how to fire event on file select

You could subscribe for the onchange event on the input field:

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

and then:

document.getElementById('file').onchange = function() {
    // fire the upload here
};

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

How do you make an array of structs in C?

That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file. Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

How to bind a List to a ComboBox?

For a backgrounder, there are 2 ways to use a ComboBox/ListBox

1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.

2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue

For 2) you will need a list of countries first

// not tested, schematic:
List<Country> countries = ...;
...; // fill 

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";

And then in the SelectionChanged,

if (comboBox1.Selecteditem != null)
{
   comboBox2.DataSource=comboBox1.SelectedValue;

}

How to filter WooCommerce products by custom attribute

You can use WooCommerce AJAX Product Filter. You can also watch how the plugin is used for product filtering.

Here is a screenshot:

enter image description here

Cannot access a disposed object - How to fix?

Stopping the timer doesn't mean that it won't be called again, depending on when you stop the timer, the timer_tick may still be queued on the message loop for the form. What will happen is that you'll get one more tick that you may not be expecting. What you can do is in your timer_tick, check the Enabled property of your timer before executing the Timer_Tick method.

What does the "assert" keyword do?

Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.

In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.

How to disable keypad popup when on edittext?

Two Simple Solutions:

First Solution is added below line of code in manifest xml file. In Manifest file (AndroidManifest.xml), add the following attribute in the activity construct

android:windowSoftInputMode="stateHidden"

Example:

<activity android:name=".MainActivity" 
          android:windowSoftInputMode="stateHidden" />

Second Solution is adding below line of code in activity

//Block auto opening keyboard  
  this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

We can use any one solution of above. Thanks

Applying an ellipsis to multiline text

I have just been playing around a little bit with this concept. Basically, if you are ok with potentially having a pixel or so cut off from your last character, here is a pure css and html solution:

The way this works is by absolutely positioning a div below the viewable region of a viewport. We want the div to offset up into the visible region as our content grows. If the content grows too much, our div will offset too high, so upper bound the height our content can grow.

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

I have tested this in Chrome, FF, Safari, and IE 11.

You can check it out here: http://codepen.io/puopg/pen/vKWJwK

You might even be able to alleviate the abrupt cut off of the character with some CSS magic.

EDIT: I guess one thing that this imposes is word-break: break-all since otherwise the content would not extend to the very end of the viewport. :(

Java Programming: call an exe from Java and passing parameters

Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.

Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)

**

ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
 int returnVal = process.exitValue();
} 

**

No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.

Why does the C++ STL not provide any "tree" containers?

the std::map is based on a red black tree. You can also use other containers to help you implement your own types of trees.

Invalid date in safari

I use moment to solve the problem. For example

var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();

I want to truncate a text or line with ellipsis using JavaScript

For preventing the dots in the middle of a word or after a punctuation symbol.

_x000D_
_x000D_
let parseText = function(text, limit){_x000D_
  if (text.length > limit){_x000D_
      for (let i = limit; i > 0; i--){_x000D_
          if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {_x000D_
              return text.substring(0, i) + '...';_x000D_
          }_x000D_
      }_x000D_
       return text.substring(0, limit) + '...';_x000D_
  }_x000D_
  else_x000D_
      return text;_x000D_
};_x000D_
    _x000D_
    _x000D_
console.log(parseText("1234567 890",5))  // >> 12345..._x000D_
console.log(parseText("1234567 890",8))  // >> 1234567..._x000D_
console.log(parseText("1234567 890",15)) // >> 1234567 890
_x000D_
_x000D_
_x000D_

Maven in Eclipse: step by step installation

By "use install a Maven plugin and use it" I am sure you are looking for a Eclipse plugin that will perform Maven functions within the IDE. If so, M2E is a good choice. You will find a lot of help within the Eclipse installation once you install M2E.

That said -- considering that you are starting off using Maven -- it would go a long way to have a good understanding of the basic concepts. Using M2E could hide some of the details which could lead to incomplete or incorrect interpretation of Maven's behavior and therefore problems downstream.

Some good Maven online references are:

How to redirect to another page using PHP

You can conditionally redirect to some page within a php file....

if (/*Condition to redirect*/){
  //You need to redirect
  header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
  exit();
 }
else{
  // do some
}

How to delay the .keyup() handler until the user stops typing?

Delay Multi Function Calls using Labels

This is the solution i work with. It will delay the execution on ANY function you want. It can be the keydown search query, maybe the quick click on previous or next buttons ( that would otherwise send multiple request if quickly clicked continuously , and be not used after all). This uses a global object that stores each execution time, and compares it with the most current request.

So the result is that only that last click / action will actually be called, because those requests are stored in a queue, that after the X milliseconds is called if no other request with the same label exists in the queue!

function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  delayed_methods[label]=""; callback();}}, time||500);
  }

You can set your own delay time ( its optional, defaults to 500ms). And send your function arguments in a "closure fashion".

For example if you want to call the bellow function:

function send_ajax(id){console.log(id);}

To prevent multiple send_ajax requests, you delay them using:

delay_method( "check date", function(){ send_ajax(2); } ,600);

Every request that uses the label "check date" will only be triggered if no other request is made in the 600 miliseconds timeframe. This argument is optional

Label independency (calling the same target function) but run both:

delay_method("check date parallel", function(){send_ajax(2);});
delay_method("check date", function(){send_ajax(2);});

Results in calling the same function but delay them independently because of their labels being different

How to change the size of the font of a JLabel to take the maximum size

Just wanted to point out that the accepted answer has a couple of limitations (which I discovered when I tried to use it)

  1. As written, it actually keeps recalculating the font size based on a ratio of the previous font size... thus after just a couple of calls it has rendered the font size as much too large. (eg Start with 12 point as your DESIGNED Font, expand the label by just 1 pixel, and the published code will calculate the Font size as 12 * (say) 1.2 (ratio of field space to text) = 14.4 or 14 point font. 1 more Pixel and call and you are at 16 point !).

It is thus not suitable (without adaptation) for use in a repeated-call setting (eg a ComponentResizedListener, or a custom/modified LayoutManager).

The listed code effectively assumes a starting size of 10 pt but refers to the current font size and is thus suitable for calling once (to set the size of the font when the label is created). It would work better in a multi-call environment if it did int newFontSize = (int) (widthRatio * 10); rather than int newFontSize = (int)(labelFont.getSize() * widthRatio);

  1. Because it uses new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse)) to generate the new font, there is no support for Bolding, Italic or Color etc from the original font in the updated font. It would be more flexible if it made use of labelFont.deriveFont instead.

  2. The solution does not provide support for HTML label Text. (I know that was probably not ever an intended outcome of the answer code offered, but as I had an HTML-text JLabel on my JPanel I formally discovered the limitation. The FontMetrics.stringWidth() calculates the text length as inclusive of the width of the html tags - ie as simply more text)

I recommend looking at the answer to this SO question where trashgod's answer points to a number of different answers (including this one) to an almost identical question. On that page I will provide an additional answer that speeds up one of the other answers by a factor of 30-100.

Tool to monitor HTTP, TCP, etc. Web Service traffic

JMeter's built-in proxy may be used to record all HTTP request/response information.

Firefox "Live HTTP headers" plugin may be used to see what is happening on the browser side when sending/receiving request.

Firefox "Tamper data" plugin may be useful when you need to intercept and modify request.

How to determine the content size of a UIWebView?

When using webview as a subview somewhere in scrollview, you can set height constraint to some constant value and later make outlet from it and use it like:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    webView.scrollView.scrollEnabled = NO;
    _webViewHeight.constant = webView.scrollView.contentSize.height;
}

How do I abort/cancel TPL Tasks?

Tasks have first class support for cancellation via cancellation tokens. Create your tasks with cancellation tokens, and cancel the tasks via these explicitly.

SwiftUI - How do I change the background color of a View?

Several possibilities : (SwiftUI / Xcode 11)

1 .background(Color.black) //for system colors

2 .background(Color("green")) //for colors you created in Assets.xcassets

  1. Otherwise you can do Command+Click on the element and change it from there.

Hope it help :)

How to install an npm package from GitHub directly?

The general form of the syntax is

<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]

which means for your case it will be

npm install git+ssh://[email protected]/visionmedia/express.git

From npmjs docs:

npm install :

Installs the package from the hosted git provider, cloning it with git. For a full git remote url, only that URL will be attempted.

<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish>

| #semver:] is one of git, git+ssh, git+http, git+https, or git+file.

If # is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:, can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither # or

semver: is specified, then master is used.

If the repository makes use of submodules, those submodules will be cloned as well.

If the package being installed contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed.

The following git environment variables are recognized by npm and will be added to the environment when running git:

  • GIT_ASKPASS
  • GIT_EXEC_PATH
  • GIT_PROXY_COMMAND
  • GIT_SSH
  • GIT_SSH_COMMAND
  • GIT_SSL_CAINFO GIT_SSL_NO_VERIFY

See the git man page for details.

Examples:

npm install git+ssh://[email protected]:npm/npm.git#v1.0.27
npm install git+ssh://[email protected]:npm/npm#semver:^5.0
npm install git+https://[email protected]/npm/npm.git
npm install git://github.com/npm/npm.git#v1.0.27
GIT_SSH_COMMAND='ssh -i ~/.ssh/custom_ident' npm install git+ssh://[email protected]:npm/npm.git npm install

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

Finding the next available id in MySQL

This worked well for me (MySQL 5.5), also solving the problem of a "starting" position.

SELECT
    IF(res.nextID, res.nextID, @r) AS nextID
FROM
    (SELECT @r := 30) AS vars,
    (
    SELECT MIN(t1.id + 1) AS nextID
    FROM test t1
    LEFT JOIN test t2
      ON t1.id + 1 = t2.id
    WHERE t1.id >= @r
      AND t2.id IS NULL
      AND EXISTS (
          SELECT id
          FROM test
          WHERE id = @r
      )
  LIMIT 1
  ) AS res
LIMIT 1

As mentioned before these types of queries are very slow, at least in MySQL.

get dataframe row count based on conditions

In Pandas, I like to use the shape attribute to get number of rows.

df[df.A > 0].shape[0]

gives the number of rows matching the condition A > 0, as desired.

What is the use of join() in Python threading?

This example demonstrate the .join() action:

import threading
import time

def threaded_worker():
    for r in range(10):
        print('Other: ', r)
        time.sleep(2)

thread_ = threading.Timer(1, threaded_worker)
thread_.daemon = True  # If the main thread kills, this thread will be killed too. 
thread_.start()

flag = True

for i in range(10):
    print('Main: ', i)
    time.sleep(2)
    if flag and i > 4:
        print(
            '''
            Threaded_worker() joined to the main thread. 
            Now we have a sequential behavior instead of concurrency.
            ''')
        thread_.join()
        flag = False

Out:

Main:  0
Other:  0
Main:  1
Other:  1
Main:  2
Other:  2
Main:  3
Other:  3
Main:  4
Other:  4
Main:  5
Other:  5

            Threaded_worker() joined to the main thread. 
            Now we have a sequential behavior instead of concurrency.

Other:  6
Other:  7
Other:  8
Other:  9
Main:  6
Main:  7
Main:  8
Main:  9

I need to round a float to two decimal places in Java

If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);

Which will output (depending on locale):

$2.30

Also, if currency isn't required (just the exact two decimal places) you can use this instead:

NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);

Which will output 2.30

What's the difference between faking, mocking, and stubbing?

all of them are called Test Doubles and used to inject the dependencies that your test case needs.

Fake

Stub: It already has a predefined behavior to set your expectation for example, stub returns only the success case of your API response Stub

A mock is a smarter stub. You verify your test passes through it. so you could make amock that return either the success or failure success depending on the condition could be changed in your test case. Mock

Dummy

Spy

How do I change the data type for a column in MySQL?

To change column data type there are change method and modify method

ALTER TABLE student_info CHANGE roll_no roll_no VARCHAR(255);

ALTER TABLE student_info MODIFY roll_no VARCHAR(255);

To change the field name also use the change method

ALTER TABLE student_info CHANGE roll_no identity_no VARCHAR(255);

SQL - select distinct only on one column

A very typical approach to this type of problem is to use row_number():

select t.*
from (select t.*,
             row_number() over (partition by number order by id) as seqnum
      from t
     ) t
where seqnum = 1;

This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid(). You can select 2 rows by using where seqnum <= 2.

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

Some applications like skype uses wamp's default port:80 so you have to find out which application is accessing this port you can easily find it by using TCP View. End the service accessing this port and restart wamp server. Now it will work.

Facebook Graph API, how to get users email?

The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.

http://developers.facebook.com/docs/authentication/permissions

You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.

I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.

android: how to change layout on button click?

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Without external variables:

       $('.element').bind('mousewheel', function(e, d) {
            if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
                || (this.scrollTop === 0 && d > 0)) {
                e.preventDefault();
            }
        });

How do I echo and send console output to a file in a bat script?

Just use the Windows version of the UNIX tee command (found from http://unxutils.sourceforge.net) in this way:

mycommand > tee outpu_file.txt

If you also need the STDERR output, then use the following.
The 2>&1 combines the STDERR output into STDOUT (the primary stream).

mycommand 2>&1 | tee output_file.txt

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

Uploading multiple files using formData()

You have to get the files length to append in JS and then send it via AJAX request as below

//JavaScript 
var ins = document.getElementById('fileToUpload').files.length;
for (var x = 0; x < ins; x++) {
    fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}

//PHP
$count = count($_FILES['fileToUpload']['name']);
for ($i = 0; $i < $count; $i++) {
    echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'<br/>';
}

Why use 'git rm' to remove a file instead of 'rm'?

Removing files using rm is not a problem per se, but if you then want to commit that the file was removed, you will have to do a git rm anyway, so you might as well do it that way right off the bat.

Also, depending on your shell, doing git rm after having deleted the file, you will not get tab-completion so you'll have to spell out the path yourself, whereas if you git rm while the file still exists, tab completion will work as normal.

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

How to call multiple functions with @click in vue?

I'd add, that you can also use this to call multiple emits or methods or both together by separating with ; semicolon

  @click="method1(); $emit('emit1'); $emit('emit2');"

Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

Where to put default parameter value in C++?

One more point I haven't found anyone mentioned:

If you have virtual method, each declaration can have its own default value!

It depends on the interface you are calling which value will be used.

Example on ideone

struct iface
{
    virtual void test(int a = 0) { std::cout << a; }
};

struct impl : public iface
{
    virtual void test(int a = 5) override { std::cout << a; }
};

int main()
{
    impl d;
    d.test();
    iface* a = &d;
    a->test();
}

It prints 50

I strongly discourage you to use it like this

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

Excel: last character/string match in a string

How about creating a custom function and using that in your formula? VBA has a built-in function, InStrRev, that does exactly what you're looking for.

Put this in a new module:

Function RSearch(str As String, find As String)
    RSearch = InStrRev(str, find)
End Function

And your function will look like this (assuming the original string is in B1):

=LEFT(B1,RSearch(B1,"\"))

How to set seekbar min and max value

If you are using the AndroidX libraries (import androidx.preference.*), this functionality exists without any hacky workarounds!

    val seekbar = findPreference("your_seekbar") as SeekBarPreference
    seekbar.min = 1
    seekbar.max = 10
    seekbar.seekBarIncrement = 1

Explicitly select items from a list or tuple

I just want to point out, even syntax of itemgetter looks really neat, but it's kinda slow when perform on large list.

import timeit
from operator import itemgetter
start=timeit.default_timer()
for i in range(1000000):
    itemgetter(0,2,3)(myList)
print ("Itemgetter took ", (timeit.default_timer()-start))

Itemgetter took 1.065209062149279

start=timeit.default_timer()
for i in range(1000000):
    myList[0],myList[2],myList[3]
print ("Multiple slice took ", (timeit.default_timer()-start))

Multiple slice took 0.6225321444745759

javac: file not found: first.java Usage: javac <options> <source files>

I had the same issue and it was to do with my file name. If you set the file location using CD in CMD, and then type DIR it will list the files in that directory. Check that the file name appears and check that the spelling and filename ending is correct.

It should be .java but mine was .java.txt. The instructions on the Java tutorials website state that you should select "Save as Type Text Documents" but for me that always adds .txt onto the end of the file name. If I change it to "Save as Type All Documents" it correctly saved the file name.

CMD DIR Example

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

How can I add a class to a DOM element in JavaScript?

new_row.className = "aClassName";

Here's more information on MDN: className

Draw horizontal rule in React Native

You could simply use an empty View with a bottom border.

<View
  style={{
    borderBottomColor: 'black',
    borderBottomWidth: 1,
  }}
/>

How to convert a Django QuerySet to a list

Why not just call .values('reqColumn1','reqColumn2') or .values_list('reqColumn1','reqColumn2') on the queryset?

answers_list = models.objects.values('reqColumn1','reqColumn2')

result = [{'reqColumn1':value1,'reqColumn2':value2}]

OR

answers_list = models.objects.values_list('reqColumn1','reqColumn2')

result = [(value1,value2)]

You can able to do all the operation on this QuerySet, which you do for list .

Check if a specific tab page is selected (active)

in .Net 4 can use

if (tabControl1.Controls[5] == tabControl1.SelectedTab)
                MessageBox.Show("Tab 5 Is Selected");

OR

if ( tabpage5 == tabControl1.SelectedTab)
         MessageBox.Show("Tab 5 Is Selected");

Adding JPanel to JFrame

public class Test{

Test2 test = new Test2();
JFrame frame = new JFrame();

Test(){
...
frame.setLayout(new BorderLayout());
frame.add(test, BorderLayout.CENTER);
...
}

//main
...
}

//public class Test2{
public class Test2 extends JPanel {

//JPanel test2 = new JPanel();

Test2(){
...
}

How do you determine the ideal buffer size when using FileInputStream?

Reading files using Java NIO's FileChannel and MappedByteBuffer will most likely result in a solution that will be much faster than any solution involving FileInputStream. Basically, memory-map large files, and use direct buffers for small ones.

Creating a simple configuration file and parser in C++

In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline(). While by default it will read up to the next '\n' (which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like = in your example.

For simplicity, the following presumes that the = are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.

const char config[] = "url=http://example.com\n"
                      "file=main.exe\n"
                      "true=0";

std::istringstream is_file(config);

std::string line;
while( std::getline(is_file, line) )
{
  std::istringstream is_line(line);
  std::string key;
  if( std::getline(is_line, key, '=') )
  {
    std::string value;
    if( std::getline(is_line, value) ) 
      store_line(key, value);
  }
}

(Adding error handling is left as an exercise to the reader.)

retrieve data from db and display it in table in php .. see this code whats wrong with it?

This is a very simple code I use and you manipulate it to change the colour and size of the table as you see fit.

First connect to the database:

<?php
$connect=mysql_connect('localhost', 'root', 'password');

mysql_select_db("name");
//here u select the data you want to retrieve from the db

$query="select * from tablename";

$result= mysql_query($query);

//here you check to see if any data has been found and you define the width of the table

If($result){

echo "<table width ='340' align='left'>
      <tr color ='#5D9951>";
$i=0;

    If(mysql_num_rows($result)>0)
    {
         //here you fetch the data from the database and print it in the respective columns   
        while($i<mysql_num_fields($result))
        {    
             echo "<th>".mysql_field_name($result, $i)."</th>";
             $i++;
        }
        echo "</tr>";

        $color=1;

        while($rows=mysql_fetch_array($result, MYSQL_ASSOC))
        {    
            If ($color==1){
                echo "<tr color='#'#cccccc'>";

                foreach ($rows as $data){
                    echo "<td align='center'>".$data. "</td>";
                }

                $color=2;
            }
            $color=1;
        }
     } else {
        echo"no results found";
        echo "</table>";
    } else {
        echo "error running query:".MYSQL_error();
}
?>

It's a very elementary piece of code but it helps if you are not used to using functions.

How to break out of multiple loops?

keeplooping=True
while keeplooping:
    #Do Stuff
    while keeplooping:
          #do some other stuff
          if finisheddoingstuff(): 
              keeplooping=False

or something like that. You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if appropriate. I kinda like the GOTO method, provided you don't mind using an April Fool's joke module - its not Pythonic, but it does make sense.

Interface vs Abstract Class (general OO)

An interface defines a contract for a service or set of services. They provide polymorphism in a horizontal manner in that two completely unrelated classes can implement the same interface but be used interchangeably as a parameter of the type of interface they implement, as both classes have promised to satisfy the set of services defined by the interface. Interfaces provide no implementation details.

An abstract class defines a base structure for its sublcasses, and optionally partial implementation. Abstract classes provide polymorphism in a vertical, but directional manner, in that any class that inherits the abstract class can be treated as an instance of that abstract class but not the other way around. Abstract classes can and often do contain implementation details, but cannot be instantiated on their own- only their subclasses can be "newed up".

C# does allow for interface inheritance as well, mind you.

How to detect Safari, Chrome, IE, Firefox and Opera browser?

You can try following way to check Browser version.

    <!DOCTYPE html>
    <html>
    <body>
    <p>What is the name(s) of your browser?</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>
    <script>

    function myFunction() { 
     if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        alert('Opera');
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1 )
    {
        alert('Chrome');
    }
    else if(navigator.userAgent.indexOf("Safari") != -1)
    {
        alert('Safari');
    }
    else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
         alert('Firefox');
    }
    else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
    {
      alert('IE'); 
    }  
    else 
    {
       alert('unknown');
    }
    }
    </script>

    </body>
    </html>

And if you need to know only IE Browser version then you can follow below code. This code works well for version IE6 to IE11

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               

            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                if (navigator.appName == 'Netscape') {
                    var ua = navigator.userAgent;
                    var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null) {
                        rv = parseFloat(RegExp.$1);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>

Is div inside list allowed?

I see you would want to do this if you wanted to make, say, the whole box of a menu item clickable. I used to insert an 'li' tag in 'a' tags to do this but this seems more valid.

How do you get git to always pull from a specific branch?

I find it hard to remember the exact git config or git branch arguments as in mipadi's and Casey's answers, so I use these 2 commands to add the upstream reference:

git pull origin master
git push -u origin master

This will add the same info to your .git/config, but I find it easier to remember.

Images can't contain alpha channels or transparencies

Photoshop

  1. Slice it
  2. Save for web
  3. Uncheck Transparency

jQuery serialize does not register checkboxes

This will set your form checkbox values to booleans using their checked state.

var form = $('#myForm');
var data = form.serializeObject();

$('#myForm input[type=checkbox]').each(function() { data[this.name] = this.checked; });

The framework we use creates two inputs with the same name, which leads to unexpected behavior when serializing the form. I would get each checkbox value parsed as a two-element array with string values. Depending on how you map data server-side, you may get unintended results.

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to generate a random int in C?

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

void main() 
{
    int visited[100];
    int randValue, a, b, vindex = 0;

    randValue = (rand() % 100) + 1;

    while (vindex < 100) {
        for (b = 0; b < vindex; b++) {
            if (visited[b] == randValue) {
                randValue = (rand() % 100) + 1;
                b = 0;
            }
        }

        visited[vindex++] = randValue;
    }

    for (a = 0; a < 100; a++)
        printf("%d ", visited[a]);
}

Fully custom validation error message with Rails

Here is my code that can be useful for you in case you still need it: My model:

validates :director, acceptance: {message: "^Please confirm that you are a director of the company."}, on: :create, if: :is_director?

Then I have created a helper to show messages:

module ErrorHelper
  def error_messages!
    return "" unless error_messages?
    messages = resource.errors.full_messages.map { |msg|
       if msg.present? && !msg.index("^").nil?
         content_tag(:p, msg.slice((msg.index("^")+1)..-1))
       else
         content_tag(:p, msg)
       end
    }.join

    html = <<-HTML
      <div class="general-error alert show">
        #{messages}
      </div>
    HTML

    html.html_safe
  end

  def error_messages?
    !resource.errors.empty?
  end
end

PHP's array_map including keys

I always like the javascript variant of array map. The most simple version of it would be:

/**
 * @param  array    $array
 * @param  callable $callback
 * @return array
 */
function arrayMap(array $array, callable $callback)
{
    $newArray = [];

    foreach( $array as $key => $value )
    {
        $newArray[] = call_user_func($callback, $value, $key, $array);
    }

    return $newArray;
}

So now you can just pass it a callback function how to construct the values.

$testArray = [
    "first_key" => "first_value", 
    "second_key" => "second_value"
];

var_dump(
    arrayMap($testArray, function($value, $key) {
        return $key . ' loves ' . $value;
    });
);

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

You could add it:

public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {
    //parse the string into property names
    //Use reflection to get and sort by properties
    //something like

    foreach( string propname in queryString.Split(','))
        input.OrderBy( x => GetPropertyValue( x, propname ) );

    // I used Kjetil Watnedal's reflection example
}

The GetPropertyValue function is from Kjetil Watnedal's answer

The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT's answer).

If you're dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.

Cut off text in string after/before separator in powershell

I had a dir full of files including some that were named invoice no-product no.pdf and wanted to sort these by product no, so...

get-childitem *.pdf | sort-object -property @{expression={$\_.name.substring($\_.name.indexof("-")+1)}}

Note that in the absence of a - this sorts by $_.name

Just get column names from hive table

If you simply want to see the column names this one line should provide it without changing any settings:

describe database.tablename;

However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:

use database;
describe tablename;

RestSharp JSON Parameter Posting

In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:

request.AddJsonBody(new { A = "foo", B = "bar" });

This method sets content type to application/json and serializes the object to a JSON string.

PHP Error: Function name must be a string

In PHP.js, $_COOKIE is a function ;-)

function $_COOKIE(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length).replace(/\+/g, '%20'));
    }
    return null;
}

via http://phpjs.org/functions/setcookie:509

How to get multiple counts with one SQL query?

I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.

select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;

Result:

-------------------
| String  | Count |
-------------------
| table1  | 123   |
| table2  | 234   |
| table3  | 345   |
| table4  | 456   |
| table5  | 567   |
-------------------

Fixed height and width for bootstrap carousel

set style="height:300px !important;" and "imgBanner" for img tag.

<img src="/image/1.jpg" class="imgBanner" style="width:100%; height:300px !important;">

then if you want responsive image, so you can use jquery as:

$.(function(){
   $(window).resize(respWhenResize);
   respWhenResize();
 })



respWhenResize(){
 
       if (pagesize < 578) {
         $('.imgBanner').css('height','200px')
        } else if (pagesize > 578 ) {
            $('.imgBanner').css('height','300px')
        }
     }

How to see docker image contents

EXPLORING DOCKER IMAGE!

  1. Figure out what kind of shell is in there bash or sh...

Inspect the image first: docker inspect name-of-container-or-image

Look for entrypoint or cmd in the JSON return.

  1. Then do: docker run --rm -it --entrypoint=/bin/bash name-of-image

once inside do: ls -lsa or any other shell command like: cd ..

The -it stands for interactive... and TTY. The --rm stands for remove container after run.

If there are no common tools like ls or bash present and you have access to the Dockerfile simple add the common tool as a layer.
example (alpine Linux):

RUN apk add --no-cache bash

And when you don't have access to the Dockerfile then just copy/extract the files from a newly created container and look through them:

docker create <image>  # returns container ID the container is never started.
docker cp <container ID>:<source_path> <destination_path>
docker rm <container ID>
cd <destination_path> && ls -lsah

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

In your state, home is initialized as an array homes: []

In your return, there is an attempt to render home (which is an array). <p>Stuff: {homes}</p>

Cannot be done this way --- If you want to render it, you need to render an array into each single item. For example: using map()

Ex: {home.map(item=>item)}

Asynchronously wait for Task<T> to complete with timeout

What about something like this?

    const int x = 3000;
    const int y = 1000;

    static void Main(string[] args)
    {
        // Your scheduler
        TaskScheduler scheduler = TaskScheduler.Default;

        Task nonblockingTask = new Task(() =>
            {
                CancellationTokenSource source = new CancellationTokenSource();

                Task t1 = new Task(() =>
                    {
                        while (true)
                        {
                            // Do something
                            if (source.IsCancellationRequested)
                                break;
                        }
                    }, source.Token);

                t1.Start(scheduler);

                // Wait for task 1
                bool firstTimeout = t1.Wait(x);

                if (!firstTimeout)
                {
                    // If it hasn't finished at first timeout display message
                    Console.WriteLine("Message to user: the operation hasn't completed yet.");

                    bool secondTimeout = t1.Wait(y);

                    if (!secondTimeout)
                    {
                        source.Cancel();
                        Console.WriteLine("Operation stopped!");
                    }
                }
            });

        nonblockingTask.Start();
        Console.WriteLine("Do whatever you want...");
        Console.ReadLine();
    }

You can use the Task.Wait option without blocking main thread using another Task.

A button to start php script, how?

Having 2 files like you suggested would be the easiest solution.

For instance:

2 files solution:

index.html

(.. your html ..)
<form action="script.php" method="get">
  <input type="submit" value="Run me now!">
</form>
(...)

script.php

<?php
  echo "Hello world!"; // Your code here
?>

Single file solution:

index.php

<?php
  if (!empty($_GET['act'])) {
    echo "Hello world!"; //Your code here
  } else {
?>
(.. your html ..)
<form action="index.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="Run me now!">
</form>
<?php
  }
?>

When to use extern in C++

This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.

To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static keyword.

header:

#ifndef HEADER_H
#define HEADER_H

// any source file that includes this will be able to use "global_x"
extern int global_x;

void print_global_x();

#endif

source 1:

#include "header.h"

// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;

int main()
{
    //set global_x here:
    global_x = 5;

    print_global_x();
}

source 2:

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

void print_global_x()
{
    //print global_x here:
    std::cout << global_x << std::endl;
}

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Select all text inside EditText when it gets focus

Why don't you try android:hint="hint" to provide the hint to the user..!!

The "hint" will automatically disappear when the user clicks on the edittextbox. its the proper and best solution.

Change tab bar item selected color in a storyboard

put this code in the viewDidLoad of the view controller that you want to change the color of

[[UITabBar appearance] setSelectedImageTintColor:[UIColor whiteColor]];

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

How to verify if nginx is running or not?

This is probably system-dependent, but this is the simplest way I've found.

if [ -e /var/run/nginx.pid ]; then echo "nginx is running"; fi

That's the best solution for scripting.

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

Should 'using' directives be inside or outside the namespace?

According the to StyleCop Documentation:

SA1200: UsingDirectivesMustBePlacedWithinNamespace

Cause A C# using directive is placed outside of a namespace element.

Rule Description A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.

For example, the following code would result in two violations of this rule.

using System;
using Guid = System.Guid;

namespace Microsoft.Sample
{
    public class Program
    {
    }
}

The following code, however, would not result in any violations of this rule:

namespace Microsoft.Sample
{
    using System;
    using Guid = System.Guid;

    public class Program
    {
    }
}

This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:

namespace Microsoft.Sample
{
    using Guid = System.Guid;
    public class Guid
    {
        public Guid(string s)
        {
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Guid g = new Guid("hello");
        }
    }
}

The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");

CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'

The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.

When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.

Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.

Placing using-alias directives within the namespace element eliminates this as a source of bugs.

  1. Multiple Namespaces

Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.

It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.

How to Fix Violations To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.

IllegalArgumentException or NullPointerException for a null parameter?

Voted up Jason Cohen's argument because it was well presented. Let me dismember it step by step. ;-)

  • The NPE JavaDoc explicitly says, "other illegal uses of the null object". If it was just limited to situations where the runtime encounters a null when it shouldn't, all such cases could be defined far more succinctly.

  • Can't help it if you assume the wrong thing, but assuming encapsulation is applied properly, you really shouldn't care or notice whether a null was dereferenced inappropriately vs. whether a method detected an inappropriate null and fired an exception off.

  • I'd choose NPE over IAE for multiple reasons

    • It is more specific about the nature of the illegal operation
    • Logic that mistakenly allows nulls tends to be very different from logic that mistakenly allows illegal values. For example, if I'm validating data entered by a user, if I get value that is unacceptable, the source of that error is with the end user of the application. If I get a null, that's programmer error.
    • Invalid values can cause things like stack overflows, out of memory errors, parsing exceptions, etc. Indeed, most errors generally present, at some point, as an invalid value in some method call. For this reason I see IAE as actually the MOST GENERAL of all exceptions under RuntimeException.
  • Actually, other invalid arguments can result in all kinds of other exceptions. UnknownHostException, FileNotFoundException, a variety of syntax error exceptions, IndexOutOfBoundsException, authentication failures, etc., etc.

In general, I feel NPE is much maligned because traditionally has been associated with code that fails to follow the fail fast principle. That, plus the JDK's failure to populate NPE's with a message string really has created a strong negative sentiment that isn't well founded. Indeed, the difference between NPE and IAE from a runtime perspective is strictly the name. From that perspective, the more precise you are with the name, the more clarity you give to the caller.

Spring Bean Scopes

Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary

Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype - Scopes a single bean definition to any number of object instances.

request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Parsing Query String in node.js

node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

Node.js create folder or use existing

You can do all of this with the File System module.

const
  fs = require('fs'),
  dirPath = `path/to/dir`

// Check if directory exists.
fs.access(dirPath, fs.constants.F_OK, (err)=>{
  if (err){
    // Create directory if directory does not exist.
    fs.mkdir(dirPath, {recursive:true}, (err)=>{
      if (err) console.log(`Error creating directory: ${err}`)
      else console.log('Directory created successfully.')
    })
  }
  // Directory now exists.
})

You really don't even need to check if the directory exists. The following code also guarantees that the directory either already exists or is created.

const
  fs = require('fs'),
  dirPath = `path/to/dir`

// Create directory if directory does not exist.
fs.mkdir(dirPath, {recursive:true}, (err)=>{
  if (err) console.log(`Error creating directory: ${err}`)
  // Directory now exists.
})

How to get 30 days prior to current date?

Simple 1 liner Vanilla Javascript code :

const priorByDays = new Date(Date.now() - days * 24 * 60 * 60 * 1000)

For example: days = 7 Assume current date = Fri Sep 18 2020 01:33:26 GMT+0530

The result would be : Fri Sep 11 2020 01:34:03 GMT+0530

The beauty of this is you can manipulate it to get result in desired type

  • timestamp : Date.now() - days * 24 * 60 * 60 * 1000

  • ISOString: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()

Split text with '\r\n'

The problem is not with the splitting but rather with the WriteLine. A \n in a string printed with WriteLine will produce an "extra" line.

Example

var text = 
  "somet interesting text\n" +
  "some text that should be in the same line\r\n" +
  "some text should be in another line";

string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
   Console.WriteLine(s); //But will print 3 lines in total.
}

To fix the problem remove \n before you print the string.

Console.WriteLine(s.Replace("\n", ""));

Convert string to Boolean in javascript

Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is

var setActive = 'true'; 
setActive = setActive == "true";

if(setActive)
// statements
else
// statements.

Forwarding port 80 to 8080 using NGINX

you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _ your_domain;

    location /health {
            access_log off;
            return 200 "healthy\n";
    }

    location / {
            proxy_pass http://localhost:8080; 
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache_bypass $http_upgrade;
    }
  }

What is the proper way to display the full InnerException?

If you're using Entity Framework, exception.ToString() will not gives you the details of DbEntityValidationException exceptions. You might want to use the same method to handle all your exception, like:

catch (Exception ex)
{
   Log.Error(GetExceptionDetails(ex));
}

Where GetExceptionDetails contains something like this:

public static string GetExceptionDetails(Exception ex)
{
    var stringBuilder = new StringBuilder();

    while (ex != null)
    {
        switch (ex)
        {
            case DbEntityValidationException dbEx:
                var errorMessages = dbEx.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
                var fullErrorMessage = string.Join("; ", errorMessages);
                var message = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                stringBuilder.Insert(0, dbEx.StackTrace);
                stringBuilder.Insert(0, message);
                break;

            default:
                stringBuilder.Insert(0, ex.StackTrace);
                stringBuilder.Insert(0, ex.Message);
                break;
        }

        ex = ex.InnerException;
    }

    return stringBuilder.ToString();
}

Subtracting time.Duration from time in Go

In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    count := 10
    then := now.Add(time.Duration(-count) * time.Minute)
    // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
    // then := now.Add(-10 * time.Minute)
    fmt.Println("10 minutes ago:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC

Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.

Playground: https://play.golang.org/p/DzzH4SA3izp

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next

Adding :default => true to boolean in existing Rails column

If you just made a migration, you can rollback and then make your migration again.

To rollback you can do as many steps as you want:

rake db:rollback STEP=1

Or, if you are using Rails 5.2 or newer:

rails db:rollback STEP=1

Then, you can just make the migration again:

def change
  add_column :profiles, :show_attribute, :boolean, default: true
end

Don't forget to rake db:migrate and if you are using heroku heroku run rake db:migrate

Improve INSERT-per-second performance of SQLite

Avoid sqlite3_clear_bindings(stmt).

The code in the test sets the bindings every time through which should be enough.

The C API intro from the SQLite docs says:

Prior to calling sqlite3_step() for the first time or immediately after sqlite3_reset(), the application can invoke the sqlite3_bind() interfaces to attach values to the parameters. Each call to sqlite3_bind() overrides prior bindings on the same parameter

There is nothing in the docs for sqlite3_clear_bindings saying you must call it in addition to simply setting the bindings.

More detail: Avoid_sqlite3_clear_bindings()

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

How to drop columns using Rails migration

Simply, You can remove column

remove_column :table_name, :column_name

For Example,

remove_column :posts, :comment

How to create our own Listener interface in android?

In the year of 2018, there's no need for listeners interfaces. You've got Android LiveData to take care of passing the desired result back to the UI components.

If I'll take Rupesh's answer and adjust it to use LiveData, it will like so:

public class Event {

    public LiveData<EventResult> doEvent() {
         /*
          * code code code
          */

         // and in the end

         LiveData<EventResult> result = new MutableLiveData<>();
         result.setValue(eventResult);
         return result;
    }
}

and now in your driver class MyTestDriver:

public class MyTestDriver {
    public static void main(String[] args) {
        Event e = new Event();
        e.doEvent().observe(this, new  Observer<EventResult>() {
            @Override
            public void onChanged(final EventResult er) {
                // do your work.
            }
        });
    }
}

For more information along with code samples you can read my post about it, as well as the offical docs:

When and why to use LiveData

Official docs

Why is this jQuery click function not working?

Be sure there is nothing on your button (such a div or a trasparent img) that keeps from clicking the button. It sounds stupid, but sometimes we think that jQuery is not working and all that stuffs and the problem is on the positioning of DOM elements.