Programs & Examples On #Commandparameter

Pass command parameter to method in ViewModel in WPF?

Try this:

 public class MyVmBase : INotifyPropertyChanged
{
  private ICommand _clickCommand;
   public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
        }
    }
    
       public void MyAction(object message)
    {
        if(message == null)
        {
            Notify($"Method {message} not defined");
            return;
        }
        switch (message.ToString())
        {
            case "btnAdd":
                {
                    btnAdd_Click();
                    break;
                }

            case "BtnEdit_Click":
                {
                    BtnEdit_Click();
                    break;
                }

            default:
                throw new Exception($"Method {message} not defined");
                break;
        }
    }
}

  public class CommandHandler : ICommand
{
    private Action<object> _action;
    private Func<object, bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action<object> action, Func<object, bool> canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
        _canExecute = canExecute ?? (x => true);
    }
    public CommandHandler(Action<object> action) : this(action, null)
    {
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
    public void Refresh()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

And in xaml:

     <Button
    Command="{Binding ClickCommand}"
    CommandParameter="BtnEdit_Click"/>

How do I remove all null and empty string values from an object?

Here is the optimized code snippet to remove empty arrays/objects as well:

function removeNullsInObject(obj) {
    if( typeof obj === 'string' ){ return; }
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if ($.isArray(value)) {
            if( value.length === 0 ){ delete obj[key]; return; }
            $.each(value, function (k,v) {
                removeNullsInObject(v);
            });
        } else if (typeof value === 'object') {
            if( Object.keys(value).length === 0 ){ 
                delete obj[key]; return; 
            }
            removeNullsInObject(value);
        }
    }); 
 }

Thanks @Alexis king :)

Binding a Button's visibility to a bool value in ViewModel

There's a third way that doesn't require a converter or a change to your view model: use a style:

<Style TargetType="Button">
   <Setter Property="Visibility" Value="Collapsed"/>
   <Style.Triggers>
      <DataTrigger Binding="{Binding IsVisible}" Value="True">
         <Setter Property="Visibility" Value="Visible"/>
      </DataTrigger>
   </Style.Triggers>
</Style>

I tend to prefer this technique because I use it in a lot of cases where what I'm binding to is not boolean - e.g. displaying an element only if its DataContext is not null, or implementing multi-state displays where different layouts appear based on the setting of an enum in the view model.

MVVM Passing EventArgs As Command Parameter

I know this is a fairly old question, but I ran into the same problem today and wasn't too interested in referencing all of MVVMLight just so I can use event triggers with event args. I have used MVVMLight in the past and it's a great framework, but I just don't want to use it for my projects any more.

What I did to resolve this problem was create an ULTRA minimal, EXTREMELY adaptable custom trigger action that would allow me to bind to the command and provide an event args converter to pass on the args to the command's CanExecute and Execute functions. You don't want to pass the event args verbatim, as that would result in view layer types being sent to the view model layer (which should never happen in MVVM).

Here is the EventCommandExecuter class I came up with:

public class EventCommandExecuter : TriggerAction<DependencyObject>
{
    #region Constructors

    public EventCommandExecuter()
        : this(CultureInfo.CurrentCulture)
    {
    }

    public EventCommandExecuter(CultureInfo culture)
    {
        Culture = culture;
    }

    #endregion

    #region Properties

    #region Command

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    #region EventArgsConverterParameter

    public object EventArgsConverterParameter
    {
        get { return (object)GetValue(EventArgsConverterParameterProperty); }
        set { SetValue(EventArgsConverterParameterProperty, value); }
    }

    public static readonly DependencyProperty EventArgsConverterParameterProperty =
        DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    public IValueConverter EventArgsConverter { get; set; }

    public CultureInfo Culture { get; set; }

    #endregion

    protected override void Invoke(object parameter)
    {
        var cmd = Command;

        if (cmd != null)
        {
            var param = parameter;

            if (EventArgsConverter != null)
            {
                param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
            }

            if (cmd.CanExecute(param))
            {
                cmd.Execute(param);
            }
        }
    }
}

This class has two dependency properties, one to allow binding to your view model's command, the other allows you to bind the source of the event if you need it during event args conversion. You can also provide culture settings if you need to (they default to the current UI culture).

This class allows you to adapt the event args so that they may be consumed by your view model's command logic. However, if you want to just pass the event args on verbatim, simply don't specify an event args converter.

The simplest usage of this trigger action in XAML is as follows:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter Command="{Binding Path=Update, Mode=OneTime}" EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

If you needed access to the source of the event, you would bind to the owner of the event

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter 
            Command="{Binding Path=Update, Mode=OneTime}" 
            EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"
            EventArgsConverterParameter="{Binding ElementName=SomeEventSource, Mode=OneTime}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

(this assumes that the XAML node you're attaching the triggers to has been assigned x:Name="SomeEventSource"

This XAML relies on importing some required namespaces

xmlns:cmd="clr-namespace:MyProject.WPF.Commands"
xmlns:c="clr-namespace:MyProject.WPF.Converters"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and creating an IValueConverter (called NameChangedArgsToStringConverter in this case) to handle the actual conversion logic. For basic converters I usually create a default static readonly converter instance, which I can then reference directly in XAML as I have done above.

The benefit of this solution is that you really only need to add a single class to any project to use the interaction framework much the same way that you would use it with InvokeCommandAction. Adding a single class (of about 75 lines) should be much more preferable to an entire library to accomplish identical results.

NOTE

this is somewhat similar to the answer from @adabyron but it uses event triggers instead of behaviours. This solution also provides an event args conversion ability, not that @adabyron's solution could not do this as well. I really don't have any good reason why I prefer triggers to behaviours, just a personal choice. IMO either strategy is a reasonable choice.

Set focus on TextBox in WPF from view model

I have found solution by editing code as per following. There is no need to set Binding property first False then True.

public static class FocusExtension
{

    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }


    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }


    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
         "IsFocused", typeof(bool), typeof(FocusExtension),
         new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));


    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d != null && d is Control)
        {
            var _Control = d as Control;
            if ((bool)e.NewValue)
            {
                // To set false value to get focus on control. if we don't set value to False then we have to set all binding
                //property to first False then True to set focus on control.
                OnLostFocus(_Control, null);
                _Control.Focus(); // Don't care about false values.
            }
        }
    }

    private static void OnLostFocus(object sender, RoutedEventArgs e)
    {
        if (sender != null && sender is Control)
        {
            (sender as Control).SetValue(IsFocusedProperty, false);
        }
    }
}

Passing two command parameters using a WPF binding

Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<string, string> tuple = new Tuple<string, string>(
            (string)values[0], (string)values[1]);
        return (object)tuple;
    }      
} 

// ...

public void OnExecute(object parameter) 
{
    var param = (Tuple<string, string>) parameter;
}

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

WPF User Control Parent

Try using the following:

Window parentWindow = Window.GetWindow(userControlReference);

The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

this.Loaded += new RoutedEventHandler(UserControl_Loaded); 

C++ Array of pointers: delete or delete []?

Your second example is correct; you don't need to delete the monsters array itself, just the individual objects you created.

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

How can I resize an image using Java?

If you dont want to import imgScalr like @Riyad Kalla answer above which i tested too works fine, you can do this taken from Peter Walser answer @Peter Walser on another issue though:

 /**
     * utility method to get an icon from the resources of this class
     * @param name the name of the icon
     * @return the icon, or null if the icon wasn't found.
     */
    public Icon getIcon(String name) {
        Icon icon = null;
        URL url = null;
        ImageIcon imgicon = null;
        BufferedImage scaledImage = null;
        try {
            url = getClass().getResource(name);

            icon = new ImageIcon(url);
            if (icon == null) {
                System.out.println("Couldn't find " + url);
            }

            BufferedImage bi = new BufferedImage(
                    icon.getIconWidth(),
                    icon.getIconHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.createGraphics();
            // paint the Icon to the BufferedImage.
            icon.paintIcon(null, g, 0,0);
            g.dispose();

            bi = resizeImage(bi,30,30);
            scaledImage = bi;// or replace with this line Scalr.resize(bi, 30,30);
            imgicon = new ImageIcon(scaledImage);

        } catch (Exception e) {
            System.out.println("Couldn't find " + getClass().getName() + "/" + name);
            e.printStackTrace();
        }
        return imgicon;
    }

 public static BufferedImage resizeImage (BufferedImage image, int areaWidth, int areaHeight) {
        float scaleX = (float) areaWidth / image.getWidth();
        float scaleY = (float) areaHeight / image.getHeight();
        float scale = Math.min(scaleX, scaleY);
        int w = Math.round(image.getWidth() * scale);
        int h = Math.round(image.getHeight() * scale);

        int type = image.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

        boolean scaleDown = scale < 1;

        if (scaleDown) {
            // multi-pass bilinear div 2
            int currentW = image.getWidth();
            int currentH = image.getHeight();
            BufferedImage resized = image;
            while (currentW > w || currentH > h) {
                currentW = Math.max(w, currentW / 2);
                currentH = Math.max(h, currentH / 2);

                BufferedImage temp = new BufferedImage(currentW, currentH, type);
                Graphics2D g2 = temp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(resized, 0, 0, currentW, currentH, null);
                g2.dispose();
                resized = temp;
            }
            return resized;
        } else {
            Object hint = scale > 2 ? RenderingHints.VALUE_INTERPOLATION_BICUBIC : RenderingHints.VALUE_INTERPOLATION_BILINEAR;

            BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = resized.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
            g2.drawImage(image, 0, 0, w, h, null);
            g2.dispose();
            return resized;
        }
    }

Git list of staged files

You can Try using :- git ls-files -s

Zoom to fit all markers in Mapbox or Leaflet

var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());

See the documentation for more info.

Android - save/restore fragment state

Try this :

@Override
protected void onPause() {
    super.onPause();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").setRetainInstance(true);
}

@Override
protected void onResume() {
    super.onResume();
    if (getSupportFragmentManager().findFragmentByTag("MyFragment") != null)
        getSupportFragmentManager().findFragmentByTag("MyFragment").getRetainInstance();
}

Hope this will help.

Also you can write this to activity tag in menifest file :

  android:configChanges="orientation|screenSize"

Good luck !!!

Git: See my last commit

git log -1 --stat

could work

Find an object in array?

Use contains:

var yourItem:YourType!
if contains(yourArray, item){
    yourItem = item
}

Or you could try what Martin pointed you at, in the comments and give filter another try: Find Object with Property in Array.

SQL update query using joins

One of the easiest way is to use a common table expression (since you're already on SQL 2005):

with cte as (
select
    im.itemid
    ,im.sku as iSku
    ,gm.SKU as GSKU
    ,mm.ManufacturerId as ManuId
    ,mm.ManufacturerName
    ,im.mf_item_number
    ,mm.ManufacturerID
    , <your other field>
from 
    item_master im, group_master gm, Manufacturer_Master mm 
where
    im.mf_item_number like 'STA%'
    and im.sku=gm.sku
    and gm.ManufacturerID = mm.ManufacturerID
    and gm.manufacturerID=34)
update cte set mf_item_number = <your other field>

The query execution engine will figure out on its own how to update the record.

Oracle select most recent date record

select *
from (select
  staff_id, site_id, pay_level, date, 
  rank() over (partition by staff_id order by date desc) r
  from owner.table
  where end_enrollment_date is null
)
where r = 1

How can I update the current line in a C# Windows Console App?

You can use Console.SetCursorPosition to set the position of the cursor and then write at the current position.

Here is an example showing a simple "spinner":

static void Main(string[] args)
{
    var spin = new ConsoleSpinner();
    Console.Write("Working....");
    while (true) 
    {
        spin.Turn();
    }
}

public class ConsoleSpinner
{
    int counter;

    public void Turn()
    {
        counter++;        
        switch (counter % 4)
        {
            case 0: Console.Write("/"); counter = 0; break;
            case 1: Console.Write("-"); break;
            case 2: Console.Write("\\"); break;
            case 3: Console.Write("|"); break;
        }
        Thread.Sleep(100);
        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
    }
}

Note that you will have to make sure to overwrite any existing output with new output or blanks.

Update: As it has been criticized that the example moves the cursor only back by one character, I will add this for clarification: Using SetCursorPosition you may set the cursor to any position in the console window.

Console.SetCursorPosition(0, Console.CursorTop);

will set the cursor to the beginning of the current line (or you can use Console.CursorLeft = 0 directly).

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

How to update large table with millions of rows in SQL Server?

WHILE EXISTS (SELECT * FROM TableName WHERE Value <> 'abc1' AND Parameter1 = 'abc' AND Parameter2 = 123)
BEGIN
UPDATE TOP (1000) TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123 AND Value <> 'abc1'
END

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

Use multiselect function as below.

$("#drp_Books_Ill_Illustrations").val(["val1", "val2"]).trigger("change");

React won't load local images

Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.

When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.

As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:

import React from "react";

function JobCard(props) {  

  const { logo } = props;
  
  return (
      <div className="jobCards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  

The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.

Center content in responsive bootstrap navbar

This code worked for me

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}
.navbar .navbar-collapse {
    text-align: center;
}

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

.attr("disabled", "disabled") issue

UPDATED

DEMO: http://jsbin.com/uneti3/3

your code is wrong, it should be something like this:

 $(bla).click(function() { 
        var disable =  $target.toggleClass('open').hasClass('open');
       $target.prev().prop("disabled", disable);
  });

you are using the toggleClass function in wrong way

Javascript / Chrome - How to copy an object from the webkit inspector as code

Add this to your console and execute

copy(JSON.stringify(foo));

This copies your JSON to clipboard

Duplicate AssemblyVersion Attribute

I had the same error and it was underlining the Assembly Vesrion and Assembly File Version so reading Luqi answer I just added them as comments and the error was solved

// AssemblyVersion is the CLR version. Change this only when making breaking    changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]

close fxml window by code, javafx

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)

How do I convert a long to a string in C++?

You could use stringstream.

#include <sstream>

// ...
std::string number;
std::stringstream strstream;
strstream << 1L;
strstream >> number;

There is usually some proprietary C functions in the standard library for your compiler that does it too. I prefer the more "portable" variants though.

The C way to do it would be with sprintf, but that is not very secure. In some libraries there is new versions like sprintf_s which protects against buffer overruns.

Rails: How can I rename a database column in a Ruby on Rails migration?

$:  rails g migration RenameHashedPasswordColumn
invoke  active_record
      create    db/migrate/20160323054656_rename_hashed_password_column.rb

Open that migration file and modify that file as below(Do enter your original table_name)

class  RenameHashedPasswordColumn < ActiveRecord::Migration
  def change
    rename_column :table_name, :hased_password, :hashed_password
  end
end

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.


Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)


Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
%>
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">
    <tr>      
      <td>${entry.key}</td>
      <td>${entry.value}</td>
      <td>${entry.key.class}</td>
    </tr>
    </c:forEach>
</table>

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    <p>
    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
    <p>

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

Request UAC elevation from within a Python script?

The following example builds on MARTIN DE LA FUENTE SAAVEDRA's excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0] should probably be replaced with a function call: subprocess.list2cmdline(sys.argv).

#! /usr/bin/env python3
import ctypes
import enum
import subprocess
import sys

# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx


# noinspection SpellCheckingInspection
class SW(enum.IntEnum):
    HIDE = 0
    MAXIMIZE = 3
    MINIMIZE = 6
    RESTORE = 9
    SHOW = 5
    SHOWDEFAULT = 10
    SHOWMAXIMIZED = 3
    SHOWMINIMIZED = 2
    SHOWMINNOACTIVE = 7
    SHOWNA = 8
    SHOWNOACTIVATE = 4
    SHOWNORMAL = 1


class ERROR(enum.IntEnum):
    ZERO = 0
    FILE_NOT_FOUND = 2
    PATH_NOT_FOUND = 3
    BAD_FORMAT = 11
    ACCESS_DENIED = 5
    ASSOC_INCOMPLETE = 27
    DDE_BUSY = 30
    DDE_FAIL = 29
    DDE_TIMEOUT = 28
    DLL_NOT_FOUND = 32
    NO_ASSOC = 31
    OOM = 8
    SHARE = 26


def bootstrap():
    if ctypes.windll.shell32.IsUserAnAdmin():
        main()
    else:
       # noinspection SpellCheckingInspection
        hinstance = ctypes.windll.shell32.ShellExecuteW(
            None,
            'runas',
            sys.executable,
            subprocess.list2cmdline(sys.argv),
            None,
            SW.SHOWNORMAL
        )
        if hinstance <= 32:
            raise RuntimeError(ERROR(hinstance))


def main():
    # Your Code Here
    print(input('Echo: '))


if __name__ == '__main__':
    bootstrap()

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Where does gcc look for C and C++ header files?

One could view the (additional) include path for a C program from bash by checking out the following:

echo $C_INCLUDE_PATH

If this is empty, it could be modified to add default include locations, by:

export C_INCLUDE_PATH=$C_INCLUDE_PATH:/usr/include

Loop in Jade (currently known as "Pug") template engine

Just adding another possibility as it might help someone that's trying to both iterate over an array AND maintain a count. For example, the code below goes through an array named items and only displays the first 3 items. Notice that the each and the if are native jade and don't need a hyphen.

ul
  - var count = 0;
  each item in items
    if count < 3
      li= item.name
    - count++;

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

Error: Java: invalid target release: 11 - IntelliJ IDEA

Below changes worked for me and hope the same works for you.

  1. Change the version of Java from 11 to 8 in pom.xml file
    <java.version>1.8</java.version>

  2. Go to, File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler
    Here, in Module column you can see your project listed and in Target bytecode version column, Java version for the project is already specified(mostly 11), change it to 8

  3. Go to, File -> Project Structure -> Modules. Here, in Source tab, you can see Language level option, choose 8 - Lambdas, type annotations etc.. Finally, choose Apply and OK, you're good to go.

javax vs java package

Some packages like javax.swing were not included in java standard library at first. Sun company decided to consider them official and included them into the early versions of java as standard libraries or standard extensions.

By convention, all the standard extensions start with an X while they can get promoted to first-class over time like what happened for javax.swing.

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

JavaScript adding decimal numbers issue

function add(){
    var first=parseFloat($("#first").val());
    var second=parseFloat($("#second").val());
    $("#result").val(+(first+second).toFixed(2));
}

DEMO.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

You should include cascade="all" (if using xml) or cascade=CascadeType.ALL (if using annotations) on your collection mapping.

This happens because you have a collection in your entity, and that collection has one or more items which are not present in the database. By specifying the above options you tell hibernate to save them to the database when saving their parent.

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

How do I count unique items in field in Access query?

Try this

SELECT Count(*) AS N
FROM
(SELECT DISTINCT Name FROM table1) AS T;

Read this for more info.

Why doesn't C++ have a garbage collector?

Imposing garbage collection is really a low level to high level paradigm shift.

If you look at the way strings are handled in a language with garbage collection, you will find they ONLY allow high level string manipulation functions and do not allow binary access to the strings. Simply put, all string functions first check the pointers to see where the string is, even if you are only drawing out a byte. So if you are doing a loop that processes each byte in a string in a language with garbage collection, it must compute the base location plus offset for each iteration, because it cannot know when the string has moved. Then you have to think about heaps, stacks, threads, etc etc.

How to check if a line has one of the strings in a list?

One approach is to combine the search strings into a regex pattern as in this answer.

Editing an item in a list<T>

You don't need to use linq since List<T> provides the methods to do this:

int index = lst.FindLastIndex(c => c.Number == textBox6.Text);
if(index != -1)
{
    lst[index] = new Class1() { ... };
}

HTML Table width in percentage, table rows separated equally

This is definitely the cleanest answer to the question: https://stackoverflow.com/a/14025331/1008519. In combination with table-layout: fixed I often find <colgroup> a great tool to make columns act as you want (see codepen here):

_x000D_
_x000D_
table {_x000D_
 /* When set to 'fixed', all columns that do not have a width applied will get the remaining space divided between them equally */_x000D_
 table-layout: fixed;_x000D_
}_x000D_
.fixed-width {_x000D_
  width: 100px;_x000D_
}_x000D_
.col-12 {_x000D_
  width: 100%;_x000D_
}_x000D_
.col-11 {_x000D_
  width: 91.666666667%;_x000D_
}_x000D_
.col-10 {_x000D_
  width: 83.333333333%;_x000D_
}_x000D_
.col-9 {_x000D_
  width: 75%;_x000D_
}_x000D_
.col-8 {_x000D_
  width: 66.666666667%;_x000D_
}_x000D_
.col-7 {_x000D_
  width: 58.333333333%;_x000D_
}_x000D_
.col-6 {_x000D_
  width: 50%;_x000D_
}_x000D_
.col-5 {_x000D_
  width: 41.666666667%;_x000D_
}_x000D_
.col-4 {_x000D_
  width: 33.333333333%;_x000D_
}_x000D_
.col-3 {_x000D_
  width: 25%;_x000D_
}_x000D_
.col-2 {_x000D_
  width: 16.666666667%;_x000D_
}_x000D_
.col-1 {_x000D_
  width: 8.3333333333%;_x000D_
}_x000D_
_x000D_
/* Stylistic improvements from here */_x000D_
_x000D_
.align-left {_x000D_
  text-align: left;_x000D_
}_x000D_
.align-right {_x000D_
  text-align: right;_x000D_
}_x000D_
table {_x000D_
  width: 100%;_x000D_
}_x000D_
table > tbody > tr > td,_x000D_
table > thead > tr > th {_x000D_
  padding: 8px;_x000D_
  border: 1px solid gray;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
  <colgroup>_x000D_
    <col /> <!-- take up rest of the space -->_x000D_
    <col class="fixed-width" /> <!-- fixed width -->_x000D_
    <col class="col-3" /> <!-- percentage width -->_x000D_
    <col /> <!-- take up rest of the space -->_x000D_
  </colgroup>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th class="align-left">Title</th>_x000D_
      <th class="align-right">Count</th>_x000D_
      <th class="align-left">Name</th>_x000D_
      <th class="align-left">Single</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
      <td class="align-right">19</td>_x000D_
      <td class="align-left">Lisa McArthur</td>_x000D_
      <td class="align-left">No</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a shorter title</td>_x000D_
      <td class="align-right">2</td>_x000D_
      <td class="align-left">John Oliver Nielson McAllister</td>_x000D_
      <td class="align-left">Yes</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" border="0">_x000D_
  <!-- define everything with percentage width -->_x000D_
  <colgroup>_x000D_
    <col class="col-6" />_x000D_
    <col class="col-1" />_x000D_
    <col class="col-4" />_x000D_
    <col class="col-1" />_x000D_
  </colgroup>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th class="align-left">Title</th>_x000D_
      <th class="align-right">Count</th>_x000D_
      <th class="align-left">Name</th>_x000D_
      <th class="align-left">Single</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a very looooooooooong title that may break into multiple lines</td>_x000D_
      <td class="align-right">19</td>_x000D_
      <td class="align-left">Lisa McArthur</td>_x000D_
      <td class="align-left">No</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="align-left">This is a shorter title</td>_x000D_
      <td class="align-right">2</td>_x000D_
      <td class="align-left">John Oliver Nielson McAllister</td>_x000D_
      <td class="align-left">Yes</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Append column to pandas dataframe

Both join() and concat() way could solve the problem. However, there is one warning I have to mention: Reset the index before you join() or concat() if you trying to deal with some data frame by selecting some rows from another DataFrame.

One example below shows some interesting behavior of join and concat:

dat1 = pd.DataFrame({'dat1': range(4)})
dat2 = pd.DataFrame({'dat2': range(4,8)})
dat1.index = [1,3,5,7]
dat2.index = [2,4,6,8]

# way1 join 2 DataFrames
print(dat1.join(dat2))
# output
   dat1  dat2
1     0   NaN
3     1   NaN
5     2   NaN
7     3   NaN

# way2 concat 2 DataFrames
print(pd.concat([dat1,dat2],axis=1))
#output
   dat1  dat2
1   0.0   NaN
2   NaN   4.0
3   1.0   NaN
4   NaN   5.0
5   2.0   NaN
6   NaN   6.0
7   3.0   NaN
8   NaN   7.0

#reset index 
dat1 = dat1.reset_index(drop=True)
dat2 = dat2.reset_index(drop=True)
#both 2 ways to get the same result

print(dat1.join(dat2))
   dat1  dat2
0     0     4
1     1     5
2     2     6
3     3     7


print(pd.concat([dat1,dat2],axis=1))
   dat1  dat2
0     0     4
1     1     5
2     2     6
3     3     7

SELECT * FROM X WHERE id IN (...) with Dapper ORM

Dapper supports this directly. For example...

string sql = "SELECT * FROM SomeTable WHERE id IN @ids"
var results = conn.Query(sql, new { ids = new[] { 1, 2, 3, 4, 5 }});

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

Using %s in C correctly - very basic level

Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

Yes, you can. But if you have non-unique entries on your table, it will fail. Here is the how to add unique constraint on your table. If you're using PostgreSQL 9.x you can follow below instruction.

CREATE UNIQUE INDEX constraint_name ON table_name (columns);

How to select different app.config for several build configurations

Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :

 <None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />

 <None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />

Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!

How to retry image pull in a kubernetes Pods?

Most probably the issue of ImagePullBackOff is due to either the image not being present or issue with the pod YAML file.

What I will do is this

kubectl get pod -n $namespace $POD_NAME --export > pod.yaml | kubectl -f apply -

I would also see the pod.yaml to see the why the earlier pod didn't work

Python vs Cpython

The original, and standard, implementation of Python is usually called CPython when you want to contrast it with the other options (and just plain “Python” otherwise). This name comes from the fact that it is coded in portable ANSI C language code. This is the Python that you fetch from http://www.python.org, get with the ActivePython and Enthought distributions, and have automatically on most Linux and Mac OS X machines. If you’ve found a preinstalled version of Python on your machine, it’s probably CPython, unless your company or organization is using Python in more specialized ways.

Unless you want to script Java or .NET applications with Python or find the benefits of Stackless or PyPy compelling, you probably want to use the standard CPython system. Because it is the reference implementation of the language, it tends to run the fastest, be the most complete, and be more up-to-date and robust than the alternative systems.

What is the difference between "::" "." and "->" in c++

Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow.

:: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static function.

. - This allows access to a member function on an already created object. For instance, Foo x; x.bar() calls the method bar() on instantiated object x which has type Foo. You can also use this to access public class variables.

-> - Essentially the same thing as . except this works on pointer types. In essence it dereferences the pointer, than calls .. Using this is equivalent to (*ptr).method()

Are global variables bad?

In the end of the day, your program or app can still work but its a matter of being tidy and having a complete understanding of whats going on. If you share a variable value among all functions, it may become difficult to trace what function is changing the value(if the function does so) and makes debugging a million times harder

Difference between Fact table and Dimension table?

  1. The fact table mainly consists of business facts and foreign keys that refer to primary keys in the dimension tables. A dimension table consists mainly of descriptive attributes that are textual fields.
  2. A dimension table contains a surrogate key, natural key, and a set of attributes. On the contrary, a fact table contains a foreign key, measurements, and degenerated dimensions.
  3. Dimension tables provide descriptive or contextual information for the measurement of a fact table. On the other hand, fact tables provide the measurements of an enterprise.
  4. When comparing the size of the two tables, a fact table is bigger than a dimensional table. In a comparison table, more dimensions are presented than the fact tables. In a fact table, less numbers of facts are observed.
  5. The dimension table has to be loaded first. While loading the fact tables, one should have to look at the dimension table. This is because the fact table has measures, facts, and foreign keys that are the primary keys in the dimension table.

Read more: Dimension Table and Fact Table | Difference Between | Dimension Table vs Fact Table http://www.differencebetween.net/technology/hardware-technology/dimension-table-and-fact-table/#ixzz3SBp8kPzo

How do I connect to my existing Git repository using Visual Studio Code?

  1. Use git clone to clone your repository into a folder (say work). You should see a new subfolder, work/.git.
  2. Open folder work in Visual Studio Code - everything should work fine!

PS: Blow away the temporary folder.

How to change already compiled .class file without decompile?

As far as I've been able to find out, there is no simple way to do it. The easiest way is to not actually convert the class file into an executable, but to wrap an executable launcher around the class file. That is, create an executable file (perhaps an OS-based, executable scripting file) which simply invokes the Java class through the command line.

If you want to actually have a program that does it, you should look into some of the automated installers out there.

Here is a way I've found:

[code]
import java.io.*;
import java.util.jar.*;

class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}

@Override
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}

public class ExeCreator {
public static int buffer = 10240;
protected void create(File exefile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(exefile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println("Adding " + listFiles[i].getName());
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);

FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}

public static void main(String[]args){
ExeCreator exe=new ExeCreator();
FilenameFilter ff = new OnlyExt("class");
File folder = new File("./examples");
File[] files = folder.listFiles(ff);
File file=new File("examples.exe");
exe.create(file, files);
}

}


[/code]`

Java: Clear the console

Try this: only works on console, not in NetBeans integrated console.

public static void cls(){
    try {

     if (System.getProperty("os.name").contains("Windows"))
         new ProcessBuilder("cmd", "/c", 
                  "cls").inheritIO().start().waitFor();
     else
         Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

"Unable to launch the IIS Express Web server" error

In my case i tried following things to fix this problem.

  1. Delete the iisexpress folder from "MyDocuments"

  2. Go to Solution Explorer --> Right click on the Project --> Go to Properties --> Go to Web tab --> See the Servers --> click on radio button "USe Visual Studio Developtment Server"

I hope this will help you.

How to filter array when object key value is in array

Fastest way (will take extra memory):

var empid=[1,4,5]
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] ;

var empIdObj={};

empid.forEach(function(element) {
empIdObj[element]=true;
});

var filteredArray=[];

records.forEach(function(element) {
if(empIdObj[element.empid])
    filteredArray.push(element)
});

Disable Logback in SpringBoot

If this error occurred in SpringBoot when you are trying to use log4j2 then do these steps:

  • Remove the jar from while packeging by adding this "excludeGroupIds log4j-slf4j-impl /excludeGroupIds"
  • Find out the which library is depends on "logback-classic" by using command "mvn dependecy:tree"
  • Wherever you find it exclude it from the dependency.

This error occurred because logback override the log4j2 changes. SO if you want to use log4j2 then you have to remove logback library and dependencies.

Hope this will help someone.

Empty set literal?

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

Global environment variables in a shell script

source myscript.sh is also feasible.

Description for linux command source:

source is a Unix command that evaluates the file following the command, 
as a list of commands, executed in the current context

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout.

This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.xml file.

It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language.

example: XML file saved at res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

This layout XML applies a string to a View:

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/yellow" />

Similarly colors should be stored in colors.xml and then referenced by using @color/color_name

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Black">#000000</color>
</resources>

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I faced the same problem. I restarted the oracle service for that DB instance and the error is gone.

JSP : JSTL's <c:out> tag

c:out escapes HTML characters so that you can avoid cross-site scripting.

if person.name = <script>alert("Yo")</script>

the script will be executed in the second case, but not when using c:out

How to fix the session_register() deprecated issue?

Use $_SESSION directly to set variables. Like this:

$_SESSION['name'] = 'stack';

Instead of:

$name = 'stack';
session_register("name");

Read More Here

If two cells match, return value from third

=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))

Will return the answer you want and also remove the #N/A result that would appear if you couldn't find a result due to it not appearing in your lookup list.

Ross

Can someone explain Microsoft Unity?

I am covering most of the examples of Dependency Injection in ASP.NET Web API 2

public interface IShape
{
    string Name { get; set; }
}

public class NoShape : IShape
{
    public string Name { get; set; } = "I have No Shape";
}

public class Circle : IShape
{
    public string Name { get; set; } = "Circle";
}

public class Rectangle : IShape
{
    public Rectangle(string name)
    {
        this.Name = name;
    }

    public string Name { get; set; } = "Rectangle";
}

In DIAutoV2Controller.cs Auto Injection mechanism is used

[RoutePrefix("api/v2/DIAutoExample")]
public class DIAutoV2Controller : ApiController
{
    private string ConstructorInjected;
    private string MethodInjected1;
    private string MethodInjected2;
    private string MethodInjected3;

    [Dependency]
    public IShape NoShape { get; set; }

    [Dependency("Circle")]
    public IShape ShapeCircle { get; set; }

    [Dependency("Rectangle")]
    public IShape ShapeRectangle { get; set; }

    [Dependency("PiValueExample1")]
    public double PiValue { get; set; }

    [InjectionConstructor]
    public DIAutoV2Controller([Dependency("Circle")]IShape shape1, [Dependency("Rectangle")]IShape shape2, IShape shape3)
    {
        this.ConstructorInjected = shape1.Name + " & " + shape2.Name + " & " + shape3.Name;
    }

    [NonAction]
    [InjectionMethod]
    public void Initialize()
    {
        this.MethodInjected1 = "Default Initialize done";
    }

    [NonAction]
    [InjectionMethod]
    public void Initialize2([Dependency("Circle")]IShape shape1)
    {
        this.MethodInjected2 = shape1.Name;
    }

    [NonAction]
    [InjectionMethod]
    public void Initialize3(IShape shape1)
    {
        this.MethodInjected3 = shape1.Name;
    }

    [HttpGet]
    [Route("constructorinjection")]
    public string constructorinjection()
    {
        return "Constructor Injected: " + this.ConstructorInjected;
    }

    [HttpGet]
    [Route("GetNoShape")]
    public string GetNoShape()
    {
        return "Property Injected: " + this.NoShape.Name;
    }

    [HttpGet]
    [Route("GetShapeCircle")]
    public string GetShapeCircle()
    {
        return "Property Injected: " + this.ShapeCircle.Name;
    }

    [HttpGet]
    [Route("GetShapeRectangle")]
    public string GetShapeRectangle()
    {
        return "Property Injected: " + this.ShapeRectangle.Name;
    }

    [HttpGet]
    [Route("GetPiValue")]
    public string GetPiValue()
    {
        return "Property Injected: " + this.PiValue;
    }

    [HttpGet]
    [Route("MethodInjected1")]
    public string InjectionMethod1()
    {
        return "Method Injected: " + this.MethodInjected1;
    }

    [HttpGet]
    [Route("MethodInjected2")]
    public string InjectionMethod2()
    {
        return "Method Injected: " + this.MethodInjected2;
    }

    [HttpGet]
    [Route("MethodInjected3")]
    public string InjectionMethod3()
    {
        return "Method Injected: " + this.MethodInjected3;
    }
}

In DIV2Controller.cs everything will be injected from the Dependency Configuration Resolver class

[RoutePrefix("api/v2/DIExample")]
public class DIV2Controller : ApiController
{
    private string ConstructorInjected;
    private string MethodInjected1;
    private string MethodInjected2;
    public string MyPropertyName { get; set; }
    public double PiValue1 { get; set; }
    public double PiValue2 { get; set; }
    public IShape Shape { get; set; }

    // MethodInjected
    [NonAction]
    public void Initialize()
    {
        this.MethodInjected1 = "Default Initialize done";
    }

    // MethodInjected
    [NonAction]
    public void Initialize2(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
    {
        this.MethodInjected2 = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
    }

    public DIV2Controller(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
    {
        this.ConstructorInjected = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
    }

    [HttpGet]
    [Route("constructorinjection")]
    public string constructorinjection()
    {
        return "Constructor Injected: " + this.ConstructorInjected;
    }

    [HttpGet]
    [Route("PropertyInjected")]
    public string InjectionProperty()
    {
        return "Property Injected: " + this.MyPropertyName;
    }

    [HttpGet]
    [Route("GetPiValue1")]
    public string GetPiValue1()
    {
        return "Property Injected: " + this.PiValue1;
    }

    [HttpGet]
    [Route("GetPiValue2")]
    public string GetPiValue2()
    {
        return "Property Injected: " + this.PiValue2;
    }

    [HttpGet]
    [Route("GetShape")]
    public string GetShape()
    {
        return "Property Injected: " + this.Shape.Name;
    }

    [HttpGet]
    [Route("MethodInjected1")]
    public string InjectionMethod1()
    {
        return "Method Injected: " + this.MethodInjected1;
    }

    [HttpGet]
    [Route("MethodInjected2")]
    public string InjectionMethod2()
    {
        return "Method Injected: " + this.MethodInjected2;
    }
}

Configuring the Dependency Resolver

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    RegisterInterfaces(container);
    config.DependencyResolver = new UnityResolver(container);

    // Other Web API configuration not shown.
}

private static void RegisterInterfaces(UnityContainer container)
{
    var dbContext = new SchoolDbContext();
    // Registration with constructor injection
    container.RegisterType<IStudentRepository, StudentRepository>(new InjectionConstructor(dbContext));
    container.RegisterType<ICourseRepository, CourseRepository>(new InjectionConstructor(dbContext));

    // Set constant/default value of Pi = 3.141 
    container.RegisterInstance<double>("PiValueExample1", 3.141);
    container.RegisterInstance<double>("PiValueExample2", 3.14);

    // without a name
    container.RegisterInstance<IShape>(new NoShape());

    // with circle name
    container.RegisterType<IShape, Circle>("Circle", new InjectionProperty("Name", "I am Circle"));

    // with rectangle name
    container.RegisterType<IShape, Rectangle>("Rectangle", new InjectionConstructor("I am Rectangle"));

    // Complex type like Constructor, Property and method injection
    container.RegisterType<DIV2Controller, DIV2Controller>(
        new InjectionConstructor("Constructor Value1", container.Resolve<IShape>("Circle"), "Constructor Value2", container.Resolve<IShape>()),
        new InjectionMethod("Initialize"),
        new InjectionMethod("Initialize2", "Value1", container.Resolve<IShape>("Circle"), "Value2", container.Resolve<IShape>()),
        new InjectionProperty("MyPropertyName", "Property Value"),
        new InjectionProperty("PiValue1", container.Resolve<double>("PiValueExample1")),
        new InjectionProperty("Shape", container.Resolve<IShape>("Rectangle")),
        new InjectionProperty("PiValue2", container.Resolve<double>("PiValueExample2")));
}

do-while loop in R

Pretty self explanatory.

repeat{
  statements...
  if(condition){
    break
  }
}

Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.

Android Button setOnClickListener Design

Implement OnClickListener() on your Activity...

public class MyActivity extends Activity implements View.OnClickListener {
}

For each button use...

buttonX.setOnClickListener(this);

In your Activity onClick() method test for which button it is...

@Override
public void onClick(View view) {
    if (View.equals(buttonX))
        // Do something
}

Also in onClick you could use view.getId() to get the resource ID and then use that in a switch/case block to identify each button and perform the relevant action.

Change background color of selected item on a ListView

You can keep track the position of the current selected element:

    OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
                mSelectedItem = position;
                mAdapter.notifyDataSetChanged();
        }
    };

And override the getView method of your adapter:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.item_list, null);

        if (position == mSelectedItem) {
            // set your color
        }

        return view;
    }

For me it did the trick.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

async is used for binding to Observables and Promises, but it seems like you're binding to a regular object. You can just remove both async keywords and it should probably work.

Android Studio: Default project directory

This may be what you want. Settings -> Appearance & Behavior -> System Settings > Project Opening > Default Directory

  1. Open 'Preferences'
  2. Select System Settings -> Project Opening
  3. Set 'Default Directory' where you want.

It worked for me. I tried Android Studio 3.5.

Make iframe automatically adjust height according to the contents without using scrollbar?

This works for me (also with multiple iframes on one page):

$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});

How to go from one page to another page using javascript?

Easier method is window.location.href = "http://example.com/new_url";

But what if you want to check if username and password whether empty or not using JavaScript and send it to the php to check whether user in the database. You can do this easily following this code.

html form -

<form name="myForm" onsubmit="return validateForm()" method="POST" action="login.php" >         
    <input type="text" name="username" id="username" />
    <input type="password" name="password" id="password" />
    <input type="submit" name="submitBt"value="LogIn" />
</form>

javascript validation-

function validateForm(){
    var uname = document.forms["myForm"]["username"].value;
    var pass = document.forms["myForm"]["password"].value;

    if((!isEmpty(uname, "Log In")) && (!isEmpty(pass, "Password"))){

        return true;
    }else{
        return false;
    }
}

function isEmpty(elemValue, field){
    if((elemValue == "") || (elemValue == null)){
        alert("you can not have "+field+" field empty");
        return true;
    }else{
        return false;
    }
}

check if user in the database using php

<?php
    $con = mysqli_connect("localhost","root","1234","users");

    if(mysqli_connect_errno()){
        echo "Couldn't connect ".mysqli_connect_error();
    }else{
        //echo "connection successful <br />";
    }

    $uname_tb = $_POST['username'];
    $pass_tb = $_POST['password'];

    $query ="SELECT * FROM user";
    $result = mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)){
        if(($row['username'] == $uname_tb) && ($row['password'] == $pass_tb)){
            echo "Login Successful";
            header('Location: dashbord.php');
            exit();
        }else{
            echo "You are not in our database".mysqli_connect_error();
        }
    }
    mysqli_close($con);
?>

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

Send POST request using NSURLSession

Teja Kumar Bethina's code changed for Swift 3:

    let urlStr = "http://url_to_manage_post_requests"
    let url = URL(string: urlStr)

    var request: URLRequest = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue("application/json", forHTTPHeaderField:"Content-Type")
    request.timeoutInterval = 60.0

    //additional headers
    request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")

    let bodyStr = "string or data to add to body of request"
    let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) -> Void in

        if let httpResponse = response as? HTTPURLResponse {
            print("responseCode \(httpResponse.statusCode)")
        }

        if error != nil {

            // You can handle error response here
            print("\(error)")
        } else {
            //Converting response to collection formate (array or dictionary)
            do {
                let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
                    JSONSerialization.ReadingOptions.mutableContainers))

                //success code
            } catch {
                //failure code
            }
        }
    }

    task.resume()

How do I get logs/details of ansible-playbook module executions?

Ansible command-line help, such as ansible-playbook --help shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.

Filter multiple values on a string column in dplyr

 by_type_year_tag_filtered <- by_type_year_tag %>%
      dplyr:: filter(tag_name %in% c("dplyr", "ggplot2"))

Remove all values within one list from another list?

If you don't have repeated values, you could use set difference.

x = set(range(10))
y = x - set([2, 3, 7])
# y = set([0, 1, 4, 5, 6, 8, 9])

and then convert back to list, if needed.

What's the difference between an argument and a parameter?

A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.

public void MyMethod(string myParam) { }

...

string myArg1 = "this is my argument";
myClass.MyMethod(myArg1);

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

You've added EF to a class library project. You also need to add it to the project that references it (your console app, website or whatever).

intl extension: installing php_intl.dll

  1. Under php extensions in your wampserver, ensure intl is checked
  2. check your extension_dir in your php/v7.0/php file ensure the directory is not commented and it is accurate
  3. (Dont know if this contributed but i did all three)In your extension list in the same file as 2 above, include the intl file in the same format as the rest(if it is not included). All the best

How do you import an Eclipse project into Android Studio now?

Android Studio has been improved since this question was posted, and the latest versions of Android Studio (as of this writing, we are at 2.1.1) have fairly good Eclipse importing capabilities, so importing Eclipse projects directly into Android Studio is now the best approach for migrating projects from Eclipse into Android Studio.

I will describe how to do this below, including a few of the pitfalls that one might encounter. I will deal in particular with importing an Eclipse workspace that contains multiple apps sharing one or more project libraries (the approaches posted thus far seem limited to importing just one Eclipse app project and its project libraries). While I don't deal with every possible issue, I do go into a lot of detail regarding some of them, which I hope will be helpful to those going through this process for the first time themselves.

I recently imported the projects from an Eclipse workspace. This workspace included four library projects that were shared between up to nine projects each.

Some background:

An Eclipse workspace contains multiple projects, which may be library projects or apps.

An Android Studio project is analogous to an Eclipse workspace, in that it can contain both library projects and apps. However, a library project or an app is represented by a "module" in Android Studio, whereas it is represented by a "project" in Eclipse.

So, to summarize: Eclipse workspaces will end up as Android Studio projects, and Eclipse projects inside a workspace will end up as Android Studio modules inside a project.

You should start the import process by creating an Android Studio project (File / New / New Project). You might give this project the same (or similar) name as you gave your Eclipse workspace. This project will eventually hold all of your modules, one each for each Eclipse project (including project libraries) that you will import.

The import process does not change your original Eclipse files, so long as you place the imported files in a different folder hierarchy, so you should choose a folder for this project that is not in your original Eclipse hierarchy. For example, if your Eclipse projects are all in a folder called Android, you might create a sibling folder called AStudio.

Your Android Studio project can then be created as a sub-folder of this new folder. The New Project wizard will prompt you to enter this top-level project folder, into which it will create your project.

Android Studio's new project wizard will then ask you to configure a single module at the time you create the project. This can be a little confusing at first, because they never actually tell you that you are creating a module, but you are; you are creating a project with a single module in it. Apparently, every project is required to have at least one module, so, since you are relying on Eclipse to provide your modules, your initial module will be a placeholder to vacuously satisfy that formal requirement.

Thus, you probably will want to create an initial module for your project that does as little as possible. Therefore, select Phone and Tablet as the type of your module, accept the default minimum SDK (API level 8), and select Add No Activity for your module.

Next, select one of the Eclipse app projects in your workspace that requires the largest number of libraries as your first project to import. The advantage of doing this is that when you import that project, all the library projects that it uses (directly, or indirectly, if some of your library projects themselves require other library projects) will get imported along with it as part of the importing process.

Each of these imported projects will get its own module within your Android Studio project. All of these modules will be siblings of one another (both in your project hierarchy, and in the folder hierarchy where their files are placed), just as if you had imported the modules separately. However, the dependencies between the modules will be created for you (in your app's build.gradle files) as part of the importing process.

Note that after you finish importing, testing and debugging this "most dependent" Eclipse project and its supporting library projects, you will go on to import a second Eclipse app project (if you have a second one in your workspace) and its library project modules (with those imported earlier getting found by the import wizard as existing modules and re-used for this new module, rather than being duplicated).

So, you should never have to import even a single library project from Eclipse directly; they will all be brought in indirectly, based on their dependencies upon app projects that you import. This is assuming that all of your library projects in the workspace are created to serve the needs of one or more app projects in that same workspace.

To perform the import of this first app project, back in Android Studio, while you are in the project that you just created, select File / New / New Module. You might think that you should be using File / New / Import Module, but no, you should not, because if you do that, Android Studio will create a new project to hold your imported module, and it will import your module to that project. You actually could create your first module that way, but then the second through Nth modules would still require that you use this other method (for importing a module into an existing project), and so I think that just starting with an "empty" project (or rather, one with its own vacuous, do-nothing placeholder module), and then importing each of your Eclipse projects as a new module into that project (i.e., the approach we are taking here), may be less confusing.

So, you are going to take your practically-empty new project, and perform a File / New / New Module in it. The wizard that this invokes will give you a choice of what kind of module you want to create. You must select "Import Eclipse ADT Project." That is what accesses the wizard that knows how to convert an Eclipse project into an Android Studio module (along with the library modules on which it depends) within your current Android Studio project.

When prompted for a source folder, you should enter the folder for your Eclipse project (this is the folder that contains that project's AndroidManifest.xml file).

The import wizard will then display the module name that it intends to create (similar to your original Eclipse project's name, but with a lower-case first letter because that is a convention that distinguishes module names from project names (which start with an upper-case letter). It usually works pretty well to accept this default.

Below the module name is a section titled "Additional required modules." This will list every library required by the module you are importing (or by any of its libraries, etc.). Since this is the first module you are importing, none of these will already be in your project, so each of them will have its Import box checked by default. You should leave these checked because you need these modules. (Note that when you import later Eclipse app projects, if a library that they need has already been imported, those libraries will still appear here, but there will be a note that "Project already contains module with this name," and the Import box will be un-checked by default. In that case, you should leave the box unchecked, so that the importer will hook up your newly-imported module(s) to the libraries that have already been imported. It may be that accepting the default names that Android Studio creates for your modules will be important for allowing the IDE to find and re-use these library modules.

Next, the importer will offer to replace any jars and library sources with Gradle dependencies, and to create camelCase module names for any dependent modules, checking all those options by default. You should generally leave these options checked and continue. Read the warning, though, about possible problems. Remember that you can always delete an imported module or modules (via the Project Structure dialog) and start the import process over again.

The next display that I got (YMMV) claims that the Android Support Repository is not installed in my SDK installation. It provides a button to open the Android SDK Manager for purposes of installing it. However, that button did not work for me. I manually opened the SDK manager as a separate app, and found that the Android Support Repository was already installed. There was an update, however. I installed that, and tapped the Refresh button in the import dialog, but that did nothing. So, I proceeded, and the perceived lack of this Repository did not seem to hurt the importing process (although I did get messages regarding it being missing from time to time later on, while working with the imported code, which I was able to appease by clicking a supplied link that corrected the problem - at least temporarily). Eventually this problem went away when I installed an update to the repository, so you may not experience it at all.

At this point, you will click Finish, and after a bit it should create your modules and build them. If all goes well, you should get a BUILD SUCCESSFUL message in your Gradle Console.

One quirk is that if the build fails, you may not see your imported modules in the Project hierarchy. It seems that you need to get to the first valid build before the new modules will appear there (my experience, anyway). You may still be able to see the new modules in the File / Project Structure dialog (e.g., if you want to delete them and start your import over).

Remember that since you are not changing your original Eclipse projects, you can always delete the modules that you have just imported (if importing goes badly), and start all over again. You can even make changes to the Eclipse side after deleting your Android Studio modules, if that will make importing go better the second time (so long as you preserve your fallback ability to build your existing source under Eclipse). As you'll see when we discuss version control below, it may be necessary for you to retain your ability to build under Eclipse, because the project structure is changed under Android Studio, so if you need to go back to a commit that precedes your move to Android Studio (e.g., to make a bug fix), you will want to have the ability to build that earlier commit in Eclipse.

To delete a module, you must select File / Project Structure, then select the module from the left side of the dialog, and then hit the delete key. For some reason, I was not able to delete a module directly in the Project hierarchy; it had to be done using this Project Structure dialog.

The import wizard generates an import-summary.txt file containing a detailed list of any issues it may have encountered, along with actions taken to resolve them. You should read it carefully, as it may provide clues as to what is happening if you have trouble building or running the imported code. It will also help you to find things that the importer moves around to accommodate the different structure of Android Studio projects.

If all does not go well, then have at look at these possible problems that you may encounter, along with solutions for those problems:

Generally speaking, there are two main kinds of problems that I encountered:

  1. Proguard problems
  2. Manifest problems

When Proguard is messed up, the (obfuscated) names of methods in your libraries may not match the names being used to invoke them from your app, and you will get compiler errors like "error: cannot find symbol class ..."

In Eclipse, Proguard stuff is pretty much ignored for library projects, with the Proguard stuff for any app project that you are building determining the obfuscation, etc. for not just itself, but for processing all of the libraries on which it depends. And that is generally what you want.

In Android Studio, however, you need to make some changes to attain this same effect. Basically, in the build.gradle files for each of your library project modules, you will want something like this:

buildTypes {
    release {
        minifyEnabled false
        consumerProguardFiles 'proguard.cfg'
    }
}

Where proguard.cfg is your library module's own proguard configuration file.

The term "consumer" in "consumerProguardFiles" apparently refers to the app module that is using this library module. So the proguard commands from that app are used in preference to those of the library module itself, and apparently this results in obfuscations that are coordinated and compatible, so that all calls from the app module to its library modules are made with matching symbols.

These "consumerProguardFiles" entries are not created automatically during the import process (at least that was my own experience) so you will want to make sure to edit that into your library modules' build.gradle files if they are not created for you during importing.

If you wanted to distribute your library projects separately, with obfuscation, then you would need an individual proguard file for them; I have not done this myself, and so that is beyond the scope of this answer.

In the app module, you will want something like this:

buildTypes {
    release {
        minifyEnabled true
        proguardFiles 'proguard.cfg'
    }
}

(BTW, as of this writing, while my apps are running just fine, I have not yet directly confirmed that things are actually getting obfuscated using this approach, so do check this yourself - e.g., by using a decompiler like apktool. I will be checking this later on, and will edit this answer when I get that info).

The second kind of problem is due to the fact that Eclipse pretty much ignores the manifest files for library projects when compiling an app project that uses those library projects, while in Android Studio, there is an interleaving of the two that apparently does not consistently prioritize the app's manifest over those of its libraries.

I encountered this because I had a library manifest that listed (just for documentation purposes) an abstract Activity class as the main activity. There was a class derived from this abstract class in my app that was declared in the manifest of each app that used the library.

In Eclipse, this never caused any problems, because the library manifests were ignored. But in Android Studio, I ended up with that abstract class as my activity class for the app, which caused a run-time error when the code made an attempt to instantiate that abstract class.

You have two choices in this case:

  1. Use tools syntax to override specific library manifest stuff in your app manifest - for example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.goalstate.WordGames.FullBoard.trialsuite"
       xmlns:tools="http://schemas.android.com/tools"
       .
       .
        <application
           tools:replace="android:name"

or,

  1. Strip out practically everything from your library modules' manifests, and rely upon the app module's manifest to provide every value. Note that you do need to have a manifest for each library module, but not much more is required than the header and a bare manifest element with just a package attribute in it.

I tried both and ended up with approach 2., above, as the simpler method. However, if you wanted to distribute your library modules separately, you would need to create a more meaningful manifest file that reflects each library module's own individual requirements.

There is probably a more "correct" way to do this which puts requirements (e.g., permissions) for each library in the library manifest itself, and allows the automatic interleaving process to combine these with those declared for the app. However, given that Eclipse ignores the manifests for libraries, it seems safer at least initially to rely entirely on the app manifests and just strip the library manifests down to the bare bones.

Be aware that some of the project properties, and also the manifest attributes, from your Eclipse project will have been used to construct portions of your build.gradle files. Specifically, your compileSdkVersion in build.gradle is set to the project build version from the Eclipse project properties, applicationId is the package name from your app's manifest, and minSdkVersion and targetSdkVersion are also copied from the app's manifest file. The dependencies section of build.gradle comes from the library project dependencies in your project's properties.

Note that this may make some of your AndroidManifest.xml values redundant and quite possibly residual (i.e., unused). This could create confusion. My understanding is that the build.gradle values are the ones that actually have an effect, and that the manifest values like targetSdkVersion are not used any more for purposes of building. However, they may still be used by app stores such as Google Play; I don't know for certain one way or the other, so at this point I am just maintaining them in tandem.

Besides the above two kinds of issue, there are more routine things like importing a project that has a project build level of 22 when you have only installed SDK level 23 in Android Studio. In that situation, it is probably better to edit your app module's build.gradle file to move compileSdkVersion from 22 (the imported value) to 23, than it would be to install the SDK for level 22, but either approach should work.

Throughout this entire process, when something does not build properly and you make a change to try to address it, you might want to try Build / Rebuild Project and/or Tools / Android / Sync Project with Gradle Files, and/or File / Invalidate Caches/Restart, to make sure that your changes have been fully incorporated. I don't know exactly when these are truly necessary, because I don't know how much is done incrementally when you haven't yet had a successful build, but I performed them all fairly regularly as a kind of superstitious ritual, and I'm fairly certain that it helped. For example, when I got a Resources$NotFound runtime error that appeared to be from an inability to find the launch icon resource, I tried all three, and the problem was fixed.

When you have performed the above for your first Eclipse project and have attained a successful build, then with luck, you can select your app module from the dropdown at the top of the Android Studio display to the left of the play button, then click the play button itself, then select a device or Android Virtual Device, and the app should be loaded for running.

Likewise, you should be able to create a signed copy of your app using the Build / Generate Signed APK feature. Note that some import-related errors may appear when running your signed copy that do not appear when using the play button, so you need to confirm that both are working before deciding that your import is complete.

Following this, you will probably want to turn on version control. I am using git myself, but there are a number of other options available.

Version control is mostly beyond the scope of this answer, but there are a few things that are affected by the importing process. First, in Eclipse you might have your various projects in various folders stuck all over the place, but when you import into Android Studio, all modules will be created as direct child folders of your main project folder. So if you had a separate git folder for each project in Eclipse, or for related groups of projects organized under a parent folder for each group (as I did), that is not going to translate very well to Android Studio.

My knowledge of this is limited as I have not worked with version control yet in Android Studio, so maybe there is a way around this, but it appears that all version control in Android Studio is unified at the project level, and so all of your modules will be under a single git archive.

This means that you may need to abandon your old git archive and start fresh with a new archive for your imported source code. And that means that you will want to keep your old git archive around, so that it can be used with Eclipse to perform any needed bug fixes, etc., at least for a while. And you also will want it to preserve a history of your project.

If you are fortunate enough to have had all of your projects organized under a single Eclipse workspace, and if you were using a single git archive for those projects, then it is possible that you might just copy your old git archive from in and under your Eclipse workspace folder to in and under your Android Studio project folder. Then, you could edit any still-relevant .gitignore items from you Eclipse project into the auto-generated .gitignore file for your Android Studio project, and let git figure out what has been changed during the importing process (and some things will have been moved around - for example, the manifest file is no longer at the top level of your module). Others have reported that git is pretty good at figuring out what has changed; I have not tried this myself.

But even if you did this, going back to a commit that precedes your move from Eclipse to Android Studio would be going back to a set of files that would only make sense from inside Eclipse. So it sounds, well, "difficult" to work with. Especially since Eclipse will still be pointing to its original set of project folders.

I personally had multiple git archives for my various sets of related projects, and so I decided to just make a clean break and start git over again in Android Studio. If you had to do this, it could affect your planning, because you would want to be at a very stable point in your code development before making the move in that case, since you will lose some accessibility to that older code within your version control system (e.g., ability to merge with post-import code) once you have made the move to Android Studio.

The part of this answer that pertains to git is partly speculative, since I have not actually worked with version control yet on my imported project files, but I wanted to include it to give some idea of the challenges, and I plan to update my answer after I have worked more with version control inside Android Studio.

How to POST JSON request using Apache HttpClient?

As mentioned in the excellent answer by janoside, you need to construct the JSON string and set it as a StringEntity.

To construct the JSON string, you can use any library or method you are comfortable with. Jackson library is one easy example:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "value"); // repeat as needed
String JSON_STRING = node.toString();
postMethod.setEntity(new StringEntity(JSON_STRING, ContentType.APPLICATION_JSON));

Hot deploy on JBoss - how do I make JBoss "see" the change?

In case you are working with the Eclipse IDE there is a free plugin Manik-Hotdeploy.

This plugin allows you to connect your eclipse workspace with your wildfly deployment folder. After a maven build your artifact (e.g. war or ear) will be automatically pushed into the deployment folder of your server. Also web content files (e.g. .xhtml .jsf ...) will be hot deployed.

The plugin runs for wildfly, glassfish and payara.

Read the section JBoss/Wildfly Support for more details.

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

In swift 5.3 and Inspired by @ravron answer:

extension UIButton {
    /// Fits the image and text content with a given spacing
    /// - Parameters:
    ///   - spacing: Spacing between the Image and the text
    ///   - contentXInset: The spacing between the view to the left image and the right text to the view
    func setHorizontalMargins(imageTextSpacing: CGFloat, contentXInset: CGFloat = 0) {
        let imageTextSpacing = imageTextSpacing / 2
        
        contentEdgeInsets = UIEdgeInsets(top: 0, left: (imageTextSpacing + contentXInset), bottom: 0, right: (imageTextSpacing + contentXInset))
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -imageTextSpacing, bottom: 0, right: imageTextSpacing)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: imageTextSpacing, bottom: 0, right: -imageTextSpacing)
    }
}

It adds an extra horizontal margin from the View to the Image and from the Label to the View

Using JavaScript to display a Blob

If you want to use fetch instead:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

How to negate 'isblank' function

If you're trying to just count how many of your cells in a range are not blank try this:

=COUNTA(range)

Example: (assume that it starts from A1 downwards):

---------    
Something 
---------
Something
---------

---------
Something
---------

---------
Something
---------

=COUNTA(A1:A6) returns 4 since there are two blank cells in there.

jQuery to remove an option from drop down list, given option's text/value

Once you have localized the dropdown element

dropdownElement = $("#dropdownElement");

Find the <option> element using the JQuery attribute selector

dropdownElement.find('option[value=foo]').remove();

Passing on command line arguments to runnable JAR

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me this setting was working.
In my windows 8.1 the path for php7 is

C:\user\test\tools\php7\php.exe

settings.json

 {  
 "php.executablePath":"/user/test/tools/php7/php.exe",
 "php.validate.executablePath": "/user/test/tools/php7/php.exe"
 }

see also https://github.com/microsoft/vscode/issues/533

ActiveXObject creation error " Automation server can't create object"

Well you can not run code from notepad so that means you are opening up the page from the file system. aka c:/foo/bar/hello.html

When you run the code from the asp.net page, you are running it from localhost. aka http://loalhost:1234/assdf.html

Each of these run in different security zones on IE.

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

If you use shared modules, just add RouterModule to a Module where your component is declared and don't forget to add <router-outlet></router-outlet>

Referenced from here RouterLink does not work

Git: How configure KDiff3 as merge tool and diff tool

Well, the problem is that Git can't find KDiff3 in the %PATH%.

In a typical Unix installation all executables reside in several well-known locations (/bin/, /usr/bin/, /usr/local/bin/, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe :) ).

In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3 in a cmd session and get KDiff3 running.

The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)

The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

Add a pipe separator after items in an unordered list unless that item is the last on a line

You can use the following CSS to solve.

ul li { float: left; }
ul li:before { content: "|"; padding: 0 .5em; }
ul li:first-child:before { content: ""; padding: 0; }

Should work on IE8+ as well.

How can I increase the size of a bootstrap button?

Use block level buttons, those that span the full width of a parent You can achieve this by adding btn-block class your button element.

Documentation here

sql server convert date to string MM/DD/YYYY

That task should be done by the next layer up in your software stack. SQL is a data repository, not a presentation system

You can do it with

CONVERT(VARCHAR(10), fmdate(), 101)

But you shouldn't

PHP - If variable is not empty, echo some html code

i hope this will work too, try using"is_null"

<?php 
$web = the_field('website');
if (!is_null($web)) {
?>

....html code here

<?php
} else { 
    echo "Niente";
}
?>

http://php.net/manual/en/function.is-null.php

hope that suits you..

Parsing JSON Array within JSON Object

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

 String jsonText = readAll(inputofyourjsonstream);
 JSONObject json = new JSONObject(jsonText);
 JSONArray arr = json.getJSONArray("sources");

Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

arr.getJSONObject(index)

to get the objects inside of the array.

getDate with Jquery Datepicker

try

$('#page_output').html(str_output);

Counting unique values in a column in pandas dataframe like in Qlik?

If I assume data is the name of your dataframe, you can do :

data['race'].value_counts()

this will show you the distinct element and their number of occurence.

Efficiently updating database using SQLAlchemy ORM

If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.

If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

How print out the contents of a HashMap<String, String> in ascending order based on its values?

The simplest solution would be to use a sorted map like TreeMap instead of HashMap. If you do not have control over the map construction, then the minimal solution would be to construct a sorted set of keys. You don't really need a new map.

Set<String> sortedKeys = new TreeSet<String>();
sortedKeys.addAll(codes.keySet());

for(String key: sortedKeys){
    println(key  + ":" + codes.get(key));
}

How to get all options of a select using jQuery?

If you're looking for all options with some selected text then the below code will work.

$('#test').find("select option:contains('B')").filter(":selected");

Full examples of using pySerial package

import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

use https://pythonhosted.org/pyserial/ for more examples

How to set radio button selected value using jquery

for multiple dropdowns

$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");

here RBLExperienceApplicable is the matching part of the radio button groups input tag ids. and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable

Aligning a float:left div to center?

use display:inline-block; instead of float

you can't centre floats, but inline-blocks centre as if they were text, so on the outer overall container of your "row" - you would set text-align: center; then for each image/caption container (it's those which would be inline-block;) you can re-align the text to left if you require

Export to csv in jQuery

By using just jQuery, you cannot avoid a server call.

However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.

To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.

Get index of selected option with jQuery

try this

 alert(document.getElementById("dropDownMenuKategorie").selectedIndex);

Parsing JSON from URL

A simple alternative solution:

  • Paste the URL into a json to csv converter

  • Open the CSV file in either Excel or Open Office

  • Use the spreadsheet tools to parse the data

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

Same as the other answers (disabled isn't sent to the server, readonly is) but some browsers prevent highlighting of a disabled form, while read-only can still be highlighted (and copied).

http://www.w3schools.com/tags/att_input_disabled.asp

http://www.w3schools.com/tags/att_input_readonly.asp

A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

You appear to have no main function, which is supposed to be the entry-point for your program.

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

The compiler is already telling you, it's not value but variable. You are looking for -Wno-unused-variable. Also, try g++ --help=warnings to see a list of available options.

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

The issue is in your registration app. It seems django-registration calls get_user_module() in models.py at a module level (when models are still being loaded by the application registration process). This will no longer work:

try:
    from django.contrib.auth import get_user_model
    User = get_user_model()
except ImportError:
    from django.contrib.auth.models import User    

I'd change this models file to only call get_user_model() inside methods (and not at module level) and in FKs use something like:

user = ForeignKey(settings.AUTH_USER_MODEL)

BTW, the call to django.setup() shouldn't be required in your manage.py file, it's called for you in execute_from_command_line. (source)

What is difference between Axios and Fetch?

They are HTTP request libraries...

I end up with the same doubt but the table in this post makes me go with isomorphic-fetch. Which is fetch but works with NodeJS.

http://andrewhfarmer.com/ajax-libraries/


The link above is dead The same table is here: https://www.javascriptstuff.com/ajax-libraries/

Or here: enter image description here

Tomcat is web server or application server?

Application Server:

Application server maintains the application logic and
serves the web pages in response to user request.

That means application server can do both application logic maintanence and web page serving.

Web Server:

Web server just serves the web pages and it cannot enforce any application logic.

Final conclusion is: Application server also contains the web server.

For further Reference : http://www.javaworld.com/javaqa/2002-08/01-qa-0823-appvswebserver.html

Populating Spring @Value during Unit Test

Spring Boot do a lot of automatically things to us but when we use the annotation @SpringBootTest we think that everything will be automatically solved by Spring boot.

There are a lot of documentation, but the minimal is to choose one engine (@RunWith(SpringRunner.class)) and indicate the class that will be used create the context to load the configuration (resources/applicationl.properties).

In a simple way you need the engine and the context:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClassTest .class)
public class MyClassTest {

    @Value("${my.property}")
    private String myProperty;

    @Test
    public void checkMyProperty(){
        Assert.assertNotNull(my.property);
    }
}

Of course, if you look the Spring Boot documentation you will find thousands os ways to do that.

Could not resolve '...' from state ''

Had the same issue with Ionic routing.

Simple solution is to use the name of the state - basically state.go(state name)

.state('tab.search', {
    url: '/search',
    views: {
      'tab-search': {
        templateUrl: 'templates/search.html',
        controller: 'SearchCtrl'
      }
    }
  })

And in controller you can use $state.go('tab.search');

Jquery bind double click and single click separately

i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code

<p>Click on this paragraph.</p>
<b> </b>

script code

var dbclick=false;    
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}

},200)

}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false


},300)
});


its not much laggy

Toggle Checkboxes on/off

in my guess, the rightest man who suggested normal variant is GigolNet Gigolashvili, but i wanna suggest even more beautiful variant. Check it

$(document).on('click', '.fieldWrapper > label', function(event) {
    event.preventDefault()
    var n = $( event.target ).parent().find('input:checked').length
    var m = $( event.target ).parent().find('input').length
    x = n==m? false:true
    $( event.target ).parent().find('input').each(function (ind, el) {
        // $(el).attr('checked', 'checked');
        this.checked = x
    })
})

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

You probably can't. Here's something that comes close. You won't get content to flow around it if there's space below.

http://jsfiddle.net/ThnLk/1289

.stuck {
    position: fixed;
    top: 10px;
    left: 10px;
    bottom: 10px;
    width: 180px;
    overflow-y: scroll;
}

You can do a percentage height as well:

http://jsfiddle.net/ThnLk/1287/

.stuck {
    max-height: 100%;
}

Algorithm for solving Sudoku

Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.

  • Setup: for each square, have a set of flags for each number showing the allowed numbers.
  • Crossing out: just like when people on the train are solving it on paper, you can iteratively cross out known numbers. Any square left with just one number will trigger another crossing out. This will either result in solving the whole puzzle, or it will run out of triggers. This is where I stalled last time.
  • Permutations: there's only 9! = 362880 ways to arrange 9 numbers, easily precomputed on a modern system. All of the rows, columns, and 3x3 squares must be one of these permutations. Once you have a bunch of numbers in there, you can do what you did with the crossing out. For each row/column/3x3, you can cross out 1/9 of the 9! permutations if you have one number, 1/(8*9) if you have 2, and so forth.
  • Cross permutations: Now you have a bunch of rows and columns with sets of potential permutations. But there's another constraint: once you set a row, the columns and 3x3s are vastly reduced in what they might be. You can do a tree search from here to find a solution.

Hiding the R code in Rmarkdown/knit and just showing the results

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

Compile a DLL in C/C++, then call it from another program

Here is how you do it:

In .h

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

extern "C" // Only if you are using C++ rather than C
{    
  EXPORT int __stdcall add2(int num);
  EXPORT int __stdcall mult(int num1, int num2);
}

in .cpp

extern "C" // Only if you are using C++ rather than C
{    
EXPORT int __stdcall add2(int num)
{
  return num + 2;
}


EXPORT int __stdcall mult(int num1, int num2)
{
  int product;
  product = num1 * num2;
  return product;
}
}

The macro tells your module (i.e your .cpp files) that they are providing the dll stuff to the outside world. People who incude your .h file want to import the same functions, so they sell EXPORT as telling the linker to import. You need to add BUILD_DLL to the project compile options, and you might want to rename it to something obviously specific to your project (in case a dll uses your dll).

You might also need to create a .def file to rename the functions and de-obfuscate the names (C/C++ mangles those names). This blog entry might be an interesting launching off point about that.

Loading your own custom dlls is just like loading system dlls. Just ensure that the DLL is on your system path. C:\windows\ or the working dir of your application are an easy place to put your dll.

Which method performs better: .Any() vs .Count() > 0?

Since this is a rather popular topic and answers differ, I had to take a fresh look on the problem.

Testing env: EF 6.1.3, SQL Server, 300k records

Table model:

class TestTable
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }
}

Test code:

class Program
{
    static void Main()
    {
        using (var context = new TestContext())
        {
            context.Database.Log = Console.WriteLine;

            context.TestTables.Where(x => x.Surname.Contains("Surname")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname")).Count(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Count(x => x.Id > 1000);

            Console.ReadLine();
        }
    }
}

Results:

Any() ~ 3ms

Count() ~ 230ms for first query, ~ 400ms for second

Remarks:

For my case, EF didn't generate SQL like @Ben mentioned in his post.

How to change value of object which is inside an array using JavaScript or jQuery?

Try this code. it uses jQuery grep function

array = $.grep(array, function (a) {
    if (a.Id == id) {
        a.Value= newValue;
    }
    return a;
});

Auto expand a textarea using jQuery

You can set the textarea's height to its scrollHeight on all events that change its potential size:

function setTextareaResponsive(id) {
   adjustTextAreaHeight(id);

   $(window).on("resize", function() {
      adjustTextareaHeight(id);
   });

   $("#" + id).on("change input", function() {
      adjustTextareaHeight(id);
   });
}

function adjustTextareaHeight(id) {
   // set height to 1, so scrollHeight is related to linecount, not original textarea size
   $("#" + id).height(1);
   $("#" + id).height(document.getElementById(id).scrollHeight);
}

I personally like it better, when the height is not padded by the extra height (usually 12px) that scrollHeight provides. That's why I like to set the height to the number of lines multiplied by the lineHeight, in which case the function adjustTextareaHeight would look like this:

function adjustTextareaHeight(id) {
   var textarea = document.getElementById(id);

   // set height to 1, so scrollHeight is related to linecount, not original textarea size
   $("#" + id).height(1);
   var lineHeight = parseInt(getComputedStyle(textarea).lineHeight)
   var numberOfLines = Math.floor(textarea.scrollHeight / lineHeight)
   $("#" + id).height(lineHeight * numberOfLines);
}

How to append elements at the end of ArrayList in Java?

import java.util.*;


public class matrixcecil {
    public static void main(String args[]){
        List<Integer> k1=new ArrayList<Integer>(10);
        k1.add(23);
        k1.add(10);
        k1.add(20);
        k1.add(24);
        int i=0;
        while(k1.size()<10){
            if(i==(k1.get(k1.size()-1))){

            }
             i=k1.get(k1.size()-1);
             k1.add(30);
             i++;
             break;
        }
        System.out.println(k1);
    }

}

I think this example will help you for better solution.

Reload content in modal (twitter bootstrap)

Here is a coffeescript version that worked for me.

$(document).on 'hidden.bs.modal', (e) ->
  target = $(e.target)
  target.removeData('bs.modal').find(".modal-content").html('')

What is the best way to uninstall gems from a rails3 project?

With newer versions of bundler you can use the clean task:

$ bundle help clean
Usage:
    bundle clean

Options:
    [--dry-run=only print out changes, do not actually clean gems]
    [--force=forces clean even if --path is not set]
    [--no-color=Disable colorization in output]
    -V, [--verbose=Enable verbose output mode]

Cleans up unused gems in your bundler directory
$ bundle clean --dry-run --force
Would have removed actionmailer (3.1.12)
Would have removed actionmailer (3.2.0.rc2)
Would have removed actionpack (3.1.12)
Would have removed actionpack (3.2.0.rc2)
Would have removed activemodel (3.1.12)
...

edit:

This is not recommended if you're using a global gemset (i.e. - all of your projects keep their gems in the same place). There're few ways to keep each project's gems separate, though:

  1. rvm gemsets (http://rvm.io/gemsets/basics)
  2. bundle install with any of the following options: --deployment or --path=<path> (http://bundler.io/v1.3/man/bundle-install.1.html)

Display Bootstrap Modal using javascript onClick

I had the same problem, after researching a lot, I finally built a js function to create modals dynamically based on my requirements. Using this function, you can create popups in one line such as:

puyModal({title:'Test Title',heading:'Heading',message:'This is sample message.'})

Or you can use other complex functionality such as iframes, video popups, etc.

Find it on https://github.com/aybhalala/puymodals For demo, go to http://pateladitya.com/puymodals/

Open URL in new window with JavaScript

Just use window.open() function? The third parameter lets you specify window size.

Example

var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&amp;url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);

how to Call super constructor in Lombok

for superclasses with many members I would suggest you to use @Delegate

@Data
public class A {
    @Delegate public class AInner{
        private final int x;
        private final int y;
    }
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(A.AInner a, int z) {
        super(a);
        this.z = z;
    }
}

PHP - regex to allow letters and numbers only

  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i

How to delete shared preferences data from App in Android

Removing all preferences:

SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
settings.edit().clear().commit();

Removing single preference:

SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);
settings.edit().remove("KeyName").commit();

How to make <a href=""> link look like a button?

Tested with Chromium 40 and Firefox 36

<a href="url" style="text-decoration:none">
   <input type="button" value="click me!"/>
</a>

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I got this error, but mine was coming from the Toasts, not a Dialog.

I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.

I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

Android "elevation" not showing a shadow

In my case, this was caused by a custom parent component setting the rendering layer type to "Software":

setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Removing this line of did the trick. Or course you need to evaluate why this is there in the first place. In my case it was to support Honeycomb, which is well behind the current minimum SDK for my project.

Python and pip, list all versions of a package that's available?

My project luddite has this feature.

Example usage:

>>> import luddite
>>> luddite.get_versions_pypi("python-dateutil")
('0.1', '0.3', '0.4', '0.5', '1.0', '1.1', '1.2', '1.4', '1.4.1', '1.5', '2.0', '2.1', '2.2', '2.3', '2.4.0', '2.4.1', '2.4.2', '2.5.0', '2.5.1', '2.5.2', '2.5.3', '2.6.0', '2.6.1', '2.7.0', '2.7.1', '2.7.2', '2.7.3', '2.7.4', '2.7.5', '2.8.0')

It lists all versions of a package available, by querying the json API of https://pypi.org/

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

Why dict.get(key) instead of dict[key]?

One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:

print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'

Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.

So instead of doing this (or something similar):

score = None
try:
    score = dictionary["score"]
except KeyError:
    score = 0

We can do this:

score = dictionary.get("score", 0)
# score = 0

How to extract numbers from a string and get an array of ints?

If you want to exclude numbers that are contained within words, such as bar1 or aa1bb, then add word boundaries \b to any of the regex based answers. For example:

Pattern p = Pattern.compile("\\b-?\\d+\\b");
Matcher m = p.matcher("9There 9are more9 th9an -2 and less than 12 numbers here9");
while (m.find()) {
  System.out.println(m.group());
}

displays:

2
12

Is there an onSelect event or equivalent for HTML <select>?

I had the same problem when I was creating a design a few months back. The solution I found was to use .live("change", function()) in combination with .blur() on the element you are using.

If you wish to have it do something when the user simply clicks, instead of changing, just replace change with click.

I assigned my dropdown an ID, selected, and used the following:

$(function () {
    $("#selected").live("change", function () {

    // do whatever you need to do

    // you want the element to lose focus immediately
    // this is key to get this working.
    $('#selected').blur();
    });
});

I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.

http://api.jquery.com/live/

Edit: Use the on selector as opposed to .live. See jQuery .on()

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

How do you round to 1 decimal place in Javascript?

I found a way to avoid the precision problems:

function badRound (num, precision) {
    const x = 10 ** precision;
    return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1

function round (num, precision) {
    const x = 10 ** (precision + 1);
    const y = 10 ** precision;
    return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01

How to filter a RecyclerView with a SearchView

This is my take on expanding @klimat answer to not losing filtering animation.

public void filter(String query){
    int completeListIndex = 0;
    int filteredListIndex = 0;
    while (completeListIndex < completeList.size()){
        Movie item = completeList.get(completeListIndex);
        if(item.getName().toLowerCase().contains(query)){
            if(filteredListIndex < filteredList.size()) {
                Movie filter = filteredList.get(filteredListIndex);
                if (!item.getName().equals(filter.getName())) {
                    filteredList.add(filteredListIndex, item);
                    notifyItemInserted(filteredListIndex);
                }
            }else{
                filteredList.add(filteredListIndex, item);
                notifyItemInserted(filteredListIndex);
            }
            filteredListIndex++;
        }
        else if(filteredListIndex < filteredList.size()){
            Movie filter = filteredList.get(filteredListIndex);
            if (item.getName().equals(filter.getName())) {
                filteredList.remove(filteredListIndex);
                notifyItemRemoved(filteredListIndex);
            }
        }
        completeListIndex++;
    }
}

Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.

UITextField border color

To simplify this actions from accepted answer, you can also create Category for UIView (since this works for all subclasses of UIView, not only for textfields:

UIView+Additions.h:

#import <Foundation/Foundation.h>

@interface UIView (Additions)
- (void)setBorderForColor:(UIColor *)color 
                    width:(float)width 
                   radius:(float)radius;
@end

UIView+Additions.m:

#import "UIView+Additions.h"

@implementation UIView (Additions)

- (void)setBorderForColor:(UIColor *)color 
                    width:(float)width
                   radius:(float)radius
{
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = YES;
    self.layer.borderColor = [color CGColor];
    self.layer.borderWidth = width;
}

@end

Usage:

#import "UIView+Additions.h"
//...
[textField setBorderForColor:[UIColor redColor]
                       width:1.0f
                      radius:8.0f];

Unzip All Files In A Directory

To unzip all files in a directory just type this cmd in terminal:

unzip '*.zip'

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

Git update submodules recursively

In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:

git submodule update --recursive --remote --merge

You may add --init to initialize any uninitialized submodules and use --rebase if you want to rebase instead of merge.

You need to commit the changes afterwards:

git add . && git commit -m 'Update submodules to latest revisions'

how to define ssh private key for servers fetched by dynamic inventory in files

The best solution I could find for this problem is to specify private key file in ansible.cfg (I usually keep it in the same folder as a playbook):

[defaults]
inventory=ec2.py
vault_password_file = ~/.vault_pass.txt
host_key_checking = False
private_key_file = /Users/eric/.ssh/secret_key_rsa

Though, it still sets private key globally for all hosts in playbook.

Note: You have to specify full path to the key file - ~user/.ssh/some_key_rsa silently ignored.

Time in milliseconds in C

The standard C library provides timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep.

Android - Handle "Enter" in an EditText

This works fine on LG Android phones. It prevents ENTER and other special characters to be interpreted as normal character. Next or Done button appears automatically and ENTER works as expected.

edit.setInputType(InputType.TYPE_CLASS_TEXT);

Comparing two arrays & get the values which are not common

Collection

$a = 1..5
$b = 4..8

$Yellow = $a | Where {$b -NotContains $_}

$Yellow contains all the items in $a except the ones that are in $b:

PS C:\> $Yellow
1
2
3

$Blue = $b | Where {$a -NotContains $_}

$Blue contains all the items in $b except the ones that are in $a:

PS C:\> $Blue
6
7
8

$Green = $a | Where {$b -Contains $_}

Not in question, but anyways; Green contains the items that are in both $a and $b.

PS C:\> $Green
4
5

Note: Where is an alias of Where-Object. Alias can introduce possible problems and make scripts hard to maintain.


Addendum 12 October 2019

As commented by @xtreampb and @mklement0: although not shown from the example in the question, the task that the question implies (values "not in common") is the symmetric difference between the two input sets (the union of yellow and blue).

Union

The symmetric difference between the $a and $b can be literally defined as the union of $Yellow and $Blue:

$NotGreen = $Yellow + $Blue

Which is written out:

$NotGreen = ($a | Where {$b -NotContains $_}) + ($b | Where {$a -NotContains $_})

Performance

As you might notice, there are quite some (redundant) loops in this syntax: all items in list $a iterate (using Where) through items in list $b (using -NotContains) and visa versa. Unfortunately the redundancy is difficult to avoid as it is difficult to predict the result of each side. A Hash Table is usually a good solution to improve the performance of redundant loops. For this, I like to redefine the question: Get the values that appear once in the sum of the collections ($a + $b):

$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}

By using the ForEach statement instead of the ForEach-Object cmdlet and the Where method instead of the Where-Object you might increase the performance by a factor 2.5:

$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})

LINQ

But Language Integrated Query (LINQ) will easily beat any native PowerShell and native .Net methods (see also High Performance PowerShell with LINQ and mklement0's answer for Can the following Nested foreach loop be simplified in PowerShell?:

To use LINQ you need to explicitly define the array types:

[Int[]]$a = 1..5
[Int[]]$b = 4..8

And use the [Linq.Enumerable]:: operator:

$Yellow   = [Int[]][Linq.Enumerable]::Except($a, $b)
$Blue     = [Int[]][Linq.Enumerable]::Except($b, $a)
$Green    = [Int[]][Linq.Enumerable]::Intersect($a, $b)
$NotGreen = [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))

Benchmark

Benchmark results highly depend on the sizes of the collections and how many items there are actually shared, as a "average", I am presuming that half of each collection is shared with the other.

Using             Time
Compare-Object    111,9712
NotContains       197,3792
ForEach-Object    82,8324
ForEach Statement 36,5721
LINQ              22,7091

To get a good performance comparison, caches should be cleared by e.g. starting a fresh PowerShell session.

$a = 1..1000
$b = 500..1500

(Measure-Command {
    Compare-Object -ReferenceObject $a -DifferenceObject $b  -PassThru
}).TotalMilliseconds
(Measure-Command {
    ($a | Where {$b -NotContains $_}), ($b | Where {$a -NotContains $_})
}).TotalMilliseconds
(Measure-Command {
    $Count = @{}
    $a + $b | ForEach-Object {$Count[$_] += 1}
    $Count.Keys | Where-Object {$Count[$_] -eq 1}
}).TotalMilliseconds

(Measure-Command {
    $Count = @{}
    ForEach ($Item in $a + $b) {$Count[$Item] += 1}
    $Count.Keys.Where({$Count[$_] -eq 1})
}).TotalMilliseconds

[Int[]]$a = $a
[Int[]]$b = $b
(Measure-Command {
    [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
}).TotalMilliseconds

Adding elements to object

This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

How to call a shell script from python code?

In case the script is having multiple arguments

#!/usr/bin/python

import subprocess
output = subprocess.call(["./test.sh","xyz","1234"])
print output

Output will give the status code. If script runs successfully it will give 0 otherwise non-zero integer.

podname=xyz  serial=1234
0

Below is the test.sh shell script.

#!/bin/bash

podname=$1
serial=$2
echo "podname=$podname  serial=$serial"

100% width in React Native Flexbox

Here you go:

Just change the line1 style as per below:

line1: {
    backgroundColor: '#FDD7E4',
    width:'100%',
    alignSelf:'center'
}

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

How to install SQL Server Management Studio 2008 component only

I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.

That is what worked for me.

Add / Change parameter of URL and redirect to the new URL

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

PHP include relative path

function relativepath($to){
    $a=explode("/",$_SERVER["PHP_SELF"] );
    $index= array_search("$to",$a);
    $str=""; 
    for ($i = 0; $i < count($a)-$index-2; $i++) {
        $str.= "../";
    }
    return $str;
    }

Here is the best solution i made about that, you just need to specify at which level you want to stop, but the problem is that you have to use this folder name one time.

get UTC timestamp in python with datetime

Another possibility is:

d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970,1,1)
t = (d - epoch).total_seconds()

This works as both "d" and "epoch" are naive datetimes, making the "-" operator valid, and returning an interval. total_seconds() turns the interval into seconds. Note that total_seconds() returns a float, even d.microsecond == 0

Linq Query Group By and Selecting First Items

var result = list.GroupBy(x => x.Category).Select(x => x.First())

Eclipse DDMS error "Can't bind to local 8600 for debugger"

In my case, it just worked when I killed the Eclipse process, and restart the software.

Set formula to a range of cells

I would update the formula in C1. Then copy the formula from C1 and paste it till C10...

Not sure about a more elegant solution

Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C1:C10").Pastespecial(XlPasteall)

JSONObject - How to get a value?

You can try the below function to get value from JSON string,

public static String GetJSONValue(String JSONString, String Field)
{
       return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");   
}

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

Performance of Java matrix math libraries?

Matrix Tookits Java (MTJ) was already mentioned before, but perhaps it's worth mentioning again for anyone else stumbling onto this thread. For those interested, it seems like there's also talk about having MTJ replace the linalg library in the apache commons math 2.0, though I'm not sure how that's progressing lately.

library not found for -lPods

if you are running into problems with this on cocoapods v25 / Xcode 5

The Pods Xcode project now sets the ONLY_ACTIVE_ARCH build setting to YES in the Debug configuration. You will have to set the same on your project/target, otherwise the build will fail.

https://github.com/CocoaPods/CocoaPods/wiki/FAQ#running-into-build-failures-after-migrating-to-xcode-5-and-cocoapods-0250

UPDATE Make sure you have latest gems / cocoapods

  • gem update system
  • gem update cocoapods

You will want to rebuild project using Pod Install to rebuild project.

Jquery - How to make $.post() use contentType=application/json?

The "json" datatype that you can pass as the last parameter to post() indicates what type of data the function is expecting in the server's response, not what type it's sending in the request. Specifically it sets the "Accept" header.

Honestly your best bet is to switch to an ajax() call. The post() function is meant as a convenience; a simplified version of the ajax() call for when you are just doing a simple form posting. You aren't.

If you really don't want to switch, you could make your own function called, say, xpost(), and have it simply transform the given parameters into parameters for a jQuery ajax() call, with the content-type set. That way, rather than rewriting all of those post() functions into ajax() functions, you just have to change them all from post to xpost (or whatever).

Difference between BYTE and CHAR in column datatypes

Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:

  1. Limits field to 11 BYTE
  2. Limits field to 11 CHARacters


Conclusion: 1 CHAR is not equal to 1 BYTE.

How to extract svg as file from web page

You can copy the HTML svg tag from the website, then paste the code on a new html file and rename the extension to svg. It worked for me. Hope it helps you.

How can I strip first X characters from string using sed?

Rather than removing n characters from the start, perhaps you could just extract the digits directly. Like so...

$ echo "pid: 1234" | grep -Po "\d+"

This may be a more robust solution, and seems more intuitive.

Convert int to ASCII and back in Python

If multiple characters are bound inside a single integer/long, as was my issue:

s = '0123456789'
nchars = len(s)
# string to int or long. Type depends on nchars
x = sum(ord(s[byte])<<8*(nchars-byte-1) for byte in range(nchars))
# int or long to string
''.join(chr((x>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))

Yields '0123456789' and x = 227581098929683594426425L

Is there a way to override class variables in Java?

You cannot override variables in a class. You can override only methods. You should keep the variables private otherwise you can get a lot of problems.

Convert float to std::string in C++

You can use std::to_string in C++11

float val = 2.5;
std::string my_val = std::to_string(val);

search in java ArrayList

You're missing the return statement because if your list size is 0, the for loop will never execute, thus the if will never run, and thus you will never return.

Move the if statement out of the loop.

Encrypt Password in Configuration Files?

I think that the best approach is to ensure that your config file (containing your password) is only accessible to a specific user account. For example, you might have an application specific user appuser to which only trusted people have the password (and to which they su to).

That way, there's no annoying cryptography overhead and you still have a password which is secure.

EDIT: I am assuming that you are not exporting your application configuration outside of a trusted environment (which I'm not sure would make any sense, given the question)

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

Implement touch using Python?

with open(file_name,'a') as f: 
    pass

How to submit a form when the return key is pressed?

I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:

<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
    border: 0 none;
    height: 0;
    width: 0;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.

Update

I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146

Intermediate CA Certificates

How to go back (ctrl+z) in vi/vim

I had the same problem right now and i solved it. You must not need it anymore so I write for others:

if you use gvim on windows, you just add this in your _vimrc: $VIMRUNTIME/mswin.vim behave mswin

else just use imap...

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

FFmpeg: How to split video efficiently?

The ffmpeg wiki links back to this page in reference to "How to split video efficiently". I'm not convinced this page answers that question, so I did as @AlcubierreDrive suggested…

echo "Two commands" 
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 -sn test1.mkv
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test2.mkv
echo "One command" 
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 \
  -sn test3.mkv -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test4.mkv

Which outputs...

Two commands
real    0m16.201s
user    0m1.830s
sys 0m1.301s

real    0m43.621s
user    0m4.943s
sys 0m2.908s

One command
real    0m59.410s
user    0m5.577s
sys 0m3.939s

I tested a SD & HD file, after a few runs & a little maths.

Two commands SD 0m53.94 #2 wins  
One command  SD 0m49.63  

Two commands SD 0m55.00  
One command  SD 0m52.26 #1 wins 

Two commands SD 0m58.60 #2 wins  
One command  SD 0m58.61 

Two commands SD 0m54.60  
One command  SD 0m50.51 #1 wins 

Two commands SD 0m53.94  
One command  SD 0m49.63 #1 wins  

Two commands SD 0m55.00  
One command  SD 0m52.26 #1 wins 

Two commands SD 0m58.71  
One command  SD 0m58.61 #1 wins

Two commands SD 0m54.63  
One command  SD 0m50.51 #1 wins  

Two commands SD 1m6.67s #2 wins  
One command  SD 1m20.18  

Two commands SD 1m7.67  
One command  SD 1m6.72 #1 wins

Two commands SD 1m4.92  
One command  SD 1m2.24 #1 wins

Two commands SD 1m1.73  
One command  SD 0m59.72 #1 wins

Two commands HD 4m23.20  
One command  HD 3m40.02 #1 wins

Two commands SD 1m1.30  
One command  SD 0m59.59 #1 wins  

Two commands HD 3m47.89  
One command  HD 3m29.59 #1 wins  

Two commands SD 0m59.82  
One command  SD 0m59.41 #1 wins  

Two commands HD 3m51.18  
One command  HD 3m30.79 #1 wins  

SD file = 1.35GB DVB transport stream
HD file = 3.14GB DVB transport stream

Conclusion

The single command is better if you are handling HD, it agrees with the manuals comments on using -ss after the input file to do a 'slow seek'. SD files have a negligible difference.

The two command version should be quicker by adding another -ss before the input file for the a 'fast seek' followed by the more accurate slow seek.

Check/Uncheck checkbox with JavaScript

vanilla (PHP) will check box on and off and store result.

<?php
    if($serverVariable=="checked") 
        $checked = "checked";
    else
        $checked = "";
?>
<input type="checkbox"  name="deadline" value="yes" <?= $checked 
?> >

# on server
<?php
        if(isset($_POST['deadline']) and
             $_POST['deadline']=='yes')
             $serverVariable = checked;    
        else
             $serverVariable = "";  
?>

How to print last two columns using awk

try with this

$ cat /tmp/topfs.txt
/dev/sda2      xfs        32G   10G   22G  32% /

awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'

awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%

awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /

VBA equivalent to Excel's mod function

But if you just want to tell the difference between an odd iteration and an even iteration, this works just fine:

If i Mod 2 > 0 then 'this is an odd 
   'Do Something
Else 'it is even
   'Do Something Else
End If