Programs & Examples On #Datagrid

A graphical user interface element that presents a tabular view of data.

Adding a Button to a WPF DataGrid

XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable 
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) yield return row;
    }
}

void Button_Click_dgvs(object sender, RoutedEventArgs e)
{

    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);
            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                 break;
            }
            break;
        }
}

After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

How to hide column of DataGridView when using custom DataSource?

Just set DataGridView.AutoGenerateColumns = false;

You need click on the arrow on top right corner (in datagridview) to add columns, and in DataPropertyName you need to put a name of your property in your class.

Then, after you defined your columns in datagridview, you can set datagridview.datasource = myClassViewModel.

How do I bind a List<CustomObject> to a WPF DataGrid?

You should do it in the xaml code:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged.

Adding values to specific DataTable cells

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

how can I enable scrollbars on the WPF Datagrid?

In my case I had to set MaxHeight and replace IsEnabled="False" by IsReadOnly="True"

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Consider this snippet of code. Modify as you see fit, or to fit your requirements. You'll need to have Imports statements for System.IO and System.Data.OleDb.

Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName

Dim conn As New OleDbConnection(connectionString)
conn.Open()

'the SELECT statement is important here, 
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)

Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect

Dim ds As New DataSet
adapter1.Fill(ds, "DATA")

myDataGridView.DataSource = ds.Tables(0).DefaultView 
myDataGridView.DataBind
conn.Close()

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

How to clear a data grid view

IF you want to clear not only Data, but also ComboBoxes, Checkboxes, try

dataGridView.Columns.Clear();

Change DataGrid cell colour based on values

If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.

C#

public class ValueToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int input;
        try
        {
            DataGridCell dgc = (DataGridCell)value;
            System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
            input = (int)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
        }
        catch (InvalidCastException e)
        {
            return DependencyProperty.UnsetValue;
        }
        switch (input)
        {
            case 1: return Brushes.Red;
            case 2: return Brushes.White;
            case 3: return Brushes.Blue;
            default: return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML

<UserControl.Resources>
    <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
    </Style>
</UserControl.Resources>
<DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
</DataGrid>

WPF Datagrid set selected row

// In General to Access all rows //

foreach (var item in dataGrid1.Items)
{
    string str = ((DataRowView)dataGrid1.Items[1]).Row["ColumnName"].ToString();
}

//To Access Selected Rows //

private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {
        string str = ((DataRowView)dataGrid1.SelectedItem).Row["ColumnName"].ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

JavaScript data grid for millions of rows

Disclaimer: i heavily use YUI DataTable without no headache for a long time. It is powerful and stable. For your needs, you can use a ScrollingDataTable wich suports

  • x-scrolling
  • y-scrolling
  • xy-scrolling
  • A powerful Event mechanism

For what you need, i think you want is a tableScrollEvent. Its API says

Fired when a fixed scrolling DataTable has a scroll.

As each DataTable uses a DataSource, you can monitoring its data through tableScrollEvent along with render loop size in order to populate your ScrollingDataTable according to your needs.

Render loop size says

In cases where your DataTable needs to display the entirety of a very large set of data, the renderLoopSize config can help manage browser DOM rendering so that the UI thread does not get locked up on very large tables. Any value greater than 0 will cause the DOM rendering to be executed in setTimeout() chains that render the specified number of rows in each loop. The ideal value should be determined per implementation since there are no hard and fast rules, only general guidelines:

  • By default renderLoopSize is 0, so all rows are rendered in a single loop. A renderLoopSize > 0 adds overhead so use thoughtfully.
  • If your set of data is large enough (number of rows X number of Columns X formatting complexity) that users experience latency in the visual rendering and/or it causes the script to hang, consider setting a renderLoopSize.
  • A renderLoopSize under 50 probably isn't worth it. A renderLoopSize > 100 is probably better.
  • A data set is probably not considered large enough unless it has hundreds and hundreds of rows.
  • Having a renderLoopSize > 0 and < total rows does cause the table to be rendered in one loop (same as renderLoopSize = 0) but it also triggers functionality such as post-render row striping to be handled from a separate setTimeout thread.

For instance

// Render 100 rows per loop
 var dt = new YAHOO.widget.DataTable(<WHICH_DIV_WILL_STORE_YOUR_DATATABLE>, <HOW YOUR_TABLE_IS STRUCTURED>, <WHERE_DOES_THE_DATA_COME_FROM>, {
     renderLoopSize:100
 });

<WHERE_DOES_THE_DATA_COME_FROM> is just a single DataSource. It can be a JSON, JSFunction, XML and even a single HTML element

Here you can see a Simple tutorial, provided by me. Be aware no other DATA_TABLE pluglin supports single and dual click at the same time. YUI DataTable allows you. And more, you can use it even with JQuery without no headache

Some examples, you can see

Feel free to question about anything else you want about YUI DataTable.

regards,

How do I bind a WPF DataGrid to a variable number of columns?

There is a sample of the way I do programmatically:

public partial class UserControlWithComboBoxColumnDataGrid : UserControl
{
    private Dictionary<int, string> _Dictionary;
    private ObservableCollection<MyItem> _MyItems;
    public UserControlWithComboBoxColumnDataGrid() {
      _Dictionary = new Dictionary<int, string>();
      _Dictionary.Add(1,"A");
      _Dictionary.Add(2,"B");
      _MyItems = new ObservableCollection<MyItem>();
      dataGridMyItems.AutoGeneratingColumn += DataGridMyItems_AutoGeneratingColumn;
      dataGridMyItems.ItemsSource = _MyItems;

    }
private void DataGridMyItems_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var desc = e.PropertyDescriptor as PropertyDescriptor;
            var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
            if (att != null)
            {
                if (att.Name == "My Combobox Item") {
                    var comboBoxColumn =  new DataGridComboBoxColumn {
                        DisplayMemberPath = "Value",
                        SelectedValuePath = "Key",
                        ItemsSource = _ApprovalTypes,
                        SelectedValueBinding =  new Binding( "Bazinga"),   
                    };
                    e.Column = comboBoxColumn;
                }

            }
        }

}
public class MyItem {
    public string Name{get;set;}
    [ColumnName("My Combobox Item")]
    public int Bazinga {get;set;}
}

  public class ColumnNameAttribute : Attribute
    {
        public string Name { get; set; }
        public ColumnNameAttribute(string name) { Name = name; }
}

How to bind DataTable to Datagrid

using (SqlCeConnection con = new SqlCeConnection())
   {
   con.ConnectionString = connectionString;
   con.Open();
   SqlCeCommand com = new SqlCeCommand("SELECT S_no,Name,Father_Name")
   SqlCeDataAdapter sda = new SqlCeDataAdapter(com);
   System.Data.DataTable dt = new System.Data.DataTable();
   sda.Fill(dt);
   dataGrid1.ItemsSource = dt.DefaultView;
   dataGrid1.AutoGenerateColumns = true;
   dataGrid1.CanUserAddRows = false;
   }

Get selected row item in DataGrid WPF

If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

WPF Datagrid Get Selected Cell Value

you can also use this function.

 public static void GetGridSelectedView(out string tuid, ref DataGrid dataGrid,string Column)
    {
        try
        {
            // grid selected row values
            var item = dataGrid.SelectedItem as DataRowView;
            if (null == item) tuid = null;
            if (item.DataView.Count > 0)
            {
                tuid =  item.DataView[dataGrid.SelectedIndex][Column].ToString().Trim();
            }
            else { tuid = null; }
        }
        catch (Exception exc) { System.Windows.MessageBox.Show(exc.Message); tuid = null; }
    }

programmatically add column & rows to WPF Datagrid

I had the same problem. Adding new rows to WPF DataGrid requires a trick. DataGrid relies on property fields of an item object. ExpandoObject enables to add new properties dynamically. The code below explains how to do it:

// using System.Dynamic;

DataGrid dataGrid;

string[] labels = new string[] { "Column 0", "Column 1", "Column 2" };

foreach (string label in labels)
{
    DataGridTextColumn column = new DataGridTextColumn();
    column.Header = label;
    column.Binding = new Binding(label.Replace(' ', '_'));

    dataGrid.Columns.Add(column);
}

int[] values = new int[] { 0, 1, 2 };

dynamic row = new ExpandoObject();

for (int i = 0; i < labels.Length; i++)
    ((IDictionary<String, Object>)row)[labels[i].Replace(' ', '_')] = values[i];

dataGrid.Items.Add(row);

//edit:

Note that this is not the way how the component should be used, however, it simplifies a lot if you have only programmatically generated data (eg. in my case: a sequence of features and neural network output).

DataGrid get selected rows' column values

UPDATED

To get the selected rows try:

IList rows = dg.SelectedItems;

You should then be able to get to the column value from a row item.

OR

DataRowView row = (DataRowView)dg.SelectedItems[0];

Then:

row["ColumnName"];

How can I set the color of a selected row in DataGrid

The above solution left blue border around each cell in my case.

This is the solution that worked for me. It is very simple, just add this to your DataGrid. You can change it from a SolidColorBrush to any other brush such as linear gradient.

<DataGrid.Resources>
  <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                   Color="#FF0000"/>
</DataGrid.Resources>

Date formatting in WPF datagrid

This is a very old question, but I found a new solution, so I wrote about it.

First of all, is this way of solution possible while using AutoGenerateColumns?

Yes, that can be done with AttachedProperty as follows.

<DataGrid AutoGenerateColumns="True" 
   local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
   ItemsSource="{Binding}" />

AttachedProperty

There are two AttachedProperty defined that allow you to specify two formats. DateTimeFormatAutoGenerate for DateTime and TimeSpanFormatAutoGenerate for TimeSpan.

class DataGridOperation
{
    public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
    public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));

    public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
    public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
    public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
        DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
            new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));

    private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is DataGrid dGrid))
            return;

        if ((e.NewValue is string format))
            dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
    }

    private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
    {
        if (e.PropertyType == typeof(T))
            (e.Column as DataGridTextColumn).Binding.StringFormat = format;
    }
}

How to use

View

<Window
   x:Class="DataGridAutogenerateCustom.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:DataGridAutogenerateCustom"
   Width="400" Height="250">
   <Window.DataContext>
      <local:MainWindowViewModel />
   </Window.DataContext>
   <StackPanel>
      <TextBlock Text="DEFAULT FORMAT" />
      <DataGrid ItemsSource="{Binding Dates}" />

      <TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
      <DataGrid
         local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
         local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
         ItemsSource="{Binding Dates}" />
   </StackPanel>
</Window>

ViewModel

public class MainWindowViewModel
{
    public DatePairs[] Dates { get; } = new DatePairs[]
    {
        new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
        new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
    };
}

public class DatePairs
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan Span => EndDate - StartDate;
}

demo_wpf_datagrid

How do I make XAML DataGridColumns fill the entire DataGrid?

Make sure your DataGrid has Width set to something like {Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window,AncestorLevel=1}}.

Like that, your setting of Width="*" attribute on DataGrid.Columns/DataGridXXXXColumn elements should work.

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

How to add data to DataGridView

Let's assume you have a class like this:

public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And assume you have dragged and dropped a DataGridView to your form, and name it dataGridView1.

You need a BindingSource to hold your data to bind your DataGridView. This is how you can do it:

private void frmDGV_Load(object sender, EventArgs e)
{
    //dummy data
    List<Staff> lstStaff = new List<Staff>();
    lstStaff.Add(new Staff()
    {
        ID = 1,
        Name = "XX"
    });
    lstStaff.Add(new Staff()
    {
        ID = 2,
        Name = "YY"
    });

    //use binding source to hold dummy data
    BindingSource binding = new BindingSource();
    binding.DataSource = lstStaff;

    //bind datagridview to binding source
    dataGridView1.DataSource = binding;
}

How to uninstall Anaconda completely from macOS

Open the terminal and remove your entire Anaconda directory, which will have a name such as “anaconda2” or “anaconda3”, by entering the following command: rm -rf ~/anaconda3. Then remove conda with command "conda uninstall" https://conda.io/docs/commands/conda-uninstall.html.

How many characters can a Java String have?

I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java.

Which command in VBA can count the number of characters in a string variable?

Len is what you want.

word = "habit"  
length = Len(word)

Get first key in a (possibly) associative array?

2019 Update

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.


You can use reset and key:

reset($array);
$first_key = key($array);

It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.

Just remember to call reset, or you may get any of the keys in the array. You can also use end instead of reset to get the last key.

If you wanted the key to get the first value, reset actually returns it:

$first_value = reset($array);

There is one special case to watch out for though (so check the length of the array first):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)

C# generic list <T> how to get the type of T?

Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:

public abstract class CollectionBase<T> : IList<T>
{
   ...

   public Type ElementType
   {
      get
      {
         return typeof(T);
      }
   }
}

I have found this approach useful, and is easy to understand for any newcomers to generics.

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

Error:Unable to locate adb within SDK in Android Studio

It's worked for me (Android Studio 3.1.3):

1. Make sure that 'Android SDK Platform-Tools' is installed:

Tools > SDK Manager > SDK Tools (Tab)

2. Copy path of 'adb.exe' file. Usually here:

C:\Users\Username\AppData\Local\Android\Sdk\platform-tools

3. Open Enviroment Variables in Windows:

'Window + R' > and type 'SystemPropertiesAdvanced'> Enviroment Variables...

4. Create new system variable with name 'PATH' and value of your adb.exe path like that 'C:\Users\Username\AppData\Local\Android\Sdk\platform-tools'

Can you hide the controls of a YouTube embed without enabling autoplay?

?modestbranding=1&autohide=1&showinfo=0&controls=0

autohide=1

is something that I never found... but it was the key :) I hope it's help

Disabling Chrome Autofill

For me, simple

<form autocomplete="off" role="presentation">

Did it.

Tested on multiple versions, last try was on 56.0.2924.87

How do you use script variables in psql?

I've posted a new solution for this on another thread.

It uses a table to store variables, and can be updated at any time. A static immutable getter function is dynamically created (by another function), triggered by update to your table. You get nice table storage, plus the blazing fast speeds of an immutable getter.

How to install "ifconfig" command in my ubuntu docker image?

In case you want to use the Docker image as a "regular" Ubuntu installation, you can also run unminimize. This will install a lot more than ifconfig, so this might not be what you want.

How do you refresh the MySQL configuration file without restarting?

You were so close! The kill -HUP method wasn't working for me either.

You were calling:

select @@global.max_connections;

All you needed was to set instead of select:

set @@global.max_connections = 400;

See:

http://www.netadmintools.com/art573.html

http://www.electrictoolbox.com/update-max-connections-mysql/

How to get longitude and latitude of any address?

You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

Getting pids from ps -ef |grep keyword

This is available on linux: pidof keyword

Is there a naming convention for MySQL?

MySQL has a short description of their more or less strict rules:

https://dev.mysql.com/doc/internals/en/coding-style.html

Most common codingstyle for MySQL by Simon Holywell:

http://www.sqlstyle.guide/

See also this question: Are there any published coding style guidelines for SQL?

How to enable Logger.debug() in Log4j

Here's a quick one-line hack that I occasionally use to temporarily turn on log4j debug logging in a JUnit test:

Logger.getRootLogger().setLevel(Level.DEBUG);

or if you want to avoid adding imports:

org.apache.log4j.Logger.getRootLogger().setLevel(
      org.apache.log4j.Level.DEBUG);

Note: this hack doesn't work in log4j2 because setLevel has been removed from the API, and there doesn't appear to be equivalent functionality.

bash: pip: command not found

Install Python latest version as given here

It has many download links like numpy and scipy

Then go to terminal and enter following command:-

sudo easy_install pip

For Python install packages check this

Requirements for Installing Packages This section describes the steps to follow before installing other Python packages.

Install pip, setuptools, and wheel If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setuptools, but will need to upgrade to the latest version:

On Linux or OS X:

pip install -U pip setuptools On Windows:

python -m pip install -U pip setuptools If you’re using a Python install on Linux that’s managed by the system package manager (e.g “yum”, “apt-get” etc…), and you want to use the system package manager to install or upgrade pip, then see Installing pip/setuptools/wheel with Linux Package Managers

Otherwise:

Securely Download get-pip.py 1

Run python get-pip.py. 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.

Inheritance and Overriding __init__ in python

The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

Maven Jacoco Configuration - Exclude classes/packages from report not working

https://github.com/jacoco/jacoco/issues/34

These are the different notations for classes we have:

  • VM Name: java/util/Map$Entry
  • Java Name: java.util.Map$Entry File
  • Name: java/util/Map$Entry.class

Agent Parameters, Ant tasks and Maven prepare-agent goal

  • includes: Java Name (VM Name also works)
  • excludes: Java Name (VM Name also works)
  • exclclassloader: Java Name

These specifications allow wildcards * and ?, where * wildcards any number of characters, even multiple nested folders.

Maven report goal

  • includes: File Name
  • excludes: File Name

These specs allow Ant Filespec like wildcards *, ** and ?, where * wildcards parts of a single path element only.

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

Fastest way to Remove Duplicate Value from a list<> by lambda

The easiest way to get a new list would be:

List<long> unique = longs.Distinct().ToList();

Is that good enough for you, or do you need to mutate the existing list? The latter is significantly more long-winded.

Note that Distinct() isn't guaranteed to preserve the original order, but in the current implementation it will - and that's the most natural implementation. See my Edulinq blog post about Distinct() for more information.

If you don't need it to be a List<long>, you could just keep it as:

IEnumerable<long> unique = longs.Distinct();

At this point it will go through the de-duping each time you iterate over unique though. Whether that's good or not will depend on your requirements.

How to use Oracle's LISTAGG function with a unique filter?

below is undocumented and not recomended by oracle. and can not apply in function, show error

select wm_concat(distinct name) as names from demotable group by group_id

regards zia

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

Disable Drag and Drop on HTML elements?

For input elements, this answer works for me.

I implemented it on a custom input component in Angular 4, but I think it could be implemented with pure JS.

HTML

<input type="text" [(ngModel)]="value" (ondragenter)="disableEvent($event)" 
(dragover)="disableEvent($event)" (ondrop)="disableEvent($event)"/>

Component definition (JS):

export class CustomInputComponent { 

  //component construction and attribute definitions

  disableEvent(event) {
    event.preventDefault();
    return false;
  }
}

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

How to concatenate int values in java?

Using Java 8 and higher, you can use the StringJoiner, a very clean and more flexible way (especially if you have a list as input instead of known set of variables a-e):

int a = 1;
int b = 0;
int c = 2;
int d = 2;
int e = 1;
List<Integer> values = Arrays.asList(a, b, c, d, e);
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining());
System.out.println(result);

If you need a separator use:

String result = values.stream().map(i -> i.toString()).collect(Collectors.joining(","));

To get the following result:

1,0,2,2,1

Edit: as LuCio commented, the following code is shorter:

Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining());

How to find list of possible words from a letter matrix [Boggle Solver]

My attempt in Java. It takes about 2 s to read file and build trie, and around 50 ms to solve the puzzle. I used the dictionary linked in the question (it has a few words that I didn't know exist in English such as fae, ima)

0 [main] INFO gineer.bogglesolver.util.Util  - Reading the dictionary
2234 [main] INFO gineer.bogglesolver.util.Util  - Finish reading the dictionary
2234 [main] INFO gineer.bogglesolver.Solver  - Found: FAM
2234 [main] INFO gineer.bogglesolver.Solver  - Found: FAME
2234 [main] INFO gineer.bogglesolver.Solver  - Found: FAMBLE
2234 [main] INFO gineer.bogglesolver.Solver  - Found: FAE
2234 [main] INFO gineer.bogglesolver.Solver  - Found: IMA
2234 [main] INFO gineer.bogglesolver.Solver  - Found: ELI
2234 [main] INFO gineer.bogglesolver.Solver  - Found: ELM
2234 [main] INFO gineer.bogglesolver.Solver  - Found: ELB
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AXIL
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AXILE
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AXLE
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AMI
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AMIL
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AMLI
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AME
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AMBLE
2234 [main] INFO gineer.bogglesolver.Solver  - Found: AMBO
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AES
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWEST
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MIX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MIL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MILE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MILO
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MAX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MAE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MAW
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MEW
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MEWL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MES
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MESA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: MWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIMA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIMAX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIME
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIMES
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIMB
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIMBO
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LIMBU
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LEI
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LEO
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LOB
2250 [main] INFO gineer.bogglesolver.Solver  - Found: LOX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: OIME
2250 [main] INFO gineer.bogglesolver.Solver  - Found: OIL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: OLE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: OLM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: EMIL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: EMBOLE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: EMBOX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: EAST
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAF
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAME
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAMBLE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WEA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WEAM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WEM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WEA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WES
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WEST
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAS
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WASE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: WAST
2250 [main] INFO gineer.bogglesolver.Solver  - Found: BLEO
2250 [main] INFO gineer.bogglesolver.Solver  - Found: BLO
2250 [main] INFO gineer.bogglesolver.Solver  - Found: BOIL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: BOLE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: BUT
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AES
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWL
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AWEST
2250 [main] INFO gineer.bogglesolver.Solver  - Found: ASE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: ASEM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: AST
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEAX
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEAM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEMI
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEMBLE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEW
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SEA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SWAM
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SWAMI
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SAW
2250 [main] INFO gineer.bogglesolver.Solver  - Found: SAWT
2250 [main] INFO gineer.bogglesolver.Solver  - Found: STU
2250 [main] INFO gineer.bogglesolver.Solver  - Found: STUB
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TWAE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TWA
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TWAE
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TWAS
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TUB
2250 [main] INFO gineer.bogglesolver.Solver  - Found: TUX

Source code consists of 6 classes. I'll post them below (if this is not the right practice on StackOverflow, please tell me).

gineer.bogglesolver.Main

package gineer.bogglesolver;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Main
{
    private final static Logger logger = Logger.getLogger(Main.class);

    public static void main(String[] args)
    {
        BasicConfigurator.configure();

        Solver solver = new Solver(4,
                        "FXIE" +
                        "AMLO" +
                        "EWBX" +
                        "ASTU");
        solver.solve();

    }
}

gineer.bogglesolver.Solver

package gineer.bogglesolver;

import gineer.bogglesolver.trie.Trie;
import gineer.bogglesolver.util.Constants;
import gineer.bogglesolver.util.Util;
import org.apache.log4j.Logger;

public class Solver
{
    private char[] puzzle;
    private int maxSize;

    private boolean[] used;
    private StringBuilder stringSoFar;

    private boolean[][] matrix;
    private Trie trie;

    private final static Logger logger = Logger.getLogger(Solver.class);

    public Solver(int size, String puzzle)
    {
        trie = Util.getTrie(size);
        matrix = Util.connectivityMatrix(size);

        maxSize = size * size;
        stringSoFar = new StringBuilder(maxSize);
        used = new boolean[maxSize];

        if (puzzle.length() == maxSize)
        {
            this.puzzle = puzzle.toCharArray();
        }
        else
        {
            logger.error("The puzzle size does not match the size specified: " + puzzle.length());
            this.puzzle = puzzle.substring(0, maxSize).toCharArray();
        }
    }

    public void solve()
    {
        for (int i = 0; i < maxSize; i++)
        {
            traverseAt(i);
        }
    }

    private void traverseAt(int origin)
    {
        stringSoFar.append(puzzle[origin]);
        used[origin] = true;

        //Check if we have a valid word
        if ((stringSoFar.length() >= Constants.MINIMUM_WORD_LENGTH) && (trie.containKey(stringSoFar.toString())))
        {
            logger.info("Found: " + stringSoFar.toString());
        }

        //Find where to go next
        for (int destination = 0; destination < maxSize; destination++)
        {
            if (matrix[origin][destination] && !used[destination] && trie.containPrefix(stringSoFar.toString() + puzzle[destination]))
            {
                traverseAt(destination);
            }
        }

        used[origin] = false;
        stringSoFar.deleteCharAt(stringSoFar.length() - 1);
    }

}

gineer.bogglesolver.trie.Node

package gineer.bogglesolver.trie;

import gineer.bogglesolver.util.Constants;

class Node
{
    Node[] children;
    boolean isKey;

    public Node()
    {
        isKey = false;
        children = new Node[Constants.NUMBER_LETTERS_IN_ALPHABET];
    }

    public Node(boolean key)
    {
        isKey = key;
        children = new Node[Constants.NUMBER_LETTERS_IN_ALPHABET];
    }

    /**
     Method to insert a string to Node and its children

     @param key the string to insert (the string is assumed to be uppercase)
     @return true if the node or one of its children is changed, false otherwise
     */
    public boolean insert(String key)
    {
        //If the key is empty, this node is a key
        if (key.length() == 0)
        {
            if (isKey)
                return false;
            else
            {
                isKey = true;
                return true;
            }
        }
        else
        {//otherwise, insert in one of its child

            int childNodePosition = key.charAt(0) - Constants.LETTER_A;
            if (children[childNodePosition] == null)
            {
                children[childNodePosition] = new Node();
                children[childNodePosition].insert(key.substring(1));
                return true;
            }
            else
            {
                return children[childNodePosition].insert(key.substring(1));
            }
        }
    }

    /**
     Returns whether key is a valid prefix for certain key in this trie.
     For example: if key "hello" is in this trie, tests with all prefixes "hel", "hell", "hello" return true

     @param prefix the prefix to check
     @return true if the prefix is valid, false otherwise
     */
    public boolean containPrefix(String prefix)
    {
        //If the prefix is empty, return true
        if (prefix.length() == 0)
        {
            return true;
        }
        else
        {//otherwise, check in one of its child
            int childNodePosition = prefix.charAt(0) - Constants.LETTER_A;
            return children[childNodePosition] != null && children[childNodePosition].containPrefix(prefix.substring(1));
        }
    }

    /**
     Returns whether key is a valid key in this trie.
     For example: if key "hello" is in this trie, tests with all prefixes "hel", "hell" return false

     @param key the key to check
     @return true if the key is valid, false otherwise
     */
    public boolean containKey(String key)
    {
        //If the prefix is empty, return true
        if (key.length() == 0)
        {
            return isKey;
        }
        else
        {//otherwise, check in one of its child
            int childNodePosition = key.charAt(0) - Constants.LETTER_A;
            return children[childNodePosition] != null && children[childNodePosition].containKey(key.substring(1));
        }
    }

    public boolean isKey()
    {
        return isKey;
    }

    public void setKey(boolean key)
    {
        isKey = key;
    }
}

gineer.bogglesolver.trie.Trie

package gineer.bogglesolver.trie;

public class Trie
{
    Node root;

    public Trie()
    {
        this.root = new Node();
    }

    /**
     Method to insert a string to Node and its children

     @param key the string to insert (the string is assumed to be uppercase)
     @return true if the node or one of its children is changed, false otherwise
     */
    public boolean insert(String key)
    {
        return root.insert(key.toUpperCase());
    }

    /**
     Returns whether key is a valid prefix for certain key in this trie.
     For example: if key "hello" is in this trie, tests with all prefixes "hel", "hell", "hello" return true

     @param prefix the prefix to check
     @return true if the prefix is valid, false otherwise
     */
    public boolean containPrefix(String prefix)
    {
        return root.containPrefix(prefix.toUpperCase());
    }

    /**
     Returns whether key is a valid key in this trie.
     For example: if key "hello" is in this trie, tests with all prefixes "hel", "hell" return false

     @param key the key to check
     @return true if the key is valid, false otherwise
     */
    public boolean containKey(String key)
    {
        return root.containKey(key.toUpperCase());
    }


}

gineer.bogglesolver.util.Constants

package gineer.bogglesolver.util;

public class Constants
{

    public static final int NUMBER_LETTERS_IN_ALPHABET = 26;
    public static final char LETTER_A = 'A';
    public static final int MINIMUM_WORD_LENGTH = 3;
    public static final int DEFAULT_PUZZLE_SIZE = 4;
}

gineer.bogglesolver.util.Util

package gineer.bogglesolver.util;

import gineer.bogglesolver.trie.Trie;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Util
{
    private final static Logger logger = Logger.getLogger(Util.class);
    private static Trie trie;
    private static int size = Constants.DEFAULT_PUZZLE_SIZE;

    /**
     Returns the trie built from the dictionary.  The size is used to eliminate words that are too long.

     @param size the size of puzzle.  The maximum lenght of words in the returned trie is (size * size)
     @return the trie that can be used for puzzle of that size
     */
    public static Trie getTrie(int size)
    {
        if ((trie != null) && size == Util.size)
            return trie;

        trie = new Trie();
        Util.size = size;

        logger.info("Reading the dictionary");
        final File file = new File("dictionary.txt");
        try
        {
            Scanner scanner = new Scanner(file);
            final int maxSize = size * size;
            while (scanner.hasNext())
            {
                String line = scanner.nextLine().replaceAll("[^\\p{Alpha}]", "");

                if (line.length() <= maxSize)
                    trie.insert(line);
            }
        }
        catch (FileNotFoundException e)
        {
            logger.error("Cannot open file", e);
        }

        logger.info("Finish reading the dictionary");
        return trie;
    }

    static boolean[] connectivityRow(int x, int y, int size)
    {
        boolean[] squares = new boolean[size * size];
        for (int offsetX = -1; offsetX <= 1; offsetX++)
        {
            for (int offsetY = -1; offsetY <= 1; offsetY++)
            {
                final int calX = x + offsetX;
                final int calY = y + offsetY;
                if ((calX >= 0) && (calX < size) && (calY >= 0) && (calY < size))
                    squares[calY * size + calX] = true;
            }
        }

        squares[y * size + x] = false;//the current x, y is false

        return squares;
    }

    /**
     Returns the matrix of connectivity between two points.  Point i can go to point j iff matrix[i][j] is true
     Square (x, y) is equivalent to point (size * y + x).  For example, square (1,1) is point 5 in a puzzle of size 4

     @param size the size of the puzzle
     @return the connectivity matrix
     */
    public static boolean[][] connectivityMatrix(int size)
    {
        boolean[][] matrix = new boolean[size * size][];
        for (int x = 0; x < size; x++)
        {
            for (int y = 0; y < size; y++)
            {
                matrix[y * size + x] = connectivityRow(x, y, size);
            }
        }
        return matrix;
    }
}

What is an Intent in Android?

From the paper Deep Dive into Android IPC/Binder Framework atAndroid Builders Summit 2013 link

The intent is understood in some small but effective lines

  1. Android supports a simple form of IPC(inter process communication) via intents
  2. Intent messaging is a framework for asynchronous communication among Android components (activity, service, content providers, broadcast receiver )
  3. Those components may run in the same or across different apps (i.e. processes)
  4. Enables both point-to-point as well as publish subscribe messaging domains
  5. The intent itself represents a message containing the description of the operation to be performed as well as data to be passed to the recipient(s).

From this thread a simple answer of android architect Dianne Hackborn states it as a data container which it actually is.

From android architecture point of view :

Intent is a data container that is used for inter process communication. It is built on top of the Binder from android architecture point of view.

Open and write data to text file using Bash?

#!/bin/sh

FILE="/path/to/file"

/bin/cat <<EOM >$FILE
text1
text2 # This comment will be inside of the file.
The keyword EOM can be any text, but it must start the line and be alone.
 EOM # This will be also inside of the file, see the space in front of EOM.
EOM # No comments and spaces around here, or it will not work.
text4 
EOM

How to check a not-defined variable in JavaScript

In JavaScript, null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, there is not a direct equivalent. If you really want to check for specifically for null, do:

if (yourvar === null) // Does not execute if yourvar is `undefined`

If you want to check if a variable exists, that can only be done with try/catch, since typeof will treat an undeclared variable and a variable declared with the value of undefined as equivalent.

But, to check if a variable is declared and is not undefined:

if (yourvar !== undefined) // Any scope

Previously, it was necessary to use the typeof operator to check for undefined safely, because it was possible to reassign undefined just like a variable. The old way looked like this:

if (typeof yourvar !== 'undefined') // Any scope

The issue of undefined being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use === and !== to test for undefined without using typeof as undefined has been read-only for some time.

If you want to know if a member exists independent but don't care what its value is:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable is truthy:

if (yourvar)

Source

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

How to change the color of an svg element?

If you want to do this to an inline svg that is, for example, a background image in your css:

_x000D_
_x000D_
background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='rgba(31,159,215,1)' viewBox='...'/%3E%3C/svg%3E");
_x000D_
_x000D_
_x000D_

of course, replace the ... with your inline image code

Java Minimum and Maximum values in Array

Imho one of the simplest Solutions is: -

//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);

//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

Best ways to teach a beginner to program?

I would recommend also watching some screencasts - they are generally created in context of a specific technology not a language, though if there's Python code displayed, that'll do :). The point is - they're created by some good programmers and watching how good programmers program is a good thing. You and your brother could do some peer programming as well, that might be an even better idea. Just don't forget to explain WHY you do something this way and not that way. I think the best way to learn programming is from good examples and try not to even see the bad ones.

How to use jQuery in AngularJS

The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.

angular.module('app')
.directive('my-slider', 
    ['$timeout', function($timeout) {
        return {
            restrict:'E',
            scope: true,
            template: '<div id="{{ id }}"></div>',
            link: function($scope) {
                $scope.id = String(Math.random()).substr(2, 8);

                $timeout(function() {
                    angular.element('#'+$scope.id).slider();                    
                });
            }
        };
    }]
);

Which Ruby version am I really running?

On your terminal, try running:

which -a ruby

This will output all the installed Ruby versions (via RVM, or otherwise) on your system in your PATH. If 1.8.7 is your system Ruby version, you can uninstall the system Ruby using:

sudo apt-get purge ruby

Once you have made sure you have Ruby installed via RVM alone, in your login shell you can type:

rvm --default use 2.0.0

You don't need to do this if you have only one Ruby version installed.

If you still face issues with any system Ruby files, try running:

dpkg-query -l '*ruby*'

This will output a bunch of Ruby-related files and packages which are, or were, installed on your system at the system level. Check the status of each to find if any of them is native and is causing issues.

how to convert string into time format and add two hours

Try this one, I test it, working fine

Date date = null;
String str = "2012/07/25 12:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
date = formatter.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
System.out.println(calendar.getTime());  // Output : Wed Jul 25 14:00:00 IST 2012

If you want to convert in your input type than add this code also

formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str=formatter.format(calendar.getTime());
System.out.println(str);  // Output : 2012-07-25 14:00:00

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

How to prettyprint a JSON file?

The json module already implements some basic pretty printing with the indent parameter that specifies how many spaces to indent by:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

To parse a file, use json.load():

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

PHP Date Time Current Time Add Minutes

echo $date = date('H:i:s', strtotime('13:00:00 + 30 minutes') );

13:00:00 - any inputted time

30 minutes - any interval you wish (20 hours, 10 minutes, 1 seconds etc...)

How to convert all tables from MyISAM into InnoDB?

for mysqli connect;

<?php

$host       = "host";
$user       = "user";
$pass       = "pss";
$database   = "db_name";


$connect = new mysqli($host, $user, $pass, $database);  

// Actual code starts here Dont forget to change db_name !!
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'db_name' 
    AND ENGINE = 'MyISAM'";

$rs = $connect->query($sql);

while($row = $rs->fetch_array())
{
    $tbl = $row[0];
    $sql = "ALTER TABLE `$tbl` ENGINE=INNODB";
    $connect->query($sql);
} ?>

Concatenating multiple text files into a single file in Bash

type [source folder]\*.[File extension] > [destination folder]\[file name].[File extension]

For Example:

type C:\*.txt > C:\1\all.txt

That will Take all the txt files in the C:\ Folder and save it in C:\1 Folder by the name of all.txt

Or

type [source folder]\* > [destination folder]\[file name].[File extension]

For Example:

type C:\* > C:\1\all.txt

That will take all the files that are present in the folder and put there Content in C:\1\all.txt

Error handling in Bash

Another consideration is the exit code to return. Just "1" is pretty standard, although there are a handful of reserved exit codes that bash itself uses, and that same page argues that user-defined codes should be in the range 64-113 to conform to C/C++ standards.

You might also consider the bit vector approach that mount uses for its exit codes:

 0  success
 1  incorrect invocation or permissions
 2  system error (out of memory, cannot fork, no more loop devices)
 4  internal mount bug or missing nfs support in mount
 8  user interrupt
16  problems writing or locking /etc/mtab
32  mount failure
64  some mount succeeded

OR-ing the codes together allows your script to signal multiple simultaneous errors.

Is JavaScript's "new" keyword considered harmful?

I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

Running a command in a new Mac OS X Terminal window

In case anyone cares, here's an equivalent for iTerm:

#!/bin/sh
osascript <<END
tell application "iTerm"
 tell the first terminal
  launch session "Default Session"
  tell the last session
   write text "cd \"`pwd`\";$1;exit"
  end tell
 end tell
end tell
END

Setting the MySQL root user password on OS X

Once you've installed MySQL, you'll need to establish the "root" password. If you don't establish a root password, then, well, there is no root password, and you don't need a password to log in.

So, that being said, you need to establish a root password.

Using terminal enter the following:

Installation: Set root user password:

/usr/local/mysql/bin/mysqladmin -u root password NEW_PASSWORD_HERE

If you've made a mistake, or need to change the root password use the following:

Change root password:

cd /usr/local/mysql/bin/
./mysql -u root -p
> Enter password: [type old password invisibly]

use mysql;
update user set password=PASSWORD("NEW_PASSWORD_HERE") where User='root';
flush privileges;
quit

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

my problem with getting this error was resolved by using the full URL "qatest.ourCompany.com/webService" instead of just "qatest/webService". Reason was that our security certificate had a wildcard i.e. "*.ourCompany.com". Once I put in the full address the exception went away. Hope this helps.

Google Chrome form autofill and its yellow background

Solution here:

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static variables are used when only one copy of it is required. Let me explain this with an example:

class circle
{
    public float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * this._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now here we have created 2 instances for our class circle , i.e 2 sets of copies of _PI along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI will be created occupying memory. So in such cases it is better to make such variables like _PI static and operate on them.

class circle
{
    static float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * Circle._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now no matter how many instances are made for the class circle , only one copy exists of variable _PI saving our memory.

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

Triggering a checkbox value changed event in DataGridView

I found a combination of the first two answers gave me what I needed. I used the CurrentCellDirtyStateChanged event and inspected the EditedFormattedValue.

private void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
   DataGridView dgv = (DataGridView)sender;
   DataGridViewCell cell = dgv.CurrentCell;
   if (cell.RowIndex >= 0 && cell.ColumnIndex == 3) // My checkbox column
     {
        // If checkbox checked, copy value from col 1 to col 2
        if (dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue != null && dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue.Equals(true))
        {
           dgv.Rows[cell.RowIndex].Cells[1].Value = dgv.Rows[cell.RowIndex].Cells[2].Value;
        }
     }
}

using lodash .groupBy. how to add your own keys for grouped output?

Here is an updated version using lodash 4 and ES6

const result = _.chain(data)
    .groupBy("color")
    .toPairs()
    .map(pair => _.zipObject(['color', 'users'], pair))
    .value();

How do I get a Date without time in Java?

This is a simple way of doing it:

Calendar cal = Calendar.getInstance();
SimpleDateFormat dateOnly = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(dateOnly.format(cal.getTime()));

Convert and format a Date in JSP

The example above showing the import with ...sun.com/jsp/jstl/format is incorrect (meaning it didn't work for me).

Instead try the below -this import statement is valid

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%@ taglib uri="http://java.sun.com/jstl/core-rt" prefix="c-rt" %><%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<html>
  <head>
    <title>Format Date</title>
  </head>

  <body>
    <c-rt:set var="now" value="<%=new java.util.Date()%>" />

    <table border="1" cellpadding="0" cellspacing="0"
    style="border-collapse: collapse" bordercolor="#111111"
    width="63%" id="AutoNumber2">
      <tr>
        <td width="100%" colspan="2" bgcolor="#0000FF">
          <p align="center">
            <b>
              <font color="#FFFFFF" size="4">Formatting: 
              <fmt:formatDate value="${now}" type="both"
              timeStyle="long" dateStyle="long" />
              </font>
            </b>
          </p>
        </td>
      </tr>

how to get the current working directory's absolute path from irb

This will give you the working directory of the current file.

File.dirname(__FILE__)

Example:

current_file: "/Users/nemrow/SITM/folder1/folder2/amazon.rb"

result: "/Users/nemrow/SITM/folder1/folder2"

if-else statement inside jsx: ReactJS

For this we can use ternary operator or if there is only one condition then "&&" operator .Like this:-

//This is for if else

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') ?
           <Text>data</Text>
        : null}
    </View>
)

}

//This is only for if or only for one condition

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') &&
           <Text>data</Text>
        }
    </View>
)

}

How to pass form input value to php function

you must have read about function call . here i give you example of it.

<?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

Why does SSL handshake give 'Could not generate DH keypair' exception?

The "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" answer did not work for me but The BouncyCastle's JCE provider suggestion did.

Here are the steps I took using Java 1.6.0_65-b14-462 on Mac OSC 10.7.5

1) Download these jars:

2) move these jars to $JAVA_HOME/lib/ext

3) edit $JAVA_HOME/lib/security/java.security as follows: security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

restart app using JRE and give it a try

How do I find the stack trace in Visual Studio?

While debugging, Go to Debug -> Windows -> Call Stack

Passing parameter to controller action from a Html.ActionLink

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })

add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

MATLAB, Filling in the area between two sets of data, lines in one figure

Personally, I find it both elegant and convenient to wrap the fill function. To fill between two equally sized row vectors Y1 and Y2 that share the support X (and color C):

fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)],  [Y1 fliplr(Y2)], C );

Unable to merge dex

In my case the problem was I implemented the same library twice in my build.gradle file. Removing the duplicate entry worked for me. And did not even needed to clean, rebuild the project.

Check whether an array is empty

<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

javascript: get a function's variable's value within another function

nameContent only exists within the first() function, as you defined it within the first() function.

To make its scope broader, define it outside of the functions:

var nameContent;

function first(){
    nameContent=document.getElementById('full_name').value;
}

function second() {
    first();
    y=nameContent; alert(y);
}
second();

A slightly better approach would be to return the value, as global variables get messy very quickly:

function getFullName() {
  return document.getElementById('full_name').value;
}

function doStuff() {
  var name = getFullName();

  alert(name);
}

doStuff();

Correct way to load a Nib for a UIView subclass

Well you could either initialize the xib using a view controller and use viewController.view. or do it the way you did it. Only making a UIView subclass as the controller for UIView is a bad idea.

If you don't have any outlets from your custom view then you can directly use a UIViewController class to initialize it.

Update: In your case:

UIViewController *genericViewCon = [[UIViewController alloc] initWithNibName:@"CustomView"];
//Assuming you have a reference for the activity indicator in your custom view class
CustomView *myView = (CustomView *)genericViewCon.view;
[parentView addSubview:myView];
//And when necessary
[myView.activityIndicator startAnimating]; //or stop

Otherwise you have to make a custom UIViewController(to make it as the file's owner so that the outlets are properly wired up).

YourCustomController *yCustCon = [[YourCustomController alloc] initWithNibName:@"YourXibName"].

Wherever you want to add the view you can use.

[parentView addSubview:yCustCon.view];

However passing the another view controller(already being used for another view) as the owner while loading the xib is not a good idea as the view property of the controller will be changed and when you want to access the original view, you won't have a reference to it.

EDIT: You will face this problem if you have setup your new xib with file's owner as the same main UIViewController class and tied the view property to the new xib view.

i.e;

  • YourMainViewController -- manages -- mainView
  • CustomView -- needs to load from xib as and when required.

The below code will cause confusion later on, if you write it inside view did load of YourMainViewController. That is because self.view from this point on will refer to your customview

-(void)viewDidLoad:(){
  UIView *childView= [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:self options:nil] objectAtIndex:0];
}

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

Mysql 1050 Error "Table already exists" when in fact, it does not

In my case the problem was that there was a view with the same name as my table, so I had to drop the view to allow the import to continue.

drop view `my-view-that-has-same-name-as-table`;

An automated solution that worked for me is to replace the normal drop table with this sed during the dump to also drop any views that might exist:

mysqldump my-db \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
| mysql my-other-db

Or if you would rather print to a file for backup

mysqldump my-db \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
> my-db.dump.sql

Or if you received the dumped file and you are importing it to your db

cat my-db.dump.sql \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
| mysql my-other-db

You get the idea

Note: it is important that you add the ^ at the beginning of the replacement regex, because there are other types of DROP TABLE IF EXISTS commands in dumps that you don't want to touch.

You go from having something like this:

--
-- Table structure for table `my_table`
--

DROP TABLE IF EXISTS `my_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `my_table` (
...

To having something like this:

--
-- Table structure for table `my_table`
--

DROP TABLE IF EXISTS `my_table`; DROP VIEW IF EXISTS `my_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `my_table` (
...

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

jquery getting post action url

Clean and Simple:

$('#signup').submit(function(event) {

      alert(this.action);
});

javascript password generator

I got insprired by the answers above (especially by the hint from @e.vyushin regarding the security of Math.random() ) and I came up with the following solution that uses the crypto.getRandomValues() to generate a rondom array of UInt32 values with the length of the password length.

Then, it loops through the array and devides each element by 2^32 (max value of a UInt32) to calculate the ratio between the actual value and the max. possible value. This ratio is then mapped to the charset string to determine which character of the string is picked.

console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
    if (charset==="letters+numbers") {
        var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    } else if (charset==="letters+numbers+signs") {
        var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_@";
    }
    var arr = new Uint32Array(len);
    var maxRange = Math.pow(2,32);
    var passwd = '';
    window.crypto.getRandomValues(arr);
    

    for (let i=0;i<len;i++) {
        var c = Math.floor(arr[i] / maxRange  * chars.length + 1);
        passwd += chars.charAt(c);
    }
    return passwd;
}

Thus, the code is able to use the advantage of the crypto-Class (improved security for the random value generation) and is adaptable to use any kind of charset the user wished. A next step would be to use regular expression strings to define the charset to be used.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

While other answers nicely described all differences between C++ casts, I would like to add a short note why you should not use C-style casts (Type) var and Type(var).

For C++ beginners C-style casts look like being the superset operation over C++ casts (static_cast<>(), dynamic_cast<>(), const_cast<>(), reinterpret_cast<>()) and someone could prefer them over the C++ casts. In fact C-style cast is the superset and shorter to write.

The main problem of C-style casts is that they hide developer real intention of the cast. The C-style casts can do virtually all types of casting from normally safe casts done by static_cast<>() and dynamic_cast<>() to potentially dangerous casts like const_cast<>(), where const modifier can be removed so the const variables can be modified and reinterpret_cast<>() that can even reinterpret integer values to pointers.

Here is the sample.

int a=rand(); // Random number.

int* pa1=reinterpret_cast<int*>(a); // OK. Here developer clearly expressed he wanted to do this potentially dangerous operation.

int* pa2=static_cast<int*>(a); // Compiler error.
int* pa3=dynamic_cast<int*>(a); // Compiler error.

int* pa4=(int*) a; // OK. C-style cast can do such cast. The question is if it was intentional or developer just did some typo.

*pa4=5; // Program crashes.

The main reason why C++ casts were added to the language was to allow a developer to clarify his intentions - why he is going to do that cast. By using C-style casts which are perfectly valid in C++ you are making your code less readable and more error prone especially for other developers who didn't create your code. So to make your code more readable and explicit you should always prefer C++ casts over C-style casts.

Here is a short quote from Bjarne Stroustrup's (the author of C++) book The C++ Programming Language 4th edition - page 302.

This C-style cast is far more dangerous than the named conversion operators because the notation is harder to spot in a large program and the kind of conversion intended by the programmer is not explicit.

Subtracting 2 lists in Python

I'd have to recommend NumPy as well

Not only is it faster for doing vector math, but it also has a ton of convenience functions.

If you want something even faster for 1d vectors, try vop

It's similar to MatLab, but free and stuff. Here's an example of what you'd do

from numpy import matrix
a = matrix((2,2,2))
b = matrix((1,1,1))
ret = a - b
print ret
>> [[1 1 1]]

Boom.

django change default runserver port

If you wish to change the default configurations then follow this steps:

  1. Open terminal type command

     $ /usr/local/lib/python<2/3>.x/dist-packages/django/core/management/commands
    
  2. Now open runserver.py file in nano editor as superuser

     $ sudo nano runserver.py
    
  3. find the 'default_port' variable then you will see the default port no is '8000'. Now you can change it to whatever you want.

  4. Now exit and save the file using "CTRL + X and Y to save the file"

Note: Replace <2/3>.x with your usable version of python

How can I remove the gloss on a select element in Safari on Mac?

As mentioned several times here

-webkit-appearance:none;

also removes the arrows, which is not what you want in most cases.

An easy workaround I found is to simply use select2 instead of select. You can re-style a select2 element as well, and most importantly, select2 looks the same on Windows, Android, iOS and Mac.

Difference between Math.Floor() and Math.Truncate()

They are functionally equivalent with positive numbers. The difference is in how they handle negative numbers.

For example:

Math.Floor(2.5) = 2
Math.Truncate(2.5) = 2

Math.Floor(-2.5) = -3
Math.Truncate(-2.5) = -2

MSDN links: - Math.Floor Method - Math.Truncate Method

P.S. Beware of Math.Round it may not be what you expect.

To get the "standard" rounding result use:

float myFloat = 4.5;
Console.WriteLine( Math.Round(myFloat) ); // writes 4
Console.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5
Console.WriteLine( myFloat.ToString("F0") ); // writes 5

Byte Array and Int conversion in Java

/*sorry this is the correct */

     public byte[] IntArrayToByteArray(int[] iarray , int sizeofintarray)
     {
       final ByteBuffer bb ;
       bb = ByteBuffer.allocate( sizeofintarray * 4);
       for(int k = 0; k < sizeofintarray ; k++)
       bb.putInt(k * 4, iar[k]);
       return bb.array();
     }

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I had faced the similar error when supporting one application. It was about the generated classes for a SOAP Webservice.

The issue was caused due to the missing classes. When javax.xml.bind.Marshaller was trying to marshal the jaxb object it was not finding all dependent classes which were generated by using wsdl and xsd. after adding the jar with all the classes at the class path the issue was resolved.

Angular js init ng-model from default values

IMHO the best solution is the @Kevin Stone directive, but I had to upgrade it to work in every conditions (f.e. select, textarea), and this one is working for sure:

    angular.module('app').directive('ngInitial', function($parse) {
        return {
            restrict: "A",
            compile: function($element, $attrs) {
                var initialValue = $attrs.value || $element.val();
                return {
                    pre: function($scope, $element, $attrs) {
                        $parse($attrs.ngModel).assign($scope, initialValue);
                    }
                }
            }
        }
    });

How to delete an element from an array in C#

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
    numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}

Getting hold of the outer class object from the inner class object

Here's the example:

// Test
public void foo() {
    C c = new C();
    A s;
    s = ((A.B)c).get();
    System.out.println(s.getR());
}

// classes
class C {}

class A {
   public class B extends C{
     A get() {return A.this;}
   }
   public String getR() {
     return "This is string";
   }
}

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Way to go from recursion to iteration

Search google for "Continuation passing style." There is a general procedure for converting to a tail recursive style; there is also a general procedure for turning tail recursive functions into loops.

Ubuntu, how do you remove all Python 3 but not 2

First of all, don't try the following command as suggested by Germain above.

   `sudo apt-get remove 'python3.*'`

In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.

https://askubuntu.com/questions/810854/i-deleted-package-python3-on-ubuntu-and-i-have-lost-dashboard-terminal-and-un

If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.

Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.

https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/

Why doesn't the Scanner class have a nextChar method?

I would imagine that it has to do with encoding. A char is 16 bytes and some encodings will use one byte for a character whereas another will use two or even more. When Java was originally designed, they assumed that any Unicode character would fit in 2 bytes, whereas now a Unicode character can require up to 4 bytes (UTF-32). There is no way for Scanner to represent a UTF-32 codepoint in a single char.

You can specify an encoding to Scanner when you construct an instance, and if not provided, it will use the platform character-set. But this still doesn't handle the issue with 3 or 4 byte Unicode characters, since they cannot be represented as a single char primitive (since char is only 16 bytes). So you would end up getting inconsistent results.

Does Python have a ternary conditional operator?

For versions prior to 2.5, there's the trick:

[expression] and [on_true] or [on_false]

It can give wrong results when on_true has a false boolean value.1
Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.

1. Is there an equivalent of C’s ”?:” ternary operator?

Objective-C and Swift URL encoding

Swift iOS:

Just For Information : I have used this:

extension String {

    func urlEncode() -> CFString {
        return CFURLCreateStringByAddingPercentEscapes(
            nil,
            self,
            nil,
            "!*'();:@&=+$,/?%#[]",
            CFStringBuiltInEncodings.UTF8.rawValue
        )
    }

}// end extension String

Date Difference in php on days?

Below code will give the output for number of days, by taking out the difference between two dates..

$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);

Send Email Intent

There is an easy solution also with ACTION_VIEW:

  Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data = Uri.parse("mailto:[email protected]?subject=Feedback");
        intent.setData(data);
        startActivity(intent);

2D Euclidean vector rotations

Sounds easier to do with the standard classes:

std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;

Vector rotation is a subset of complex multiplication. To rotate over an angle alpha, you multiply by std::complex<double> { cos(alpha), sin(alpha) }

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

How do I split a string into an array of characters?

It's as simple as:

s.split("");

The delimiter is an empty string, hence it will break up between each single character.

Android Transparent TextView?

Use this:

android:background="@android:color/transparent"

When do I use path params vs. query params in a RESTful API?

The fundamental way to think about this subject is as follows:

A URI is a resource identifier that uniquely identifies a specific instance of a resource TYPE. Like everything else in life, every object (which is an instance of some type), have set of attributes that are either time-invariant or temporal.

In the example above, a car is a very tangible object that has attributes like make, model and VIN - that never changes, and color, suspension etc. that may change over time. So if we encode the URI with attributes that may change over time (temporal), we may end up with multiple URIs for the same object:

GET /cars/honda/civic/coupe/{vin}/{color=red}

And years later, if the color of this very same car is changed to black:

GET /cars/honda/civic/coupe/{vin}/{color=black}

Note that the car instance itself (the object) has not changed - it's just the color that changed. Having multiple URIs pointing to the same object instance will force you to create multiple URI handlers - this is not an efficient design, and is of course not intuitive.

Therefore, the URI should only consist of parts that will never change and will continue to uniquely identify that resource throughout its lifetime. Everything that may change should be reserved for query parameters, as such:

GET /cars/honda/civic/coupe/{vin}?color={black}

Bottom line - think polymorphism.

jQuery - how can I find the element with a certain id?

As all html ids are unique in a valid html document why not search for the ID directly? If you're concerned if they type in an id that isn't a table then you can inspect the tag type that way?

Just an idea!

S

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

if you are using GIT for control versions and in some of yours commit you added db.sqlite3, GIT will keep some references of the database, so when you execute 'python manage.py migrate', this reference will be reflected on the new database. I recommend to execute the following command:

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch 'db.sqlite3' HEAD

it worked for me :)

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

On Windows 7 64-bit, I added the registry entry using the following script:

@echo off
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Description" /t REG_SZ /d "Oracle Next Generation Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "GeckoVersion" /t REG_SZ /d "1.9"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Path" /t REG_SZ /d "C:\Oracle\jdev11123\jdk160_24\jre\bin\new_plugin\npjp2.dll"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "ProductName" /t REG_SZ /d "Oracle Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Vendor" /t REG_SZ /d "Oracle Corp."
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Version" /t REG_SZ /d "10.3.1"

Note that you will have to change the Path.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

Cast to generic type in C#

To convert any type object to a generic type T, the trick is to first assign to an object of any higher type then cast that to the generic type.

object temp = otherTypeObject;
T result = (T)temp;

XAMPP Apache won't start

Open services.msc directly from command prompt and disabled SQL Server reporting services

& SQL Server analysis services.

How to inject window into a service?

In Angular RC4 the following works which is a combination of some of the above answers, in your root app.ts add it the providers:

@Component({
    templateUrl: 'build/app.html',
    providers: [
        anotherProvider,
        { provide: Window, useValue: window }
    ]
})

Then in your service etc inject it into the constructor

constructor(
      @Inject(Window) private _window: Window,
)

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

i had the same case on linux ubuntu and just fixed it, it seems that OS was confused between the /root/.ssh/ and home/user/.ssh/ dir, what i did was:

  1. removed all keys from root and home/user .shh directory.
  2. generated a new key make sure to pay attention to the path of creation (/home/you/.ssh/id_rsa) or (/root/.ssh/id_rsa)
  3. check heroku keys heroku keys
  4. if keys in there clear heroku keys:clear
  5. heroku keys:add now in here if heroku couldn't find a key and asked to generate one right no, and this mean you have the same issue as mine, do the add command like this heroku keys:add /root/.ssh/id_rsa.pub the path that you'll add will be the one that you got in step 2.
  6. try git push heroku master now

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

How to perform update operations on columns of type JSONB in Postgres 9.4

If you're able to upgrade to Postgresql 9.5, the jsonb_set command is available, as others have mentioned.

In each of the following SQL statements, I've omitted the where clause for brevity; obviously, you'd want to add that back.

Update name:

UPDATE test SET data = jsonb_set(data, '{name}', '"my-other-name"');

Replace the tags (as oppose to adding or removing tags):

UPDATE test SET data = jsonb_set(data, '{tags}', '["tag3", "tag4"]');

Replacing the second tag (0-indexed):

UPDATE test SET data = jsonb_set(data, '{tags,1}', '"tag5"');

Append a tag (this will work as long as there are fewer than 999 tags; changing argument 999 to 1000 or above generates an error. This no longer appears to be the case in Postgres 9.5.3; a much larger index can be used):

UPDATE test SET data = jsonb_set(data, '{tags,999999999}', '"tag6"', true);

Remove the last tag:

UPDATE test SET data = data #- '{tags,-1}'

Complex update (delete the last tag, insert a new tag, and change the name):

UPDATE test SET data = jsonb_set(
    jsonb_set(data #- '{tags,-1}', '{tags,999999999}', '"tag3"', true), 
    '{name}', '"my-other-name"');

It's important to note that in each of these examples, you're not actually updating a single field of the JSON data. Instead, you're creating a temporary, modified version of the data, and assigning that modified version back to the column. In practice, the result should be the same, but keeping this in mind should make complex updates, like the last example, more understandable.

In the complex example, there are three transformations and three temporary versions: First, the last tag is removed. Then, that version is transformed by adding a new tag. Next, the second version is transformed by changing the name field. The value in the data column is replaced with the final version.

batch file - counting number of files in folder and storing in a variable

@echo off
setlocal enableextensions
set count=0
for %%x in (*.txt) do set /a count+=1
echo %count%
endlocal
pause

This is the best.... your variable is: %count%

NOTE: you can change (*.txt) to any other file extension to count other files.....

Filtering DataGridView without changing datasource

You could create a DataView object from your datasource. This would allow you to filter and sort your data without directly modifying the datasource.

Also, remember to call dataGridView1.DataBind(); after you set the data source.

What are all possible pos tags of NLTK?

The reference is available at the official site

Copy and pasting from there:

  • CC | Coordinating conjunction |
  • CD | Cardinal number |
  • DT | Determiner |
  • EX | Existential there |
  • FW | Foreign word |
  • IN | Preposition or subordinating conjunction |
  • JJ | Adjective |
  • JJR | Adjective, comparative |
  • JJS | Adjective, superlative |
  • LS | List item marker |
  • MD | Modal |
  • NN | Noun, singular or mass |
  • NNS | Noun, plural |
  • NNP | Proper noun, singular |
  • NNPS | Proper noun, plural |
  • PDT | Predeterminer |
  • POS | Possessive ending |
  • PRP | Personal pronoun |
  • PRP$ | Possessive pronoun |
  • RB | Adverb |
  • RBR | Adverb, comparative |
  • RBS | Adverb, superlative |
  • RP | Particle |
  • SYM | Symbol |
  • TO | to |
  • UH | Interjection |
  • VB | Verb, base form |
  • VBD | Verb, past tense |
  • VBG | Verb, gerund or present participle |
  • VBN | Verb, past participle |
  • VBP | Verb, non-3rd person singular present |
  • VBZ | Verb, 3rd person singular present |
  • WDT | Wh-determiner |
  • WP | Wh-pronoun |
  • WP$ | Possessive wh-pronoun |
  • WRB | Wh-adverb |

How do you stop tracking a remote branch in Git?

As mentioned in Yoshua Wuyts' answer, using git branch:

git branch --unset-upstream

Other options:

You don't have to delete your local branch.

Simply delete the local branch that is tracking the remote branch:

git branch -d -r origin/<remote branch name>

-r, --remotes tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!

See "Having a hard time understanding git-fetch"

there's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo

As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:

git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge

Remove the upstream information for <branchname>.
If no branch is specified it defaults to the current branch.

(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn))

That will make any push/pull completely unaware of origin/<remote branch name>.

Copy entire directory contents to another directory?

This is my piece of Groovy code for that. Tested.

private static void copyLargeDir(File dirFrom, File dirTo){
    // creation the target dir
    if (!dirTo.exists()){
        dirTo.mkdir();
    }
    // copying the daughter files
    dirFrom.eachFile(FILES){File source ->
        File target = new File(dirTo,source.getName());
        target.bytes = source.bytes;
    }
    // copying the daughter dirs - recursion
    dirFrom.eachFile(DIRECTORIES){File source ->
        File target = new File(dirTo,source.getName());
        copyLargeDir(source, target)
    }
}

How to clear memory to prevent "out of memory error" in excel vba?

I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.

Contain an image within a div?

Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.

#container img {
    max-height: 250px;
    max-width: 250px;
} 

See my example with an image that isn't a square, it doesn't stretch

Column count doesn't match value count at row 1

  1. you missed the comma between two values or column name
  2. you put extra values or an extra column name

Select datatype of the field in postgres

You can get data types from the information_schema (8.4 docs referenced here, but this is not a new feature):

=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
    column_name     | data_type 
--------------------+-----------
 id                 | integer
 default_printer_id | integer
 master_host_enable | boolean
(3 rows)

Adding image to JFrame

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));

Making a POST call instead of GET using urllib2

url="https://myserver/post_service"
data["name"] = "joe"
data["age"] = "20"
data_encoded = urllib2.urlencode(data)
print urllib2.urlopen(url + "?" + data_encoded).read()

May be this can help

Check for database connection, otherwise display message

very basic:

<?php 
$username = 'user';
$password = 'password';
$server = 'localhost'; 
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>

result:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

What is a singleton in C#?

Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.

Swift Set to Array

You can create an array with all elements from a given Swift Set simply with

let array = Array(someSet)

This works because Set conforms to the SequenceType protocol and an Array can be initialized with a sequence. Example:

let mySet = Set(["a", "b", "a"])  // Set<String>
let myArray = Array(mySet)        // Array<String>
print(myArray) // [b, a]

How to set multiple commands in one yaml file with Kubernetes?

If you're willing to use a Volume and a ConfigMap, you can mount ConfigMap data as a script, and then run that script:

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  entrypoint.sh: |-
    #!/bin/bash
    echo "Do this"

    echo "Do that"
---
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: "ubuntu:14.04"
    command:
    - /bin/entrypoint.sh
    volumeMounts:
    - name: configmap-volume
      mountPath: /bin/entrypoint.sh
      readOnly: true
      subPath: entrypoint.sh
  volumes:
  - name: configmap-volume
    configMap:
      defaultMode: 0700
      name: my-configmap

This cleans up your pod spec a little and allows for more complex scripting.

$ kubectl logs my-pod
Do this
Do that

ImportError: No module named sqlalchemy

So here is an idea!

Since it seemed to work somewhere else.

install python-virtualenv and optionally you can install virtualenv-wrapper (which is pretty cool to create projects and so on)

In each env, you might have different versions of eggs. In other word, you could have sqlalchemy 1 and sqlaclhemy 1.5 in two different envs and they won't conflict with each others. It seems that you have a problem with your currently installed eggs.

So here we go:

virtualenv --no-site-packages foo
source foo/bin/activate

The parameter --no-site-packages will create a virtualenv and not use the packages already installed on your computer. It's pretty much like a bare python install.

source foo/bin/activate loads the virtualenv.

It's not that really userfriendly. And that's why http://www.doughellmann.com/projects/virtualenvwrapper/ exists.

That said, you should see somthing like thant in your terminal "(foo)user@domain$:" once your virtualenv is activated. It means that you can go on!

Then you have to do.

python setup.py develop of your project. It should download and install dependencies of your project in the virtualenv located in foo. If you need to install anything else, please use pip or easy_install without using sudo. When using virtualenv, you almost never need to use sudo. Sudo will install package in your global python install while it's not required and not really desirable.

If something happens in your virtualenv, you can always delete it and create a new one. This is no big deal. No need to mess with anything. Doesn't work? start over, do pip install -U if needed, define the versions if needed and so on.

Last but not least, in the other answers, it seems that the import changed. If the new versions for flask-sqlalchemy is located somewhere else, you should update your import or install the version you used to use.

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

Easiest way to change font and font size

Use this one to change only font size not the name of the font

label1.Font = new System.Drawing.Font(label1.Font.Name, 24F);

GitHub: How to make a fork of public repository private?

GitHub now has an import option that lets you choose whatever you want your new imported repository public or private

Github Repository import

Kill a postgresql session/connection

I use the following rake task to override the Rails drop_database method.

lib/database.rake

require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLAdapter < AbstractAdapter
      def drop_database(name)
        raise "Nah, I won't drop the production database" if Rails.env.production?
        execute <<-SQL
          UPDATE pg_catalog.pg_database
          SET datallowconn=false WHERE datname='#{name}'
        SQL

        execute <<-SQL
          SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
          WHERE pg_stat_activity.datname = '#{name}';
        SQL
        execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
      end
    end
  end
end

Edit: This is for Postgresql 9.2+

How to use sha256 in php5.3.0

Could this be a typo? (two Ps in ppasscode, intended?)

$_POST['ppasscode'];

I would make sure and do:

print_r($_POST);

and make sure the data is accurate there, and then echo out what it should look like:

echo hash('sha256', $_POST['ppasscode']);

Compare this output to what you have in the database (manually). By doing this you're exploring your possible points of failure:

  1. Getting password from form
  2. hashing the password
  3. stored password
  4. comparison of the two.

How can I reorder my divs using only CSS?

CSS really shouldn't be used to restructure the HTML backend. However, it is possible if you know the height of both elements involved and are feeling hackish. Also, text selection will be messed up when going between the divs, but that's because the HTML and CSS order are opposite.

#firstDiv { position: relative; top: YYYpx; height: XXXpx; }
#secondDiv { position: relative; top: -XXXpx; height: YYYpx; }

Where XXX and YYY are the heights of firstDiv and secondDiv respectively. This will work with trailing elements, unlike the top answer.

Detect if a NumPy array contains at least one non-numeric value?

If infinity is a possible value, I would use numpy.isfinite

numpy.isfinite(myarray).all()

If the above evaluates to True, then myarray contains no, numpy.nan, numpy.inf or -numpy.inf values.

numpy.nan will be OK with numpy.inf values, for example:

In [11]: import numpy as np

In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])

In [13]: np.isnan(b)
Out[13]: 
array([[False, False],
       [ True, False]], dtype=bool)

In [14]: np.isfinite(b)
Out[14]: 
array([[ True, False],
       [False, False]], dtype=bool)

Connection refused to MongoDB errno 111

For me, changing the ownership of /var/lib/mongodb and /tmp/mongodb-27017.sock to mongodb was the way to go.

Just do:

sudo chown -R mongodb:mongodb /var/lib/mongodb

and then:

sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

and then start or restart the mongodb server:

sudo systemctl start mongod

or

sudo systemctl restart mongod

and check the status

sudo systemctl status mongod

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Oh my God. not need to do anything special. only in your post section do as follows:

    $.post(yourURL,{ '': results})(function(e){ ...}

In server use this:

   public ActionResult MethodName(List<yourViewModel> model){...}

this link help you to done ...

How to use a jQuery plugin inside Vue

You need to use either the globals loader or expose loader to ensure that webpack includes the jQuery lib in your source code output and so that it doesn't throw errors when your use $ in your components.

// example with expose loader:
npm i --save-dev expose-loader

// somewhere, import (require) this jquery, but pipe it through the expose loader
require('expose?$!expose?jQuery!jquery')

If you prefer, you can import (require) it directly within your webpack config as a point of entry, so I understand, but I don't have an example of this to hand

Alternatively, you can use the globals loader like this: https://www.npmjs.com/package/globals-loader

Getting the HTTP Referrer in ASP.NET

Sometime you must to give all the link like this

System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

(in option when "Current" not founded)

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

I was facing this issue recently, too. Since you can't change the browser's default behavior of showing the popup in case of a 401 (basic or digest authentication), there are two ways to fix this:

  • Change the server response to not return a 401. Return a 200 code instead and handle this in your jQuery client.
  • Change the method that you're using for authorization to a custom value in your header. Browsers will display the popup for Basic and Digest. You have to change this on both the client and the server.

    headers : {
      "Authorization" : "BasicCustom"
    }
    

Please also take a look at this for an example of using jQuery with Basic Auth.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

In your project level Gradle file increase the dependencies classpath version low to high like

dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }

to change like

dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
    }

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.

If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.

Get GPS location from the web browser

If you use the Geolocation API, it would be as simple as using the following code.

navigator.geolocation.getCurrentPosition(function(location) {
  console.log(location.coords.latitude);
  console.log(location.coords.longitude);
  console.log(location.coords.accuracy);
});

You may also be able to use Google's Client Location API.

This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.

Catch Ctrl-C in C

Regarding existing answers, note that signal handling is platform dependent. Win32 for example handles far fewer signals than POSIX operating systems; see here. While SIGINT is declared in signals.h on Win32, see the note in the documentation that explains that it will not do what you might expect.

Compare two objects in Java with possible null values

For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:

android.text.TextUtils.equals(str1, str2);

It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.

Source Code:

/**
 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked  well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check
 * @param b second CharSequence to check
 * @return true if a and b are equal
 */
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b) return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i)) return false;
            }
            return true;
        }
    }
    return false;
}

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

Linux command (like cat) to read a specified quantity of characters

Even though this was answered/accepted years ago, the presently accepted answer is only correct for one-byte-per-character encodings like iso-8859-1, or for the single-byte subsets of variable-byte character sets (like Latin characters within UTF-8). Even using multiple-byte splices instead would still only work for fixed-multibyte encodings like UTF-16. Given that now UTF-8 is well on its way to being a universal standard, and when looking at this list of languages by number of native speakers and this list of top 30 languages by native/secondary usage, it is important to point out a simple variable-byte character-friendly (not byte-based) technique, using cut -c and tr/sed with character-classes.

Compare the following which doubly fails due to two common Latin-centric mistakes/presumptions regarding the bytes vs. characters issue (one is head vs. cut, the other is [a-z][A-Z] vs. [:upper:][:lower:]):

$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$     head -c 1 | \
$     sed -e 's/[A-Z]/[a-z]/g'
[[unreadable binary mess, or nothing if the terminal filtered it]]

to this (note: this worked fine on FreeBSD, but both cut & tr on GNU/Linux still mangled Greek in UTF-8 for me though):

$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$     cut -c 1 | \
$     tr '[:upper:]' '[:lower:]'
p

Another more recent answer had already proposed "cut", but only because of the side issue that it can be used to specify arbitrary offsets, not because of the directly relevant character vs. bytes issue.

If your cut doesn't handle -c with variable-byte encodings correctly, for "the first X characters" (replace X with your number) you could try:

  • sed -E -e '1 s/^(.{X}).*$/\1/' -e q - which is limited to the first line though
  • head -n 1 | grep -E -o '^.{X}' - which is limited to the first line and chains two commands though
  • dd - which has already been suggested in other answers, but is really cumbersome
  • A complicated sed script with sliding window buffer to handle characters spread over multiple lines, but that is probably more cumbersome/fragile than just using something like dd

If your tr doesn't handle character-classes with variable-byte encodings correctly you could try:

  • sed -E -e 's/[[:upper:]]/\L&/g (GNU-specific)

What does .class mean in Java?

That means a Class with a type of anything (unknown).

You should read java generics tutorial to get to understand it better

Resize font-size according to div size

I was looking for the same funcionality and found this answer. However, I wanted to give you guys a quick update. It's CSS3's vmin unit.

p, li
{
  font-size: 1.2vmin;
}

vmin means 'whichever is smaller between the 1% of the ViewPort's height and the 1% of the ViewPort's width'.

More info on SitePoint

There is an error in XML document (1, 41)

I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.

Is there a way to collapse all code blocks in Eclipse?

Just to sum up:

  1. anycode:
    • ctrl + shift + NUMPAD_divide = collapse all
    • NUMPAD_multiply = exand all
  2. pydev:
    • -ctrl + 0 = collapse all
    • -ctrl + 9 = exand all

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

Convert python datetime to timestamp in milliseconds

For Python2.7 - modifying MYGz's answer to not strip milliseconds:

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s.%f')
d_in_ms = int(float(d)*1000)
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482248322760
2016-12-20 09:38:42.760000

How Do I Convert an Integer to a String in Excel VBA?

In my case, the function CString was not found. But adding an empty string to the value works, too.

Dim Test As Integer, Test2 As Variant
Test = 10
Test2 = Test & ""
//Test2 is now "10" not 10

What is the MySQL JDBC driver connection string?

For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-

class DBConnection {
   private static Connection con = null;
   private static String USERNAME = "your_mysql_username";
   private static String PASSWORD = "your_mysql_password";
   private static String DRIVER = "com.mysql.jdbc.Driver";
   private static String URL = "jdbc:mysql://localhost:3306/database_name";

   public static Connection getDatabaseConnection(){
       Class.forName(DRIVER);
       return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
   }
}

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

"Continue" (to next iteration) on VBScript

Your suggestion would work, but using a Do loop might be a little more readable.

This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.

Dim i

For i = 0 To 10
    Do
        If i = 4 Then Exit Do
        WScript.Echo i
    Loop While False
Next

As crush suggests, it looks a little better if you remove the extra indentation level.

Dim i

For i = 0 To 10: Do
    If i = 4 Then Exit Do
    WScript.Echo i
Loop While False: Next

Convert tuple to list and back

To convert tuples to list

(Commas were missing between the tuples in the given question, it was added to prevent error message)

Method 1:

level1 = (
     (1,1,1,1,1,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,1,1,1,1,1))

level1 = [list(row) for row in level1]

print(level1)

Method 2:

level1 = map(list,level1)

print(list(level1))

Method 1 took --- 0.0019991397857666016 seconds ---

Method 2 took --- 0.0010001659393310547 seconds ---

Understanding slice notation

Python slicing notation:

a[start:end:step]
  • For start and end, negative values are interpreted as being relative to the end of the sequence.
  • Positive indices for end indicate the position after the last element to be included.
  • Blank values are defaulted as follows: [+0:-0:1].
  • Using a negative step reverses the interpretation of start and end

The notation extends to (numpy) matrices and multidimensional arrays. For example, to slice entire columns you can use:

m[::,0:2:] ## slice the first two columns

Slices hold references, not copies, of the array elements. If you want to make a separate copy an array, you can use deepcopy().

HTML form input tag name element array with JavaScript

Try this something like this:

var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
  alert(p_ids[i].value);
}

Python strftime - date without leading 0?

We can do this sort of thing with the advent of the format method since python2.6:

>>> import datetime
>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now())
'2013/4/19'

Though perhaps beyond the scope of the original question, for more interesting formats, you can do stuff like:

>>> '{dt:%A} {dt:%B} {dt.day}, {dt.year}'.format(dt=datetime.datetime.now())
'Wednesday December 3, 2014'

And as of python3.6, this can be expressed as an inline formatted string:

Python 3.6.0a2 (v3.6.0a2:378893423552, Jun 13 2016, 14:44:21) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> f'{dt:%A} {dt:%B} {dt.day}, {dt.year}'
'Monday August 29, 2016'

Alternative to Intersect in MySQL

Your query would always return an empty recordset since cut_name= '?????' and cut_name='??' will never evaluate to true.

In general, INTERSECT in MySQL should be emulated like this:

SELECT  *
FROM    mytable m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    othertable o
        WHERE   (o.col1 = m.col1 OR (m.col1 IS NULL AND o.col1 IS NULL))
                AND (o.col2 = m.col2 OR (m.col2 IS NULL AND o.col2 IS NULL))
                AND (o.col3 = m.col3 OR (m.col3 IS NULL AND o.col3 IS NULL))
        )

If both your tables have columns marked as NOT NULL, you can omit the IS NULL parts and rewrite the query with a slightly more efficient IN:

SELECT  *
FROM    mytable m
WHERE   (col1, col2, col3) IN
        (
        SELECT  col1, col2, col3
        FROM    othertable o
        )

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

len() of a numpy array in python

You can transpose the array if you want to get the length of the other dimension.

len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)

When should the xlsm or xlsb formats be used?

One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.

position: fixed doesn't work on iPad and iPhone

I ended up using the new jQuery Mobile v1.1: http://jquerymobile.com/blog/2012/04/13/announcing-jquery-mobile-1-1-0/

We now have a solid re-write that provides true fixed toolbars on the a lot of popular platforms and safely falls back to static toolbar positioning in other browsers.

The coolest part about this approach is that, unlike JS-based solutions that impose the unnatural scrolling physics across all platforms, our scrolling feels 100% native because it is. This means that scrolling feels right everywhere and works with touch, mousewheel and keyboard user input. As a bonus, our CSS-based solution is super lightweight and doesn’t impact compatibility or accessibility.

Simpler way to check if variable is not equal to multiple string values?

Some basic regex would do the trick nicely for $some_variable !== 'uk' && $some_variable !== 'in':

if(!preg_match('/^uk|in$/', $some_variable)) {
    // Do something
}

jQuery - determine if input element is textbox or select list

alternatively you can retrieve DOM properties with .prop

here is sample code for select box

if( ctrl.prop('type') == 'select-one' ) { // for single select }

if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }

for textbox

  if( ctrl.prop('type') == 'text' ) { // for text box }

how do I create an array in jquery?

You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.

array('Item 1', 'Item 2', 'Items 3')  // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2')  // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')

Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:

['Item 1', 'Item 2', 'Item 3']  // array (numerically indexed)

An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:

{ first : 'Item 1', second : 'Item 2' }  // object (a.k.a. "associative array")

They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.


* Technically everything is an Object in Javascript, please put that aside for this argument. ;)

Which characters need to be escaped in HTML?

Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:

 1)  &lt; (<)
    
 2)  &gt; (>)
    
 3)  &amp; (&)

Also we may use double-quote (") as " and the single quote (') as &apos

Avoid putting dynamic content in <script> and <style>.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)

HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php

So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.

Changing to UTF-8 means re-saving your file:

Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.

Invisible or ambiguous characters:

A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.

One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.

An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using   makes it quite clear where such spaces appear in the text.

python request with authentication (access_token)

I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN

header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)

PHP exec() vs system() vs passthru()

If you're running your PHP script from the command-line, passthru() has one large benefit. It will let you execute scripts/programs such as vim, dialog, etc, letting those programs handle control and returning to your script only when they are done.

If you use system() or exec() to execute those scripts/programs, it simply won't work.

Gotcha: For some reason, you can't execute less with passthru() in PHP.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

Number of occurrences of a character in a string

The most straight forward, and most efficient, would be to simply loop through the characters in the string:

int cnt = 0;
foreach (char c in test) {
  if (c == '&') cnt++;
}

You can use Linq extensions to make a simpler, and almost as efficient version. There is a bit more overhead, but it's still surprisingly close to the loop in performance:

int cnt = test.Count(c => c == '&');

Then there is the old Replace trick, however that is better suited for languages where looping is awkward (SQL) or slow (VBScript):

int cnt = test.Length - test.Replace("&", "").Length;

Format Date/Time in XAML in Silverlight

In SL5 I found this to work:

<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">

Disable Rails SQL logging in console

In case someone wants to actually knock out SQL statement logging (without changing logging level, and while keeping the logging from their AR models):

The line that writes to the log (in Rails 3.2.16, anyway) is the call to debug in lib/active_record/log_subscriber.rb:50.

That debug method is defined by ActiveSupport::LogSubscriber.

So we can knock out the logging by overwriting it like so:

module ActiveSupport
  class LogSubscriber
    def debug(*args, &block)
    end
  end
end

How to cherry-pick from a remote branch?

Since "zebra" is a remote branch, I was thinking I don't have its data locally.

You are correct that you don't have the right data, but tried to resolve it in the wrong way. To collect data locally from a remote source, you need to use git fetch. When you did git checkout zebra you switched to whatever the state of that branch was the last time you fetched. So fetch from the remote first:

# fetch just the one remote
git fetch <remote>
# or fetch from all remotes
git fetch --all
# make sure you're back on the branch you want to cherry-pick to
git cherry-pick xyz

Maven Unable to locate the Javac Compiler in:

It sounds like you have JDK_HOME defined as a user variable and PATH defined as a System variable, or vice versa - echo %PATH% should not contain unresolved variables like ...;%JDK_HOME%.

Make sure that the %JDK_HOME%\bin path is on your PATH variable, unresolved, even if you have to put the path in explicitly.

jQuery Set Cursor Position in Text Area

This works for me in chrome

$('#input').focus(function() {
    setTimeout( function() {
        document.getElementById('input').selectionStart = 4;
        document.getElementById('input').selectionEnd = 4;
    }, 1);
});

Apparently you need a delay of a microsecond or more, because usually a user focusses on the text field by clicking at some position in the text field (or by hitting tab) which you want to override, so you have to wait till the position is set by the user click and then change it.

Tree implementation in Java (root, parents and children)

This tree is not a binary tree, so you need an array of the children elements, like List.

public Node(Object data, List<Node> children) {
    this.data = data;
    this.children = children;
}

Then create the instances.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

Deleting node_modules and package-lock.json and npm i solve the issue for me.

Express: How to pass app-instance to routes from a different file?

Like I said in the comments, you can use a function as module.exports. A function is also an object, so you don't have to change your syntax.

app.js

var controllers = require('./controllers')({app: app});

controllers.js

module.exports = function(params)
{
    return require('controllers/index')(params);
}

controllers/index.js

function controllers(params)
{
  var app = params.app;

  controllers.posts = require('./posts');

  controllers.index = function(req, res) {
    // code
  };
}

module.exports = controllers;

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

sscanf in Python

Update: The Python documentation for its regex module, re, includes a section on simulating scanf, which I found more useful than any of the answers above.

https://docs.python.org/2/library/re.html#simulating-scanf

Open an html page in default browser with VBA?

You can even say:

FollowHyperlink "www.google.com"

If you get Automation Error then use http://:

ThisWorkbook.FollowHyperlink("http://www.google.com")

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Although most of these previous answers will work, I suggest you explore the provider or BloC architectures, both of which have been recommended by Google.

In short, the latter will create a stream that reports to widgets in the widget tree whenever a change in the state happens and it updates all relevant views regardless of where it is updated from.

Here is a good overview you can read to learn more about the subject: https://bloclibrary.dev/#/

Threading pool similar to the multiprocessing Pool?

Hi to use the thread pool in Python you can use this library :

from multiprocessing.dummy import Pool as ThreadPool

and then for use, this library do like that :

pool = ThreadPool(threads)
results = pool.map(service, tasks)
pool.close()
pool.join()
return results

The threads are the number of threads that you want and tasks are a list of task that most map to the service.

shared global variables in C

In the header file

header file

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

In the file with the file you want the global to live:

#define MAIN_FILE
#include "share.h"

In the other files that need the extern version:

#include "share.h"

NHibernate.MappingException: No persister for: XYZ

I got this off of here:

In my case the mapping class was not public. In other words, instead of:

public class UserMap : ClassMap<user>  // note the public!

I just had:

class UserMap : ClassMap<user>

Make footer stick to bottom of page using Twitter Bootstrap

just add the class navbar-fixed-bottom to your footer.

<div class="footer navbar-fixed-bottom">

Update for Bootstrap 4 -

as mentioned by Sara Tibbetts - class is fixed-bottom

<div class="footer fixed-bottom">