Programs & Examples On #Anonymous access

How to install mysql-connector via pip

pip install mysql-connector

Last but not least,You can also install mysql-connector via source code

Download source code from: https://dev.mysql.com/downloads/connector/python/

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

android TextView: setting the background color dynamically doesn't work

tv.setTextColor(getResources().getColor(R.color.solid_red));

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.

  1. Default @INC

    Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command (env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this:

    $ env -i perl -V
    ...
    @INC:
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    

Note . at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T (taint checks enabled).

To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs:

Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3

  1. Environmental variable PERL5LIB (or PERLLIB)

    Perl pre-pends @INC with a list of directories (colon-separated) contained in PERL5LIB (if it is not defined, PERLLIB is used) environment variable of your shell. To see the contents of @INC after PERL5LIB and PERLLIB environment variables have taken effect, run perl -V.

    $ perl -V
    ...
    %ENV:
      PERL5LIB="/home/myuser/test"
    @INC:
     /home/myuser/test
     /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/site_perl/5.18.0
     /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld
     /usr/lib/perl5/5.18.0
     .
    
  2. -I command-line option

    Perl pre-pends @INC with a list of directories (colon-separated) passed as value of the -I command-line option. This can be done in three ways, as usual with Perl options:

    • Pass it on command line:

      perl -I /my/moduledir your_script.pl
      
    • Pass it via the first line (shebang) of your Perl script:

      #!/usr/local/bin/perl -w -I /my/moduledir
      
    • Pass it as part of PERL5OPT (or PERLOPT) environment variable (see chapter 19.02 in Programming Perl)

  3. Pass it via the lib pragma

    Perl pre-pends @INC with a list of directories passed in to it via use lib.

    In a program:

    use lib ("/dir1", "/dir2");
    

    On the command line:

    perl -Mlib=/dir1,/dir2
    

    You can also remove the directories from @INC via no lib.

  4. You can directly manipulate @INC as a regular Perl array.

    Note: Since @INC is used during the compilation phase, this must be done inside of a BEGIN {} block, which precedes the use MyModule statement.

    • Add directories to the beginning via unshift @INC, $dir.

    • Add directories to the end via push @INC, $dir.

    • Do anything else you can do with a Perl array.

Note: The directories are unshifted onto @INC in the order listed in this answer, e.g. default @INC is last in the list, preceded by PERL5LIB, preceded by -I, preceded by use lib and direct @INC manipulation, the latter two mixed in whichever order they are in Perl code.

References:

There does not seem to be a comprehensive @INC FAQ-type post on Stack Overflow, so this question is intended as one.

When to use each approach?

  • If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC compiled into the Perl binary.

  • If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC in previous use case), set the users' PERL5LIB, usually during user login.

    Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su.

  • If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB manually, or pass the -I option to perl.

  • If the modules need to be used only for specific scripts, by all users using them, use use lib/no lib pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).

  • If the directories in @INC need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib/no lib pragmas, then use direct @INC manipulation inside BEGIN {} block or inside a special purpose library designated for @INC manipulation, which must be used by your script(s) before any other modules are used.

    An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.

  • An additional use case for directly manipulating @INC is to be able to add subroutine references or object references (yes, Virginia, @INC can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).

How to choose the id generation strategy when using JPA and Hibernate

I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.

Android ListView with Checkbox and all clickable

Set the CheckBox as focusable="false" in your XML layout. Otherwise it will steal click events from the list view.

Of course, if you do this, you need to manually handle marking the CheckBox as checked/unchecked if the list item is clicked instead of the CheckBox, but you probably want that anyway.

Adding placeholder text to textbox

Let's extend the TextBox with PlcaeHoldText and PlaceHoldBackround. I stripped some code form my project.

say goodbye to Grid or Canvas!

<TextBox x:Class="VcpkgGui.View.PlaceHoldedTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:VcpkgGui.View"
             mc:Ignorable="d"
             Name="placeHoldTextBox"
             TextAlignment="Left"
         >
    <TextBox.Resources>
        <local:FrameworkWidthConverter x:Key="getElemWidth"/>
        <local:FrameworkHeightConverter x:Key="getElemHeight"/>
        <VisualBrush x:Key="PlaceHoldTextBrush" TileMode="None" Stretch="None" AlignmentX="Left" AlignmentY="Center" Opacity="1">
            <VisualBrush.Visual>
                <Border Background="{Binding ElementName=placeHoldTextBox, Path=PlaceHoldBackground}"
                        BorderThickness="0"
                        Margin="0,0,0,0"
                        Width="{Binding Mode=OneWay, ElementName=placeHoldTextBox, Converter={StaticResource getElemWidth}}"
                        Height="{Binding Mode=OneWay, ElementName=placeHoldTextBox, Converter={StaticResource getElemHeight}}"
                        >
                    <Label Content="{Binding ElementName=placeHoldTextBox, Path=PlaceHoldText}"
                           Background="Transparent"
                           Foreground="#88000000"
                           HorizontalAlignment="Stretch"
                           VerticalAlignment="Stretch"
                           HorizontalContentAlignment="Left"
                           VerticalContentAlignment="Center"
                           ClipToBounds="True"
                           Padding="0,0,0,0"
                           FontSize="14"
                           FontStyle="Normal"
                           Opacity="1"/>
                </Border>
            </VisualBrush.Visual>
        </VisualBrush>
    </TextBox.Resources>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <Trigger Property="Text" Value="{x:Null}">
                    <Setter Property="Background"  Value="{StaticResource PlaceHoldTextBrush}"/>
                </Trigger>
                <Trigger Property="Text" Value="">
                    <Setter Property="Background"  Value="{StaticResource PlaceHoldTextBrush}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace VcpkgGui.View
{
    /// <summary>
    /// PlaceHoldedTextBox.xaml ?????
    /// </summary>
    public partial class PlaceHoldedTextBox : TextBox
    {

        public string PlaceHoldText
        {
            get { return (string)GetValue(PlaceHoldTextProperty); }
            set { SetValue(PlaceHoldTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for PlaceHolderText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PlaceHoldTextProperty =
            DependencyProperty.Register("PlaceHoldText", typeof(string), typeof(PlaceHoldedTextBox), new PropertyMetadata(string.Empty));



        public Brush PlaceHoldBackground
        {
            get { return (Brush)GetValue(PlaceHoldBackgroundProperty); }
            set { SetValue(PlaceHoldBackgroundProperty, value); }
        }

        public static readonly DependencyProperty PlaceHoldBackgroundProperty =
            DependencyProperty.Register(nameof(PlaceHoldBackground), typeof(Brush), typeof(PlaceHoldedTextBox), new PropertyMetadata(Brushes.White));

        public PlaceHoldedTextBox() :base()
        {
            InitializeComponent();
        }
    }

    [ValueConversion(typeof(FrameworkElement), typeof(double))]
    internal class FrameworkWidthConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value is FrameworkElement elem)
                return double.IsNaN(elem.Width) ? elem.ActualWidth : elem.Width;
            else
                return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    [ValueConversion(typeof(FrameworkElement), typeof(double))]
    internal class FrameworkHeightConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is FrameworkElement elem)
                return double.IsNaN(elem.Height) ? elem.ActualHeight : elem.Height;
            else
                return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

}

Trimming text strings in SQL Server 2008

I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):

_x000D_
_x000D_
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
 IF (@c IS NULL) RETURN NULL;_x000D_
 DECLARE @WHITESPACE NCHAR(31);_x000D_
 SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
 IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
 RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
 -- Check tiny strings (NULL, 0 or 1 chars)_x000D_
 IF @TEXT IS NULL RETURN N'';_x000D_
 DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
 IF @TEXTLENGTH < 2 BEGIN_x000D_
  IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
  IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
  RETURN @TEXT;_x000D_
 END_x000D_
 -- Check whether we have to LTRIM/RTRIM_x000D_
 DECLARE @SKIPSTART INT;_x000D_
 SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
 DECLARE @SKIPEND INT;_x000D_
 SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
 DECLARE @INDEX INT;_x000D_
 IF (@SKIPSTART = 1) BEGIN_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- FULLTRIM_x000D_
   -- Determine start white-space length_x000D_
   SELECT @INDEX = 2;_x000D_
   WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise assign index as @SKIPSTART_x000D_
    SELECT @SKIPSTART = @INDEX;_x000D_
    -- Increase character index_x000D_
    SELECT @INDEX = (@INDEX + 1);_x000D_
   END_x000D_
   -- Return '' if the whole string is white-space_x000D_
   IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
  END _x000D_
  -- LTRIM_x000D_
  -- Determine start white-space length_x000D_
  SELECT @INDEX = 2;_x000D_
  WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
   -- Stop loop if no white-space_x000D_
   IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
   -- Otherwise assign index as @SKIPSTART_x000D_
   SELECT @SKIPSTART = @INDEX;_x000D_
   -- Increase character index_x000D_
   SELECT @INDEX = (@INDEX + 1);_x000D_
  END_x000D_
  -- Return trimmed string_x000D_
  RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
 END ELSE BEGIN_x000D_
  -- RTRIM_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
  END _x000D_
 END_x000D_
 -- NO TRIM_x000D_
 RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
_x000D_
_x000D_

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,

it should be: -

 <a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' : 
 'userclass'"> 
 </a>

or just:

<a href="" th:class="${isAdmin} ? 'newclass' : 
  'baseclass'"> 
 </a>

PHP refresh window? equivalent to F5 page reload?

PHP cannot force the client to do anything. It cannot refresh the page, let alone refresh the parent of a frame.

EDIT: You can of course, make PHP write JavaScript, but this is not PHP doing, it's actually JavaScript, and it will fail if JavaScript is disabled.

<?php
    echo '<script>parent.window.location.reload(true);</script>';
?>

How to use regex in String.contains() method in Java

public static void main(String[] args) {
    String test = "something hear - to - find some to or tows";
    System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
    System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
    if(fromIndex != null && fromIndex < text.length())
        return Pattern.compile(pattern).matcher(text).find();

    return Pattern.compile(pattern).matcher(text).find();
}

1.result: true

2.result: true

How do you select a particular option in a SELECT element in jQuery?

Exactly it will work try this below methods

For normal select option

<script>    
    $(document).ready(function() {
    $("#id").val('select value here');
       });
        </script>

For select 2 option trigger option need to use

<script>    
        $(document).ready(function() {
        $("#id").val('select value here').trigger('change');
           });
            </script>

What is the difference between range and xrange functions in Python 2.X?

range(): range(1, 10) returns a list from 1 to 10 numbers & hold whole list in memory.

xrange(): Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than range() and more memory efficient. xrange() object like an iterator and generates the numbers on demand.(Lazy Evaluation)

In [1]: range(1,10)

Out[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]: xrange(10)

Out[2]: xrange(10)

In [3]: print xrange.__doc__

xrange([start,] stop[, step]) -> xrange object

Understanding the Gemfile.lock file

in regards to the exclamation mark I just found out it's on gems fetched via :git, e.g.

gem "foo", :git => "[email protected]:company/foo.git"

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, this js reproduces the same problem that happens with Paola

My solution:

$(document.body).tooltip({selector: '[title]'})
.on('click mouseenter mouseleave','[title]', function(ev) {
    $(this).tooltip('mouseenter' === ev.type? 'show': 'hide');
});

No connection could be made because the target machine actively refused it?

This is really specific, but if you receive this error after trying to connect to a database using mongo, what worked for me was running mongod.exe before running mongo.exe and then the connection worked fine. Hope this helps someone.

How to pretty print nested dictionaries?

This class prints out a complex nested dictionary with sub dictionaries and sub lists.  
##
## Recursive class to parse and print complex nested dictionary
##

class NestedDictionary(object):
    def __init__(self,value):
        self.value=value

    def print(self,depth):
        spacer="--------------------"
        if type(self.value)==type(dict()):
            for kk, vv in self.value.items():
                if (type(vv)==type(dict())):
                    print(spacer[:depth],kk)
                    vvv=(NestedDictionary(vv))
                    depth=depth+3
                    vvv.print(depth)
                    depth=depth-3
                else:
                    if (type(vv)==type(list())):
                        for i in vv:
                            vvv=(NestedDictionary(i))
                            depth=depth+3
                            vvv.print(depth)
                            depth=depth-3
                    else:
                        print(spacer[:depth],kk,vv) 

##
## Instatiate and execute - this prints complex nested dictionaries
## with sub dictionaries and sub lists
## 'something' is a complex nested dictionary

MyNest=NestedDictionary(weather_com_result)
MyNest.print(0)

Random float number generation

Take a look at Boost.Random. You could do something like this:

float gen_random_float(float min, float max)
{
    boost::mt19937 rng;
    boost::uniform_real<float> u(min, max);
    boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > gen(rng, u);
    return gen();
}

Play around, you might do better passing the same mt19937 object around instead of constructing a new one every time, but hopefully you get the idea.

Javascript: How to loop through ALL DOM elements on a page?

You can pass a * to getElementsByTagName() so that it will return all elements in a page:

var all = document.getElementsByTagName("*");

for (var i=0, max=all.length; i < max; i++) {
     // Do something with the element here
}

Note that you could use querySelectorAll(), if it's available (IE9+, CSS in IE8), to just find elements with a particular class.

if (document.querySelectorAll)
    var clsElements = document.querySelectorAll(".mySpeshalClass");
else
    // loop through all elements instead

This would certainly speed up matters for modern browsers.


Browsers now support foreach on NodeList. This means you can directly loop the elements instead of writing your own for loop.

document.querySelectorAll('*').forEach(function(node) {
    // Do whatever you want with the node object.
});

Performance note - Do your best to scope what you're looking for by using a specific selector. A universal selector can return lots of nodes depending on the complexity of the page. Also, consider using document.body.querySelectorAll instead of document.querySelectorAll when you don’t care about <head> children.

Save string to the NSUserDefaults?

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

to get it back later

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

Put spacing between divs in a horizontal row?

Quite a few ways to apprach this problem.

Use the box-sizing css3 property and simulate the margins with borders.

http://jsfiddle.net/Z7mFr/1/

div.inside {
 width: 25%;
 float:left;
 border-right: 5px solid grey;
 background-color: blue;
 box-sizing:border-box;
 -moz-box-sizing:border-box; /* Firefox */
 -webkit-box-sizing:border-box; /* Safari */
}

<div style="width:100%; height: 200px; background-color: grey;">
 <div class="inside">A</div>
 <div class="inside">B</div>
 <div class="inside">C</div>
 <div class="inside">D</div>
</div>

Reduce the percentage of your elements widths and add some margin-right.

http://jsfiddle.net/mJfz3/

.outer {
 width:100%;
 background:#999;
 overflow:auto;
}

.inside {
 float:left;
 width:24%;
 margin-right:1%;
 background:#333;
}

The connection to adb is down, and a severe error has occurred

I just got the same problem and to fix it, I opened the task manager and killed the adb.exe process, then I restarted Eclipse.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I solved this by looking at this comment on JBIDE-11655 : deleting all .project, .settings and .classpath in my projects folder.

How to get text from EditText?

in Kotlin 1.3

 val readTextFromUser = (findViewById(R.id.inputedText) as EditText).text.toString()

This will read the current text that the user has typed on the UI screen

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

Is there a .NET/C# wrapper for SQLite?

Version 1.2 of Monotouch includes support for System.Data. You can find more details here: http://monotouch.net/Documentation/System.Data

But basically it allows you to use the usual ADO .NET patterns with sqlite.

nodemon not working: -bash: nodemon: command not found

in Windows OS run:

npx nodemon server.js

or add in package.json config:

...
"scripts": {
    "dev": "npx nodemon server.js"
  },
...

then run:

npm run dev

How can I print literal curly-brace characters in a string and also use .format on it?

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

Here's the relevant part of the Python documentation for format string syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

Which type of folder structure should be used with Angular 2?

If project is small and will remain small, I would recommend to structure by type (Method 2: ng-book2)

app
|- components
|  |- hero
|  |- hero-list
|  |- villain
|  |- ...
|- services
|  |- hero.service.ts
|  |- ...
|- utils
|- shared

If project will grow you should structure your folders by domain (Method 3: mgechev/angular2-seed)

app
|- heroes
|  |- hero
|  |- hero-list
|  |- hero.service.ts
|- villains
|  |- villain
|  |- ...
|- utils
|- shared

Better to Follow official docs.
https://angular.io/guide/styleguide#application-structure-and-ngmodules

Display progress bar while doing some work in C#?

Use the BackgroundWorker component it is designed for exactly this scenario.

You can hook into its progress update events and update your progress bar. The BackgroundWorker class ensures the callbacks are marshalled to the UI thread so you don't need to worry about any of that detail either.

How to create a toggle button in Bootstrap

Initial answer from 2013

An excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

<input type="checkbox" name="my-checkbox" checked>
$("[name='my-checkbox']").bootstrapSwitch();

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like this one from the React Component framework (not Bootstrap related, but can be integrated in Bootstrap grid and UI though).

Other implementations exist for Angular, View or jQuery.

Modern 2018 Switch

import '../assets/index.less'
import React from 'react'
import ReactDOM from 'react-dom'
import Switch from 'rc-switch'

class Switcher extends React.Component {
  state = {
    disabled: false,
  }

  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    })
  }

  render() {
    return (
      <div style={{ margin: 20 }}>
        <Switch
          disabled={this.state.disabled}
          checkedChildren={'?'}
          unCheckedChildren={'?'}
        />
        </div>
      </div>
    )
  }
}

ReactDOM.render(<Switcher />, document.getElementById('__react-content'))

Native Bootstrap Switches

See ohkts11's answer below about the native Bootstrap switches.

What is difference between @RequestBody and @RequestParam?

@RequestParam makes Spring to map request parameters from the GET/POST request to your method argument.

GET Request

http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia

public String getCountryFactors(@RequestParam(value = "city") String city, 
                    @RequestParam(value = "country") String country){ }

POST Request

@RequestBody makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.

http://testwebaddress.com/getInformation.do

You have JSON data as such coming from the front end and hits your controller class

{
   "city": "Sydney",
   "country": "Australia"
}

Java Code - backend (@RequestBody)

public String getCountryFactors(@RequestBody Country countryFacts)
    {
        countryFacts.getCity();
        countryFacts.getCountry();
    }


public class Country {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

How to flush route table in windows?

From command prompt as admin run:

netsh interface ip delete destinationcache

Works on Win7.

Maven2: Missing artifact but jars are in place

I tried all of the above solutions except manually installing jar in my repository.

By deleting the _remote_repositories file in the same directory as the "missing jar file" and doing maven update I got it to work.

This is the same end result as manually installing, I presume.

Where does Android emulator store SQLite database?

The databases are stored as SQLite files in /data/data/PACKAGE/databases/DATABASEFILE where:

You can see (copy from/to filesystem) the database file in the emulator selecting DDMS perspective, in the File Explorer tab.

Javascript onclick hide div

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

Get full query string in C# ASP.NET

Just use Request.QueryString.ToString() to get full query string, like this:

string URL = "http://www.example.com/rendernews.php?"+Request.Querystring.ToString();

How to get multiple counts with one SQL query?

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

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

Result:

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

How to Set Opacity (Alpha) for View in Android

Although btnMybutton.getBackground().setAlpha(45); is nice idea, it just apply alpha to background and not the whole view.

If you want apply alpha to view use btnMybutton.setAlpha(0.30f); instead. This apply opacity to View. It accepts a value between 0 and 1.

Doc says:

Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque. If this view overrides onSetAlpha(int) to return true, then this view is responsible for applying the opacity itself. Otherwise, calling this method is equivalent to calling setLayerType(int, android.graphics.Paint) and setting a hardware layer. Note that setting alpha to a translucent value (0 < alpha < 1) may have performance implications. It is generally best to use the alpha property sparingly and transiently, as in the case of fading animations.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

How to get a Static property with Reflection

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)

Cannot delete directory with Directory.Delete(path, true)

As mentioned above the "accepted" solution fails on reparse points - yet people still mark it up(???). There's a much shorter solution that properly replicates the functionality:

public static void rmdir(string target, bool recursive)
{
    string tfilename = Path.GetDirectoryName(target) +
        (target.Contains(Path.DirectorySeparatorChar.ToString()) ? Path.DirectorySeparatorChar.ToString() : string.Empty) +
        Path.GetRandomFileName();
    Directory.Move(target, tfilename);
    Directory.Delete(tfilename, recursive);
}

I know, doesn't handle the permissions cases mentioned later, but for all intents and purposes FAR BETTER provides the expected functionality of the original/stock Directory.Delete() - and with a lot less code too.

You can safely carry on processing because the old dir will be out of the way ...even if not gone because the 'file system is still catching up' (or whatever excuse MS gave for providing a broken function).

As a benefit, if you know your target directory is large/deep and don't want to wait (or bother with exceptions) the last line can be replaced with:

    ThreadPool.QueueUserWorkItem((o) => { Directory.Delete(tfilename, recursive); });

You are still safe to carry on working.

og:type and valid values : constantly being parsed as og:type=website

As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines

books.author This object type represents a single author of a book.

books.book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

books.quotes
Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

books.rates
Returns no data as of April 4, 2018.

An action representing someone rating a book.

books.reads
Returns no data as of April 4, 2018.

An action representing someone reading a book.

books.wants_to_read
Returns no data as of April 4, 2018.

An action representing someone wanting to read a book.

business.business This object type represents a place of business that has a location, operating hours and contact information.

fitness.bikes
Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

fitness.runs
Returns no data as of April 4, 2018.

An action representing someone running a course.

fitness.walks
Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

music.listens
Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

music.playlists
Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.

music.song This object type represents a single song.

news.publishes An action representing someone publishing a news article.

news.reads
Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.

product.group This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user.

restaurant.menu This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items.

restaurant.restaurant This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.

video.movie This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the video.movie or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

video.rates
Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

video.wants_to_watch
Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.

video.watches
Returns no data as of April 4, 2018.

An action representing someone watching video content.

Html encode in PHP

By encode, do you mean: Convert all applicable characters to HTML entities?

htmlspecialchars or htmlentities

You can also use strip_tags if you want to remove all HTML tags :

strip_tags

Note: this will NOT stop all XSS attacks

getting the table row values with jquery

All Elements

$('#tabla > tbody  > tr').each(function() {
    $(this).find("td:gt(0)").each(function(){
       alert($(this).html());
       });
});

How to use function srand() with time.h?

#include"stdio.h"
#include"conio.h"
#include"time.h"

void main()
{
  time_t t;
  int i;
  srand(time(&t));

  for(i=1;i<=10;i++)
    printf("%c\t",rand()%10);
  getch();
}

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Detecting mobile devices

Related answer: https://stackoverflow.com/a/13805337/1306809

There's no single approach that's truly foolproof. The best bet is to mix and match a variety of tricks as needed, to increase the chances of successfully detecting a wider range of handheld devices. See the link above for a few different options.

SQL Server insert if not exists best practice

Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code

Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from 
(
    select new.* from 
    (
        select distinct cName, cCity, cState 
        from [Competitors] s, [City] c, [State] s
    ) new
    left join 
    (   
        select distinct cName, cCity, cState 
        from [Competitors] s
    ) existing
    on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
    where existing.Name is null  or existing.City is null or existing.State is null
)

add a string prefix to each value in a string column using Pandas

Another solution with .loc:

df = pd.DataFrame({'col': ['a', 0]})
df.loc[df.index, 'col'] = 'string' + df['col'].astype(str)

This is not as quick as solutions above (>1ms per loop slower) but may be useful in case you need conditional change, like:

mask = (df['col'] == 0)
df.loc[mask, 'col'] = 'string' + df['col'].astype(str)

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

NUnit is probably the most supported by the 3rd party tools. It's also been around longer than the other three.

I personally don't care much about unit test frameworks, mocking libraries are IMHO much more important (and lock you in much more). Just pick one and stick with it.

How to convert a string from uppercase to lowercase in Bash?

The correct way to implement your code is

y="HELLO"
val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
string="$val world"

This uses $(...) notation to capture the output of the command in a variable. Note also the quotation marks around the string variable -- you need them there to indicate that $val and world are a single thing to be assigned to string.

If you have bash 4.0 or higher, a more efficient & elegant way to do it is to use bash builtin string manipulation:

y="HELLO"
string="${y,,} world"

Simplest way to have a configuration file in a Windows Forms C# application

Use:

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

AppSettings has been deprecated and is now considered obsolete (link).

In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.

As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.

How to list all methods for an object in Ruby?

To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):

Parser.new.methods - Object.new.methods

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

This literally means that the mentioned class com.example.Bean doesn't have a public (non-static!) getter method for the mentioned property foo. Note that the field itself is irrelevant here!

The public getter method name must start with get, followed by the property name which is capitalized at only the first letter of the property name as in Foo.

public Foo getFoo() {
    return foo;
}

You thus need to make sure that there is a getter method matching exactly the property name, and that the method is public (non-static) and that the method does not take any arguments and that it returns non-void. If you have one and it still doesn't work, then chances are that you were busy editing code forth and back without firmly cleaning the build, rebuilding the code and redeploying/restarting the application. You need to make sure that you have done so.

For boolean (not Boolean!) properties, the getter method name must start with is instead of get.

public boolean isFoo() {
    return foo;
}

Regardless of the type, the presence of the foo field itself is thus not relevant. It can have a different name, or be completely absent, or even be static. All of below should still be accessible by ${bean.foo}.

public Foo getFoo() {
    return bar;
}
public Foo getFoo() {
    return new Foo("foo");
}
public Foo getFoo() {
    return FOO_CONSTANT;
}

You see, the field is not what counts, but the getter method itself. Note that the property name itself should not be capitalized in EL. In other words, ${bean.Foo} won't ever work, it should be ${bean.foo}.

See also:

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

C# cannot convert method to non delegate type

You can simplify your class code to this below and it will work as is but if you want to make your example work, add parenthesis at the end : string x = getTitle();

public class Pin
{
   public string Title { get; set;}
}

What are Unwind segues for and how do you use them?

For example if you navigate from viewControllerB to viewControllerA then in your viewControllerA below delegate will call and data will share.

@IBAction func unWindSeague (_ sender : UIStoryboardSegue) {
        if sender.source is ViewControllerB  {
            if let _ = sender.source as? ViewControllerB {
                self.textLabel.text = "Came from B = B->A , B exited"
            }
            
        }

}
  • Unwind Seague Source View Controller ( You Need to connect Exit Button to VC’s exit icon and connect it to unwindseague:

enter image description here

  • Unwind Seague Completed -> TextLabel of viewControllerA is Changed.

enter image description here

how to console.log result of this ajax call?

If you want to check your URL. I suppose you are using Chrome. You can go to chrome console and URL will be displayed under "XHR finished loading:"

Close iOS Keyboard by touching anywhere using Swift

I found the best solution included the accepted answer from @Esqarrouth, with some adjustments:

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboardView")
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboardView() {
        view.endEditing(true)
    }
}

The line tap.cancelsTouchesInView = false was critical: it ensures that the UITapGestureRecognizer does not prevent other elements on the view from receiving user interaction.

The method dismissKeyboard() was changed to the slightly less elegant dismissKeyboardView(). This is because in my project's fairly old codebase, there were numerous times where dismissKeyboard() was already used (I imagine this is not uncommon), causing compiler issues.

Then, as above, this behaviour can be enabled in individual View Controllers:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

Facebook development in localhost

NOTE: As of 2012 Facebook allows registration of "localhost" as return Url. You still may need similar workaround for other providers (i.e. Microsoft one).

If you need real domain name registered with Facebook (like my.really.own.domain.com) you can locally redirect requests to this domain to your machine. Easiest out of box approach on any OS is to change "hosts" file to map the domain to 127.0.0.1 (see http://technet.microsoft.com/en-us/library/bb727005.aspx#EDAA and https://serverfault.com/questions/118290/cname-record-alias-in-windows-hosts-file).

I usually use Fiddler to do it for me (on Windows with local IIS) - see samples on http://www.fiddler2.com/Fiddler/Dev/ScriptSamples.asp.

if (oSession.HostnameIs("my.really.own.domain.com")) {
   oSession.host="localhost:80";
}

Hosts file approach of approaches does not work with Visual Studio Development Server as it requires incoming Urls to be localhost/127.0.0.1. If you need to work with it (or possibly with IIS express) to override host - Using Fiddler with IIS7 Express

Disable form auto submit on button click

You could just try using return false (return false overrides default behaviour on every DOM element) like that :

myform.onsubmit = function ()
{ 
  // do what you want
  return false
}

and then submit your form using myform.submit()

or alternatively :

mybutton.onclick = function () 
{
   // do what you want
   return false
}

Also, if you use type="button" your form will not be submitted.

How can I detect if a selector returns null?

The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length of the collection returned by the selector or check whether the first array element is 'undefined'.

You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined

How do I pass a method as a parameter in Python

Not exactly what you want, but a related useful tool is getattr(), to use method's name as a parameter.

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

JavaScript split String with white space

Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)

So:

var stringArray = str.split(/(\s+)/);
                             ^   ^
//

Output:

["my", " ", "car", " ", "is", " ", "red"]

This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.

Android: Center an image

If you are using a LinearLayout , use the gravity attribute :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView android:layout_width="wrap_content"
        android:id="@+id/imageView1"
        android:src="@drawable/icon"
        android:layout_height="wrap_content"
        android:scaleType="centerInside" />
</LinearLayout>

If you are using a RelativeLayout , you can use android:layout_centerInParent as follows :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon"
        android:scaleType="centerInside"
        android:layout_centerInParent="true" />

</RelativeLayout>

Difference between BYTE and CHAR in column datatypes

One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.

See also http://www.joelonsoftware.com/articles/Unicode.html

delete word after or around cursor in VIM

It doesn't look like there's any built-in way to do it in insert mode, which was the question. Some of the other answers are correct for normal mode, as well as pointing out that a custom mapping could be created to add the functionality in insert mode.

Honestly, you should probably do most of your deleting in normal mode. ^W is neat to know about but I'm not sure I can think of a situation where I'd rather do it than esc to go into normal mode and have the more powerful deletion commands at my disposal.

Vim is very different from a number of other editors (including TextMate) in this way. If you're using it productively, you'll probably find that you don't spend very much time in insert mode.

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).

Your code looks fine if you need to run a request from server side code or under a different user.

Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.

Execute a stored procedure in another stored procedure in SQL server

Yes, you can do that like this:

BEGIN
   DECLARE @Results TABLE (Tid INT PRIMARY KEY);

   INSERT @Results

   EXEC Procedure2 [parameters];
   SET @total 1;

END
SELECT @total

How to call stopservice() method of Service class from the calling activity class

That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.

If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.

AutoService

class AutoService extends IntentService {
     private static final String TAG = "AutoService";
     private Timer timer;    
     private TimerTask task;

     public onCreate() {
          timer = new Timer();
          timer = new TimerTask() {
            public void run() 
            {
                System.out.println("done");
            }
          }
     }

     protected void onHandleIntent(Intent i) {
        Log.d(TAG, "onHandleIntent");     

        int delay = 5000; // delay for 5 sec.
        int period = 5000; // repeat every sec.


        timer.scheduleAtFixedRate(timerTask, delay, period);
     }

     public boolean stopService(Intent name) {
        // TODO Auto-generated method stub
        timer.cancel();
        task.cancel();
        return super.stopService(name);
    }

}

PHP - auto refreshing page

you can use

<meta http-equiv="refresh" content="10" > 

just add it after the head tags

where 10 is the time your page will refresh itself

Selecting only first-level elements in jquery

$("ul > li a")

But you would need to set a class on the root ul if you specifically want to target the outermost ul:

<ul class="rootlist">
...

Then it's:

$("ul.rootlist > li a")....

Another way of making sure you only have the root li elements:

$("ul > li a").not("ul li ul a")

It looks kludgy, but it should do the trick

How to turn on/off MySQL strict mode in localhost (xampp)?

In my case, I need to add:

sql_mode="STRICT_TRANS_TABLES"

under [mysqld] in the file my.ini located in C:\xampp\mysql\bin.

base64 encode in MySQL

create table encrypt(username varchar(20),password varbinary(200))

insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';

Programmatically generate video or animated GIF in Python?

Well, now I'm using ImageMagick. I save my frames as PNG files and then invoke ImageMagick's convert.exe from Python to create an animated GIF. The nice thing about this approach is I can specify a frame duration for each frame individually. Unfortunately this depends on ImageMagick being installed on the machine. They have a Python wrapper but it looks pretty crappy and unsupported. Still open to other suggestions.

How to get my activity context?

If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application instead.

I'd suggest reading this article about context to better figure it out what context you need.

python JSON object must be str, bytes or bytearray, not 'dict

json.loads take a string as input and returns a dictionary as output.

json.dumps take a dictionary as input and returns a string as output.


With json.loads({"('Hello',)": 6, "('Hi',)": 5}),

You are calling json.loads with a dictionary as input.

You can fix it as follows (though I'm not quite sure what's the point of that):

d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)

Hadoop/Hive : Loading data from .csv on a local machine

For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE 
'org.apache.hadoop.hive.serde2.OpenCSVSerde' 
STORED AS TEXTFILE ;

The real difference between "int" and "unsigned int"

There is no difference between the two in how they are stored in memory and registers, there is no signed and unsigned version of int registers there is no signed info stored with the int, the difference only becomes relevant when you perform maths operations, there are signed and unsigned version of the maths ops built into the CPU and the signedness tell the compiler which version to use.

Explain ggplot2 warning: "Removed k rows containing missing values"

Just for the shake of completing the answer given by eipi10.

I was facing the same problem, without using scale_y_continuous nor coord_cartesian.

The conflict was coming from the x axis, where I defined limits = c(1, 30). It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error

Removed 8 rows containing missing values (geom_bar)

Adjusting the limits of the x axis to limits = c(0, 31) solved the problem.

In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space

How to create a sub array from another array in Java?

The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:

java -version

I'm guessing that you are not running 1.6

How to place object files in separate subdirectory

This is the makefile that I use for most of my projects,

It permits putting source files, headers and inline files in subfolders, and subfolders of subfolders and so-forth, and will automatically generate a dependency file for each object This means that modification of headers and inline files will trigger recompilation of files which are dependent.

Source files are detected via shell find command, so there is no need to explicitly specify, just keep coding to your hearts content.

It will also copy all files from a 'resources' folder, into the bin folder when the project is compiled, which I find handy most of the time.

To provide credit where it is due, the auto-dependencies feature was based largely off Scott McPeak's page that can be found HERE, with some additional modifications / tweaks for my needs.

Example Makefile

#Compiler and Linker
CC          := g++-mp-4.7

#The Target Binary Program
TARGET      := program

#The Directories, Source, Includes, Objects, Binary and Resources
SRCDIR      := src
INCDIR      := inc
BUILDDIR    := obj
TARGETDIR   := bin
RESDIR      := res
SRCEXT      := cpp
DEPEXT      := d
OBJEXT      := o

#Flags, Libraries and Includes
CFLAGS      := -fopenmp -Wall -O3 -g
LIB         := -fopenmp -lm -larmadillo
INC         := -I$(INCDIR) -I/usr/local/include
INCDEP      := -I$(INCDIR)

#---------------------------------------------------------------------------------
#DO NOT EDIT BELOW THIS LINE
#---------------------------------------------------------------------------------
SOURCES     := $(shell find $(SRCDIR) -type f -name *.$(SRCEXT))
OBJECTS     := $(patsubst $(SRCDIR)/%,$(BUILDDIR)/%,$(SOURCES:.$(SRCEXT)=.$(OBJEXT)))

#Defauilt Make
all: resources $(TARGET)

#Remake
remake: cleaner all

#Copy Resources from Resources Directory to Target Directory
resources: directories
    @cp $(RESDIR)/* $(TARGETDIR)/

#Make the Directories
directories:
    @mkdir -p $(TARGETDIR)
    @mkdir -p $(BUILDDIR)

#Clean only Objecst
clean:
    @$(RM) -rf $(BUILDDIR)

#Full Clean, Objects and Binaries
cleaner: clean
    @$(RM) -rf $(TARGETDIR)

#Pull in dependency info for *existing* .o files
-include $(OBJECTS:.$(OBJEXT)=.$(DEPEXT))

#Link
$(TARGET): $(OBJECTS)
    $(CC) -o $(TARGETDIR)/$(TARGET) $^ $(LIB)

#Compile
$(BUILDDIR)/%.$(OBJEXT): $(SRCDIR)/%.$(SRCEXT)
    @mkdir -p $(dir $@)
    $(CC) $(CFLAGS) $(INC) -c -o $@ $<
    @$(CC) $(CFLAGS) $(INCDEP) -MM $(SRCDIR)/$*.$(SRCEXT) > $(BUILDDIR)/$*.$(DEPEXT)
    @cp -f $(BUILDDIR)/$*.$(DEPEXT) $(BUILDDIR)/$*.$(DEPEXT).tmp
    @sed -e 's|.*:|$(BUILDDIR)/$*.$(OBJEXT):|' < $(BUILDDIR)/$*.$(DEPEXT).tmp > $(BUILDDIR)/$*.$(DEPEXT)
    @sed -e 's/.*://' -e 's/\\$$//' < $(BUILDDIR)/$*.$(DEPEXT).tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $(BUILDDIR)/$*.$(DEPEXT)
    @rm -f $(BUILDDIR)/$*.$(DEPEXT).tmp

#Non-File Targets
.PHONY: all remake clean cleaner resources

CSS values using HTML5 data attribute

As of today, you can read some values from HTML5 data attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data properties for setting the content.

Unfortunately it is not working for the width and height (tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).

But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width and data-height. You can find the GitHub repo to it here: cssattr.js.

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

Resizing an Image without losing any quality

Are you resizing larger, or smaller? By a small % or by a larger factor like 2x, 3x? What do you mean by quality for your application? And what type of images - photographs, hard-edged line drawings, or what? Writing your own low-level pixel grinding code or trying to do it as much as possible with existing libraries (.net or whatever)?

There is a large body of knowledge on this topic. The key concept is interpolation.

Browsing recommendations:
* http://www.all-in-one.ee/~dersch/interpolator/interpolator.html
* http://www.cambridgeincolour.com/tutorials/image-interpolation.htm
* for C#: https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&fid=3657&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=629945 * this is java-specific but might be educational - http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

How to pass Multiple Parameters from ajax call to MVC Controller

In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.

var dataObject = JSON.stringify({
                    'input': $('#myInput').val(),
                    'name': $('#myName').val(),
                });

Now use it in ajax call

$.ajax({
          url: "/Home/SaveChart",
          type: 'POST',
          async: false,
          dataType: 'json',
          contentType: 'application/json',
          data: dataObject,
          success: function (data) { },
          error: function (xhr) { }            )};

What is the exact location of MySQL database tables in XAMPP folder?

For Mac, your database files are located at:

/Applications/XAMPP/xamppfiles/var/mysql

You might need admin permissions to access or delete your files.

Removing padding gutter from grid columns in Bootstrap 4

You can use the mixin make-col-ready and set the gutter width to zero:

@include make-col-ready(0);

How do I save a stream to a file in C#?

You must not use StreamReader for binary files (like gifs or jpgs). StreamReader is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)

Why do you need to use a StreamReader at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?

EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

To use it to dump a stream to a file, for example:

using (Stream file = File.Create(filename))
{
    CopyStream(input, file);
}

Note that Stream.CopyTo was introduced in .NET 4, serving basically the same purpose.

What is the best way to connect and use a sqlite database from C#

if you have any problem with the library you can use Microsoft.Data.Sqlite;

 public static DataTable GetData(string connectionString, string query)
        {
            DataTable dt = new DataTable();
            Microsoft.Data.Sqlite.SqliteConnection connection;
            Microsoft.Data.Sqlite.SqliteCommand command;

            connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
            try
            {
                connection.Open();
                command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
                dt.Load(command.ExecuteReader());
                connection.Close();
            }
            catch
            {
            }

            return dt;
        }

you can add NuGet Package Microsoft.Data.Sqlite

How to kill all active and inactive oracle sessions for user

Execute this script:

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' 
FROM v$session 
where username='YOUR_USER';

It will printout sqls, which should be executed.

How to send and retrieve parameters using $state.go toParams and $stateParams?

If this is a query parameter that you want to pass like this: /toState?referer=current_user

then you need to describe your state like this:

$stateProvider.state('toState', {
  url:'toState?referer',
  views:{'...'}
});

source: https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters

Eclipse error: R cannot be resolved to a variable

The R file can't be generated if your layout contains errors. If your res folder is empty, then it's safe to assume that there's no res/layout folder with any layouts in it, but your activity is probably calling setContentView and not finding anything -- that qualifies as a problem with your layout.

How to use if - else structure in a batch file?

IF...ELSE IF constructs work very well in batch files, in particular when you use only one conditional expression on each IF line:

IF %F%==1 (
    ::copying the file c to d
    copy "%sourceFile%1" "%destinationFile1%"
) ELSE IF %F%==0 (
    ::moving the file e to f
    move "%sourceFile2%" "%destinationFile2%" )

In your example you use IF...AND...IF type construct, where 2 conditions must be met simultaneously. In this case you can still use IF...ELSE IF construct, but with extra parentheses to avoid uncertainty for the next ELSE condition:

IF %F%==1 (IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile1%" "%destinationFile1%" )
) ELSE IF %F%==1 (IF %C%==0 (
    ::moving the file e to f
    move "%sourceFile2%" "%destinationFile2%"))

The above construct is equivalent to:

IF %F%==1 (
    IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile1%" "%destinationFile1%"
    ) ELSE IF %C%==0 (
    ::moving the file e to f
    move "%sourceFile2%" "%destinationFile2%"))

Processing sequence of batch commands depends on CMD.exe parsing order. Just make sure your construct follows that logical order, and as a rule it will work. If your batch script is processed by Cmd.exe without errors, it means this is the correct (i.e. supported by your OS Cmd.exe version) construct, even if someone said otherwise.

How do you create different variable names while in a loop?

Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break

how to get all markers on google-maps-v3

For an specific cluster use: getMarkers() Gets the array of markers in the clusterer.

For all the markers in the map use: getTotalMarkers() Gets the array of markers in the clusterer.

Android - Best and safe way to stop thread

You should make your thread support interrupts. Basically, you can call yourThread.interrupt() to stop the thread and, in your run() method you'd need to periodically check the status of Thread.interrupted()

There is a good tutorial here.

Why aren't python nested functions called closures?

People are confusing about what closure is. Closure is not the inner function. the meaning of closure is act of closing. So inner function is closing over a nonlocal variable which is called free variable.

def counter_in(initial_value=0):
    # initial_value is the free variable
    def inc(increment=1):
        nonlocal initial_value
        initial_value += increment
        return print(initial_value)
    return inc

when you call counter_in() this will return inc function which has a free variable initial_value. So we created a CLOSURE. people call inc as closure function and I think this is confusing people, people think "ok inner functions are closures". in reality inc is not a closure, since it is part of the closure, to make life easy, they call it closure function.

  myClosingOverFunc=counter_in(2)

this returns inc function which is closing over the free variable initial_value. when you invoke myClosingOverFunc

 myClosingOverFunc() 

it will print 2.

when python sees that a closure sytem exists, it creates a new obj called CELL. this will store only the name of the free variable which is initial_value in this case. This Cell obj will point to another object which stores the value of the initial_value.

in our example, initial_value in outer function and inner function will point to this cell object, and this cell object will be point to the value of the initial_value.

  variable initial_value =====>> CELL ==========>> value of initial_value

So when you call counter_in its scope is gone, but it does not matter. because variable initial_value is directly referencing the CELL Obj. and it indirectly references the value of initial_value. That is why even though scope of outer function is gone, inner function will still have access to the free variable

let's say I want to write a function, which takes in a function as an arg and returns how many times this function is called.

def counter(fn):
    # since cnt is a free var, python will create a cell and this cell will point to the value of cnt
    # every time cnt changes, cell will be pointing to the new value
    cnt = 0

    def inner(*args, **kwargs):
        # we cannot modidy cnt with out nonlocal
        nonlocal cnt
        cnt += 1
        print(f'{fn.__name__} has been called {cnt} times')
        # we are calling fn indirectly via the closue inner
        return fn(*args, **kwargs)
    return inner
      

in this example cnt is our free variable and inner + cnt create CLOSURE. when python sees this it will create a CELL Obj and cnt will always directly reference this cell obj and CELL will reference the another obj in the memory which stores the value of cnt. initially cnt=0.

 cnt   ======>>>>  CELL  =============>  0

when you invoke the inner function wih passing a parameter counter(myFunc)() this will increase the cnt by 1. so our referencing schema will change as follow:

 cnt   ======>>>>  CELL  =============>  1  #first counter(myFunc)()
 cnt   ======>>>>  CELL  =============>  2  #second counter(myFunc)()
 cnt   ======>>>>  CELL  =============>  3  #third counter(myFunc)()

this is only one instance of closure. You can create multiple instances of closure with passing another function

counter(differentFunc)()

this will create a different CELL obj from the above. We just have created another closure instance.

 cnt  ======>>  difCELL  ========>  1  #first counter(differentFunc)()
 cnt  ======>>  difCELL  ========>  2  #secon counter(differentFunc)()
 cnt  ======>>  difCELL  ========>  3  #third counter(differentFunc)()


  

Chrome sendrequest error: TypeError: Converting circular structure to JSON

Based on zainengineer's answer... Another approach is to make a deep copy of the object and strip circular references and stringify the result.

_x000D_
_x000D_
function cleanStringify(object) {_x000D_
    if (object && typeof object === 'object') {_x000D_
        object = copyWithoutCircularReferences([object], object);_x000D_
    }_x000D_
    return JSON.stringify(object);_x000D_
_x000D_
    function copyWithoutCircularReferences(references, object) {_x000D_
        var cleanObject = {};_x000D_
        Object.keys(object).forEach(function(key) {_x000D_
            var value = object[key];_x000D_
            if (value && typeof value === 'object') {_x000D_
                if (references.indexOf(value) < 0) {_x000D_
                    references.push(value);_x000D_
                    cleanObject[key] = copyWithoutCircularReferences(references, value);_x000D_
                    references.pop();_x000D_
                } else {_x000D_
                    cleanObject[key] = '###_Circular_###';_x000D_
                }_x000D_
            } else if (typeof value !== 'function') {_x000D_
                cleanObject[key] = value;_x000D_
            }_x000D_
        });_x000D_
        return cleanObject;_x000D_
    }_x000D_
}_x000D_
_x000D_
// Example_x000D_
_x000D_
var a = {_x000D_
    name: "a"_x000D_
};_x000D_
_x000D_
var b = {_x000D_
    name: "b"_x000D_
};_x000D_
_x000D_
b.a = a;_x000D_
a.b = b;_x000D_
_x000D_
console.log(cleanStringify(a));_x000D_
console.log(cleanStringify(b));
_x000D_
_x000D_
_x000D_

What is the usefulness of PUT and DELETE HTTP request methods?

Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer

The easiest way to see benefits from this is to look at this example. Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers. So URL like this: /blog/article/1 would invoke blogController::articleAction($id); Now this Router is only aware of the URL or /blog/article/1/

But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.

That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.

For example:

if you want to retrive article 1 you can do this:

GET /blog/article/1 HTTP/1.1

but if you want to delete article 1 you will do this:

DELETE /blog/article/1 HTTP/1.1

Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.

Read this two articles, they might help you:

Symfony 2 - HTTP Fundamentals

Symfony 2 - Routing

These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.

Hope this helps!

Multiple files upload (Array) with CodeIgniter 2.0

SO what I change is I load upload library each time

                $config = array();
                $config['upload_path'] = $filePath;
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']      = '0';
                $config['overwrite']     = FALSE;

                $files = $_FILES;
                $count = count($_FILES['nameUpload']['name']);


                for($i=0; $i<$count; $i++)
                {
                    $this->load->library('upload', $config);

                    $_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
                    $_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
                    $_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
                    $_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
                    $_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];

                    $this->upload->do_upload('nameUpload');
                }

And it work for me.

How can I submit a form using JavaScript?

HTML

<!-- change id attribute to name  -->

<form method="post" action="yourUrl" name="theForm">
    <button onclick="placeOrder()">Place Order</button>
</form>

JavaScript

function placeOrder () {
    document.theForm.submit()
}

loop through json array jquery

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data);
$.each(data, function(i, item) {
    alert(item);
});

Wait 5 seconds before executing next line

Best way to create a function like this for wait in milli seconds, this function will wait for milliseconds provided in the argument:

_x000D_
_x000D_
function waitSeconds(iMilliSeconds) {_x000D_
    var counter= 0_x000D_
        , start = new Date().getTime()_x000D_
        , end = 0;_x000D_
    while (counter < iMilliSeconds) {_x000D_
        end = new Date().getTime();_x000D_
        counter = end - start;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

When You are sending a single quote in a query

empid = " T'via"
empid =escape(empid)

When You get the value including a single quote

var xxx  = request.QueryString("empid")
xxx= unscape(xxx)

If you want to search/ insert the value which includes a single quote in a query xxx=Replace(empid,"'","''")

How to print_r $_POST array?

As you need to see the result for testing purpose. The simple and elegant solution is the below code.

echo "<pre>";
print_r($_POST);
echo "</pre>";

Best way to get value from Collection by index

Convert the collection into an array by using function

Object[] toArray(Object[] a) 

How can I echo HTML in PHP?

This is how I do it:

<?php if($contition == true){ ?>
         <input type="text" value="<?php echo $value_stored_in_php_variable; ?>" />
<?php }else{ ?>
         <p>No input here </p>
<?php } ?>

How to make a JFrame button open another JFrame class in Netbeans?

Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)

btnLogin.addActionListener(new ActionListener() 
{
    public void actionPerformed(ActionEvent e) {
        this.setVisible(false);
        new FrmMain().setVisible(true); // Main Form to show after the Login Form..
    }
});

How to Join to first row

@Quassnoi answer is good, in some cases (especially if the outer table is big), a more efficient query might be with using windowed functions, like this:

SELECT  Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description
FROM    Orders
LEFT JOIN 
        (
        SELECT  LineItems.Quantity, LineItems.Description, OrderId, ROW_NUMBER()
                OVER (PARTITION BY OrderId ORDER BY (SELECT NULL)) AS RowNum
        FROM    LineItems

        ) LineItems2 ON LineItems2.OrderId = Orders.OrderID And RowNum = 1

Sometimes you just need to test which query gives better performance.

How can I use an http proxy with node.js http.Client?

Node should support using the http_proxy environmental variable - so it is cross platform and works on system settings rather than requiring a per-application configuration.

Using the provided solutions, I would recommend the following:

Coffeescript

get_url = (url, response) ->
  if process.env.http_proxy?
    match = process.env.http_proxy.match /^(http:\/\/)?([^:\/]+)(:([0-9]+))?/i
    if match
      http.get { host: match[2], port: (if match[4]? then match[4] else 80), path: url }, response
      return
  http.get url, response

Javascript

get_url = function(url, response) {
  var match;
  if (process.env.http_proxy != null) {
    match = process.env.http_proxy.match(/^(http:\/\/)?([^:\/]+)(:([0-9]+))?/i);
    if (match) {
      http.get({
        host: match[2],
        port: (match[4] != null ? match[4] : 80),
        path: url
      }, response);
      return;
    }
  }
  return http.get(url, response);
};

Usage To use the method, effectively just replace http.get, for instance the following writes the index page of google to a file called test.htm:

file = fs.createWriteStream path.resolve(__dirname, "test.htm")
get_url "http://www.google.com.au/", (response) ->
  response.pipe file
  response.on "end", ->
    console.log "complete"

Convert UTC/GMT time to local time

Don't forget if you already have a DateTime object and are not sure if it's UTC or Local, it's easy enough to use the methods on the object directly:

DateTime convertedDate = DateTime.Parse(date);
DateTime localDate = convertedDate.ToLocalTime();

How do we adjust for the extra hour?

Unless specified .net will use the local pc settings. I'd have a read of: http://msdn.microsoft.com/en-us/library/system.globalization.daylighttime.aspx

By the looks the code might look something like:

DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges( year );

And as mentioned above double check what timezone setting your server is on. There are articles on the net for how to safely affect the changes in IIS.

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

Jackson serialization: ignore empty values (or null)

You need to add import com.fasterxml.jackson.annotation.JsonInclude;

Add

@JsonInclude(JsonInclude.Include.NON_NULL)

on top of POJO

If you have nested POJO then

@JsonInclude(JsonInclude.Include.NON_NULL)

need to add on every values.

NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.

Get current URL from IFRAME

Some additional information for anyone who might be struggling with this:

You'll be getting null values if you're trying to get URL from iframe before it's loaded. I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:

var iframe = document.createElement('iframe');
iframe.onload = function() {

    //some custom settings
    this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";

    var href = iframe.contentWindow.location.href;
    var origin = iframe.contentWindow.location.origin;
    var url = iframe.contentWindow.location.url;
    var path = iframe.contentWindow.location.pathname;

    console.log("href: ", href)
    console.log("origin: ", origin)
    console.log("path: ", path)
    console.log("url: ", url)
};

iframe.src = 'http://localhost/folder/index.html';

document.body.appendChild(iframe);

Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.

Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

Python - difference between two strings

I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:

import difflib

case_a = 'afrykbnerskojezyczny'
case_b = 'afrykanerskojezycznym'

output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']

Convert NSArray to NSString in Objective-C

One approach would be to iterate over the array, calling the description message on each item:

NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
    [result appendString:[obj description]];
}
NSLog(@"The concatenated string is %@", result);

Another approach would be to do something based on each item's class:

NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
    if ([obj isKindOfClass:[NSNumber class]])
    {
        // append something
    }
    else
    {
        [result appendString:[obj description]];
    }
}
NSLog(@"The concatenated string is %@", result);

If you want commas and other extraneous information, you can just do:

NSString * result = [array description];

How to find index of list item in Swift?

Swift 4. If your array contains elements of type [String: AnyObject]. So to find the index of element use the below code

var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)

Or If you want to found index on the basis of key from Dictionary. Here array contains Objects of Model class and I am matching id property.

   let userId = 20
    if let index = array.index(where: { (dict) -> Bool in
           return dict.id == userId // Will found index of matched id
    }) {
    print("Index found")
    }
OR
      let storeId = Int(surveyCurrent.store_id) // Accessing model key value
      indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one

Creating a file name as a timestamp in a batch job

1) You can download GNU coreutils which comes with GNU date

2) you can use VBScript, which makes date manipulation easier in Windows:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
Set objFolder = objFS.GetFolder(strFolder)
current = Now
mth = Month(current)
d = Day(current)
yr = Year(current)
If Len(mth) <2 Then
    mth="0"&mth
End If
If Len(d) < 2 Then
    d = "0"&d
End If
timestamp=yr & "-" & mth &"-"& d
For Each strFile In objFolder.Files
    strFileName = strFile.Name
    If InStr(strFileName,"file_name_here") > 0 Then
        BaseName = objFS.GetBaseName(strFileName)
        Extension = objFS.GetExtensionName(strFileName)
        NewName = BaseName & "-" & timestamp & "." & Extension
        strFile.Name = NewName
    End If
Next

Run the script as:

c:\test> cscript /nologo myscript.vbs

Dealing with "Xerces hell" in Java/Maven?

I know this doesn't answer the question exactly, but for ppl coming in from google that happen to use Gradle for their dependency management:

I managed to get rid of all xerces/Java8 issues with Gradle like this:

configurations {
    all*.exclude group: 'xml-apis'
    all*.exclude group: 'xerces'
}

Column name or number of supplied values does not match table definition

Dropping the table was not an option for me, since I'm keeping a running log. If every time I needed to insert I had to drop, the table would be meaningless.

My error was because I had a couple columns in the create table statement that were products of other columns, changing these fixed my problem. eg

create table foo (
field1 as int
,field2 as int
,field12 as field1 + field2 )

create table copyOfFoo (
field1 as int
,field2 as int
,field12 as field1 + field2)  --this is the problem, should just be 'as int'

insert into copyOfFoo
SELECT * FROM foo

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

Change limit for "Mysql Row size too large"

I also encountered the same problem. I solve the problem by executing the following sql:

ALTER ${table} ROW_FORMAT=COMPRESSED;

But, I think u should know about the Row Storage.
There are two kinds of columns: variable-length column(such as VARCHAR, VARBINARY, and BLOB and TEXT types) and fixed-length column. They are stored in different types of pages.

Variable-length columns are an exception to this rule. Columns such as BLOB and VARCHAR that are too long to fit on a B-tree page are stored on separately allocated disk pages called overflow pages. We call such columns off-page columns. The values of these columns are stored in singly-linked lists of overflow pages, and each such column has its own list of one or more overflow pages. In some cases, all or a prefix of the long column value is stored in the B-tree, to avoid wasting storage and eliminating the need to read a separate page.

and when purpose of setting ROW_FORMAT is

When a table is created with ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED, InnoDB can store long variable-length column values (for VARCHAR, VARBINARY, and BLOB and TEXT types) fully off-page, with the clustered index record containing only a 20-byte pointer to the overflow page.

Wanna know more about DYNAMIC and COMPRESSED Row Formats

parsing JSONP $http.jsonp() response in angular.js

For parsing do this-

   $http.jsonp(url).
    success(function(data, status, headers, config) {
    //what do I do here?
     $scope.data=data;
}).

Or you can use `$scope.data=JSON.Stringify(data);

In Angular template you can use it as

{{data}}

Plain Old CLR Object vs Data Transfer Object

I wrote an article for that topic: DTO vs Value Object vs POCO.

In short:

  • DTO != Value Object
  • DTO ? POCO
  • Value Object ? POCO

jQuery callback on image load (even when the image is cached)

A modification to GUS's example:

$(document).ready(function() {
    var tmpImg = new Image() ;
    tmpImg.onload = function() {
        // Run onload code.
    } ;

tmpImg.src = $('#img').attr('src');
})

Set the source before and after the onload.

:first-child not working as expected

you can also use

.detail_container h1:nth-of-type(1)

By changing the number 1 by any other number you can select any other h1 item.

C# Interfaces. Implicit implementation versus Explicit implementation

In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.

Here's an example:

public abstract class StringList : IEnumerable<string>
{
    private string[] _list = new string[] {"foo", "bar", "baz"};

    // ...

    #region IEnumerable<string> Members
    public IEnumerator<string> GetEnumerator()
    {
        foreach (string s in _list)
        { yield return s; }
    }
    #endregion

    #region IEnumerable Members
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    #endregion
}

Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.

ie.

StringList sl = new StringList();

// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();

PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

Get column index from column name in python pandas

For returning multiple column indices, I recommend using the pandas.Index method get_indexer, if you have unique labels:

df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
df.columns.get_indexer(['pear', 'apple'])
# Out: array([0, 1], dtype=int64)

If you have non-unique labels in the index (columns only support unique labels) get_indexer_for. It takes the same args as get_indeder:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]}, 
    index=[0, 1, 1])
df.index.get_indexer_for([0, 1])
# Out: array([0, 1, 2], dtype=int64)

Both methods also support non-exact indexing with, f.i. for float values taking the nearest value with a tolerance. If two indices have the same distance to the specified label or are duplicates, the index with the larger index value is selected:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
    index=[0, .9, 1.1])
df.index.get_indexer([0, 1])
# array([ 0, -1], dtype=int64)

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

Just include SizeToReportContent="true" as shown below

<rsweb:ReportViewer ID="ReportViewer1" runat="server" SizeToReportContent="True"...

How to convert String to long in Java?

It's quite simple, use Long.valueOf(String s);

For example:

String s;
long l;

Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);

You're done!!!

Angular ng-if="" with multiple arguments

Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

I recommend rbenv* https://github.com/rbenv/rbenv

* If this meets your criteria: https://github.com/rbenv/rbenv/wiki/Why-rbenv?:

rbenv does…

  • Provide support for specifying application-specific Ruby versions.
  • Let you change the global Ruby version on a per-user basis.
  • Allow you to override the Ruby version with an environment variable.

In contrast with RVM, rbenv does not…

  • Need to be loaded into your shell. Instead, rbenv's shim approach works by adding a directory to your $PATH.
  • Override shell commands like cd or require prompt hacks. That's dangerous and error-prone.
  • Have a configuration file. There's nothing to configure except which version of Ruby you want to use.
  • Install Ruby. You can build and install Ruby yourself, or use ruby-build to automate the process.
  • Manage gemsets. Bundler is a better way to manage application dependencies. If you have projects that are not yet using Bundler you can install the rbenv-gemset plugin.
  • Require changes to Ruby libraries for compatibility. The simplicity of rbenv means as long as it's in your $PATH, nothing else needs to know about it.

INSTALLATION

Install Homebrew http://brew.sh

Then:

$ brew update
$ brew install rbenv 
$ brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile

UPDATE
There's one additional step after brew install rbenv Run rbenv init and add one line to .bash_profile as it states. After that reopen your terminal window […] SGI Sep 30 at 12:01 —https://stackoverflow.com/users/119770

$ rbenv install --list
Available versions:
 1.8.5-p113
 1.8.5-p114
 […]
 2.3.1
 2.4.0-dev
 jruby-1.5.6
 […]
$ rbenv install 2.3.1
[…]

Set the global version:

$ rbenv global 2.3.1
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Set the local version of your repo by adding .ruby-version to your repo's root dir:

$ cd ~/whatevs/projects/new_repo
$ echo "2.3.1" > .ruby-version

For MacOS visit this link

Android appcompat v7:23

Original answer:

I too tried to change the support library to "23". When I changed the targetSdkVersion to 23, Android Studio reported the following error:

This support library should not use a lower version (22) than the targetSdkVersion (23)

I simply changed:

compile 'com.android.support:appcompat-v7:23.0.0'

to

compile 'com.android.support:appcompat-v7:+'

Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1.


Pro tip:

You can use double quotes and create a ${supportLibVersion} variable for simplicity. Example:

ext {
    supportLibVersion = '23.1.1'
}

compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"

source: https://twitter.com/manidesto/status/669195097947377664

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

The width is being restricted by the size of the body. If you make the width of the body larger you will see it stays on one line with the background color.

To maintain the minimum width: min-width:100%

Typescript: React event types

For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState here's my solution:

const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);

const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
    setAnchorElement(event.currentTarget);
};

What is the use of "assert"?

As written in other answers, assert statements are used to check the state of the program at a given point.

I won't repeat what was said about associated message, parentheses, or -O option and __debug__ constant. Check also the doc for first hand information. I will focus on your question: what is the use of assert? More precisely, when (and when not) should one use assert?

The assert statements are useful to debug a program, but discouraged to check user input. I use the following rule of thumb: keep assertions to detect a this should not happen situation. A user input may be incorrect, e.g. a password too short, but this is not a this should not happen case. If the diameter of a circle is not twice as large as its radius, you are in a this should not happen case.

The most interesting, in my mind, use of assert is inspired by the programming by contract as described by B. Meyer in [Object-Oriented Software Construction]( https://www.eiffel.org/doc/eiffel/Object-Oriented_Software_Construction%2C_2nd_Edition ) and implemented in the [Eiffel programming language]( https://en.wikipedia.org/wiki/Eiffel_(programming_language)). You can't fully emulate programming by contract using the assert statement, but it's interesting to keep the intent.

Here's an example. Imagine you have to write a head function (like the [head function in Haskell]( http://www.zvon.org/other/haskell/Outputprelude/head_f.html)). The specification you are given is: "if the list is not empty, return the first item of a list". Look at the following implementations:

>>> def head1(xs): return xs[0]

And

>>> def head2(xs):
...     if len(xs) > 0:
...         return xs[0]
...     else:
...         return None

(Yes, this can be written as return xs[0] if xs else None, but that's not the point).

If the list is not empty, both functions have the same result and this result is correct:

>>> head1([1, 2, 3]) == head2([1, 2, 3]) == 1
True

Hence, both implementations are (I hope) correct. They differ when you try to take the head item of an empty list:

>>> head1([])
Traceback (most recent call last):
...
IndexError: list index out of range

But:

>>> head2([]) is None
True

Again, both implementations are correct, because no one should pass an empty list to these functions (we are out of the specification). That's an incorrect call, but if you do such a call, anything can happen. One function raises an exception, the other returns a special value. The most important is: we can't rely on this behavior. If xs is empty, this will work:

print(head2(xs))

But this will crash the program:

print(head1(xs))

To avoid some surprises, I would like to know when I'm passing some unexpected argument to a function. In other words: I would like to know when the observable behavior is not reliable, because it depends on the implementation, not on the specification. Of course, I can read the specification, but programmers do not always read carefully the docs.

Imagine if I had a way to insert the specification into the code to get the following effect: when I violate the specification, e.g by passing an empty list to head, I get a warning. That would be a great help to write a correct (i.e. compliant with the specification) program. And that's where assert enters on the scene:

>>> def head1(xs):
...     assert len(xs) > 0, "The list must not be empty"
...     return xs[0]

And

>>> def head2(xs):
...     assert len(xs) > 0, "The list must not be empty"
...     if len(xs) > 0:
...         return xs[0]
...     else:
...         return None

Now, we have:

>>> head1([])
Traceback (most recent call last):
...
AssertionError: The list must not be empty

And:

>>> head2([])
Traceback (most recent call last):
...
AssertionError: The list must not be empty

Note that head1 throws an AssertionError, not an IndexError. That's important because an AssertionError is not any runtime error: it signals a violation of the specification. I wanted a warning, but I get an error. Fortunately, I can disable the check (using the -O option), but at my own risks. I will do it a crash is really expensive, and hope for the best. Imagine my program is embedded in a spaceship that travels through a black hole. I will disable assertions and hope the program is robust enough to not crash as long as possible.

This example was only about preconditions, be you can use assert to check postconditions (the return value and/or the state) and invariants (state of a class). Note that checking postconditions and invariants with assert can be cumbersome:

  • for postconditions, you need to assign the return value to a variable, and maybe to store the iniial state of the object if you are dealing with a method;
  • for invariants, you have to check the state before and after a method call.

You won't have something as sophisticated as Eiffel, but you can however improve the overall quality of a program.


To summarize, the assert statement is a convenient way to detect a this should not happen situation. Violations of the specification (e.g. passing an empty list to head) are first class this should not happen situations. Hence, while the assert statement may be used to detect any unexpected situation, it is a privilegied way to ensure that the specification is fulfilled. Once you have inserted assert statements into the code to represent the specification, we can hope you have improved the quality of the program because incorrect arguments, incorrect return values, incorrect states of a class..., will be reported.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

dataset = dataset.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

This worked for me

Java 8 Lambda filter by Lists

Something like:

clients.stream.filter(c->{
   users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());

This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.

How do I commit only some files?

Suppose you made changes to multiple files, like:

  • File1
  • File2
  • File3
  • File4
  • File5

But you want to commit only changes of File1 and File3.

There are two ways for doing this:

1.Stage only these two files, using:

git add file1 file2

then, commit

git commit -m "your message"

then push,

git push

2.Direct commit

git commit file1 file3 -m "my message"

then push,

git push

Actually first method is useful in case if we are modifying files regularly and staging them --> Large Projects, generally Live projects.
But if we are modifying files and not staging them then we can do direct commit --> Small projects

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

How to enable CORS on Firefox?

I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted...' in dev tools panel.

Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.

Sorting HTML table with JavaScript

Sorting html table column on page load

var table = $('table#all_items_table');
var rows = table.find('tr:gt(0)').toArray().sort(comparer(3));
for (var i = 0; i < rows.length; i++) {
    table.append(rows[i])
}
function comparer(index) {
    return function (a, b) {
        var v1= getCellValue(a, index),
        v2= getCellValue(b, index);
        return $.isNumeric(v2) && $.isNumeric(v1) ? v2 - v1: v2.localeCompare(v1)
    }
}


function getCellValue(row, index) {
    return parseFloat($(row).children('td').eq(index).html().replace(/,/g,'')); //1234234.45645->1234234
}

enter image description here

How to set proxy for wget?

In Ubuntu 12.x, I added the following lines in $HOME/.wgetrc

http_proxy = http://uname:[email protected]:8080

use_proxy = on

unique combinations of values in selected columns in pandas data frame and count

Slightly related, I was looking for the unique combinations and I came up with this method:

def unique_columns(df,columns):

    result = pd.Series(index = df.index)

    groups = meta_data_csv.groupby(by = columns)
    for name,group in groups:
       is_unique = len(group) == 1
       result.loc[group.index] = is_unique

    assert not result.isnull().any()

    return result

And if you only want to assert that all combinations are unique:

df1.set_index(['A','B']).index.is_unique

How to query as GROUP BY in django?

You need to do custom SQL as exemplified in this snippet:

Custom SQL via subquery

Or in a custom manager as shown in the online Django docs:

Adding extra Manager methods

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

How do I make a list of data frames?

Taking as a given you have a "large" number of data.frames with similar names (here d# where # is some positive integer), the following is a slight improvement of @mark-miller's method. It is more terse and returns a named list of data.frames, where each name in the list is the name of the corresponding original data.frame.

The key is using mget together with ls. If the data frames d1 and d2 provided in the question were the only objects with names d# in the environment, then

my.list <- mget(ls(pattern="^d[0-9]+"))

which would return

my.list
$d1
  y1 y2
1  1  4
2  2  5
3  3  6

$d2
  y1 y2
1  3  6
2  2  5
3  1  4

This method takes advantage of the pattern argument in ls, which allows us to use regular expressions to do a finer parsing of the names of objects in the environment. An alternative to the regex "^d[0-9]+$" is "^d\\d+$".

As @gregor points out, it is a better overall to set up your data construction process so that the data.frames are put into named lists at the start.

data

d1 <- data.frame(y1 = c(1,2,3),y2 = c(4,5,6))
d2 <- data.frame(y1 = c(3,2,1),y2 = c(6,5,4))

In C++, what is a virtual base class?

About the memory layout

As a side note, the problem with the Dreaded Diamond is that the base class is present multiple times. So with regular inheritance, you believe you have:

  A
 / \
B   C
 \ /
  D

But in the memory layout, you have:

A   A
|   |
B   C
 \ /
  D

This explain why when call D::foo(), you have an ambiguity problem. But the real problem comes when you want to use a member variable of A. For example, let's say we have:

class A
{
    public :
       foo() ;
       int m_iValue ;
} ;

When you'll try to access m_iValue from D, the compiler will protest, because in the hierarchy, it'll see two m_iValue, not one. And if you modify one, say, B::m_iValue (that is the A::m_iValue parent of B), C::m_iValue won't be modified (that is the A::m_iValue parent of C).

This is where virtual inheritance comes handy, as with it, you'll get back to a true diamond layout, with not only one foo() method only, but also one and only one m_iValue.

What could go wrong?

Imagine:

  • A has some basic feature.
  • B adds to it some kind of cool array of data (for example)
  • C adds to it some cool feature like an observer pattern (for example, on m_iValue).
  • D inherits from B and C, and thus from A.

With normal inheritance, modifying m_iValue from D is ambiguous and this must be resolved. Even if it is, there are two m_iValues inside D, so you'd better remember that and update the two at the same time.

With virtual inheritance, modifying m_iValue from D is ok... But... Let's say that you have D. Through its C interface, you attached an observer. And through its B interface, you update the cool array, which has the side effect of directly changing m_iValue...

As the change of m_iValue is done directly (without using a virtual accessor method), the observer "listening" through C won't be called, because the code implementing the listening is in C, and B doesn't know about it...

Conclusion

If you're having a diamond in your hierarchy, it means that you have 95% probability to have done something wrong with said hierarchy.

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

How to delete an SMS from the inbox in Android programmatically?

I think this can not be perfectly done for the time being. There are 2 basic problems:

  1. How can you make sure the sms is already in the inbox when you try to delete it?
    Notice that SMS_RECEIVED is not an ordered broadcast.
    So dmyung's solution is completely trying one's luck; even the delay in Doug's answer is not a guarantee.

  2. The SmsProvider is not thread safe.(refer to http://code.google.com/p/android/issues/detail?id=2916#c0)
    The fact that more than one clients are requesting delete and insert in it at the same time will cause data corruption or even immediate Runtime Exception.

JQuery Ajax Post results in 500 Internal Server Error

I run into the same thing today. As suggested before get Firebug for Firefox, Enable Console and preview POST response. That helped me to find out how stupid the problem was. My action was expecting value of a type int and I was posting string. (ASP.NET MVC2)

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

Transitions on the CSS display property

I've came across this issue multiple times and now simply went with:

.block {
  opacity: 1;
  transition: opacity 250ms ease;
}

.block--invisible {
  pointer-events: none;
  opacity: 0;
}

By adding the class block--invisible the whole Elements will not be clickable but all Elements behind it will be because of the pointer-events:none which is supported by all major browsers (no IE < 11).

Unable to copy file - access to the path is denied

Simple Solution:

Just upgrade the following packages

Microsoft.CodeDom.Providers.DotNetCompilerPlatform v1.0.5 to v1.0.7

It will resolve the issue.

What is the equivalent of "none" in django templates?

{% if profile.user.first_name %} works (assuming you also don't want to accept '').

if in Python in general treats None, False, '', [], {}, ... all as false.

angularjs: allows only numbers to be typed into a text box

This functionality just what you need. http://docs.angularjs.org/api/ng.directive:input.number

EDIT:

You can wrap the jquery plugin into directive. I created an example here: http://jsfiddle.net/anazimok/jTJCF/

HTML:

<div ng-app="myApp">
    <div>
        <input type="text" min="0" max="99" number-mask="" ng-model="message">
            <button ng-click="handleClick()">Broadcast</button>
    </div>

</div>

CSS:

.ng-invalid {
    border: 1px solid red;
}

JS:

// declare a module
var app = angular.module('myApp', []);

app.directive('numberMask', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).numeric();
        }
    }
});

jQuery: Adding two attributes via the .attr(); method

Should work:

.attr({
    target:"nw", 
    title:"Opens in a new window",
    "data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});

Note:

" When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

From the jQuery documentation (Sep 2016) for .attr:

Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

Edit:
For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use

$(".something").attr("title","Test");

To set multiple attributes you need to wrap everything in { ... }

$(".something").attr( { title:"Test", alt:"Test2" } );

Edit - If you're trying to get/set the 'checked' attribute from a checkbox...

You will need to use prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

So to get the checked status of a checkbox, you should use:

$('#checkbox1').prop('checked'); // Returns true/false

Or to set the checkbox as checked or unchecked you should use:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

What is the difference between statically typed and dynamically typed languages?

Statically Typed

The types are checked before run-time so mistakes can be caught earlier.

Examples = c++

Dynamically Typed

The types are checked during execution.

Examples = Python

How to use setprecision in C++

#include <bits/stdc++.h>                        // to include all libraries 
using namespace std; 
int main() 
{ 
double a,b;
cin>>a>>b;
double x=a/b;                                 //say we want to divide a/b                                 
cout<<fixed<<setprecision(10)<<x;             //for precision upto 10 digit 
return 0; 
} 

input: 1987 31

output: 662.3333333333 10 digits after decimal point

Quickest way to compare two generic lists for differences

I have used this code to compare two list which has million of records.

This method will not take much time

    //Method to compare two list of string
    private List<string> Contains(List<string> list1, List<string> list2)
    {
        List<string> result = new List<string>();

        result.AddRange(list1.Except(list2, StringComparer.OrdinalIgnoreCase));
        result.AddRange(list2.Except(list1, StringComparer.OrdinalIgnoreCase));

        return result;
    }

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

set environment variable

JAVA_HOME=C:\Program Files\Java\jdk1.6.0_24

classpath=C:\Program Files\Java\jdk1.6.0_24\lib\tools.jar

path=C:\Program Files\Java\jdk1.6.0_24\bin

CSS override rules and specificity

The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.

To make the second one override the first one, you can make more specific by adding information of it's parents:

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

Here is a nice article for more information on selector precedence.

Example on ToggleButton

Try this Toggle Buttons

test_activity.xml

<ToggleButton 
android:id="@+id/togglebutton" 
android:layout_width="100px" 
android:layout_height="50px" 
android:layout_centerVertical="true" 
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>

Test.java

public class Test extends Activity {

private ToggleButton togglebutton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}

public void toggleclick(View v){
    if(togglebutton.isChecked())
        Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
    }
}

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

How to find and return a duplicate value in array

Alas most of the answers are O(n^2).

Here is an O(n) solution,

a = %w{the quick brown fox jumps over the lazy dog}
h = Hash.new(0)
a.find { |each| (h[each] += 1) == 2 } # => 'the"

What is the complexity of this?

  • Runs in O(n) and breaks on first match
  • Uses O(n) memory, but only the minimal amount

Now, depending on how frequent duplicates are in your array these runtimes might actually become even better. For example if the array of size O(n) has been sampled from a population of k << n different elements only the complexity for both runtime and space becomes O(k), however it is more likely that the original poster is validating input and wants to make sure there are no duplicates. In that case both runtime and memory complexity O(n) since we expect the elements to have no repetitions for the majority of inputs.

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

JPA getSingleResult() or null

Throwing an exception is how getSingleResult() indicates it can't be found. Personally I can't stand this kind of API. It forces spurious exception handling for no real benefit. You just have to wrap the code in a try-catch block.

Alternatively you can query for a list and see if its empty. That doesn't throw an exception. Actually since you're not doing a primary key lookup technically there could be multiple results (even if one, both or the combination of your foreign keys or constraints makes this impossible in practice) so this is probably the more appropriate solution.

How to measure elapsed time

Per the Android docs SystemClock.elapsedRealtime() is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.

The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.

  • SystemClock.elapsedRealtime() and SystemClock.elapsedRealtimeNanos() are the best bet for calculating general purpose elapsed time.
  • SystemClock.uptimeMillis() and System.nanoTime() are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick with elapsedRealtime().
  • Stay away from System.currentTimeMillis() as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based on currentTimeMillis() to not always be accurate.

When the game starts:

long startTime = SystemClock.elapsedRealtime();

When the game ends:

long endTime = SystemClock.elapsedRealtime();
long elapsedMilliSeconds = endTime - startTime;
double elapsedSeconds = elapsedMilliSeconds / 1000.0;

Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis() as the basis of the time sent to setText(...).

Also, instead of using Timer, you might want to look into using TimerTask, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Please update your php.ini with

default_socket_timeout = 120

You can create your own php.ini if php is installed a CGI instead of a Apache module

Position DIV relative to another DIV?

You want to use position: absolute while inside the other div.

DEMO

When should I use semicolons in SQL Server?

If you like getting random Command Timeout errors in SQLServer then leave off the semi-colon at the end of your CommandText strings.

I don't know if this is documented anywhere or if it is a bug, but it does happen and I have learnt this from bitter experience.

I have verifiable and reproducible examples using SQLServer 2008.

aka -> In practice, always include the terminator even if you're just sending one statement to the database.

I can't install python-ldap

In FreeBSD 11:

pkg install openldap-client # for lber.h
pkg install cyrus-sasl # if you need sasl.h
pip install python-ldap

Detecting Enter keypress on VB.NET

In the KeyDown Event:

 If e.KeyCode = Keys.Enter Then
       Messagebox.Show("Enter key pressed")
 end if

How to prevent page scrolling when scrolling a DIV element?

Update 2: My solution is based on disabling the browser's native scrolling altogether (when cursor is inside the DIV) and then manually scrolling the DIV with JavaScript (by setting its .scrollTop property). An alternative and IMO better approach would be to only selectively disable the browser's scrolling in order to prevent the page scroll, but not the DIV scroll. Check out Rudie's answer below which demonstrates this solution.


Here you go:

$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
    var e0 = e.originalEvent,
        delta = e0.wheelDelta || -e0.detail;

    this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
    e.preventDefault();
});

Live demo: https://jsbin.com/howojuq/edit?js,output

So you manually set the scroll position and then just prevent the default behavior (which would be to scroll the DIV or whole web-page).

Update 1: As Chris noted in the comments below, in newer versions of jQuery, the delta information is nested within the .originalEvent object, i.e. jQuery does not expose it in its custom Event object anymore and we have to retrieve it from the native Event object instead.

groovy: safely find a key in a map and return its value

The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false, then you can do this:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"

if(mymap[key]) {
    println mymap[key]
}

However, if the value could potentially be Groovy-false, you should use:

if(mymap.containsKey(key)) {
    println mymap[key]
}

The easiest solution, though, if you know the value isn't going to be Groovy-false (or you can ignore that), and want a default value, is like this:

def value = mymap[key] ?: "default"

All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap (or LinkedHashMap) design that makes direct key access nearly instantaneous.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

You should use "merge a range of revision".

To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.

The same in the opposite way to merge a branch in the trunk.

About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

The cleanest way I found to do this is create a child of 'ThemeOverlay.AppCompat.Dark.ActionBar'. In the example, I set the Toolbar's background color to RED and text's color to BLUE.

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#FF0000</item>
    <item name="android:textColorPrimary">#0000FF</item>
</style>

You can then apply your theme to the toolbar:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:theme="@style/MyToolbar"
    android:minHeight="?attr/actionBarSize"/>

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

My problem was that I've had two paths on my PC that contained the same libraries. Both paths were added to the Additional Library Directories in Configuration Properties -> Linker -> General. Removing one of the paths solved the problem.

row-level trigger vs statement-level trigger

statement level trigger is only once for dml statement row leval trigger is for each row for dml statements

ListView with OnItemClickListener

If you want to enable item click in list view use

listitem.setClickable(false);

this may seem wrong at first glance but it works!

In MS DOS copying several files to one file

make sure you have mapped the y: drive, or copy all the files to local dir c:/local

c:/local> copy *.* c:/newfile.txt

Select 50 items from list at random to write to file

Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:

  1. Import the libraries
  2. Create the seed for random number generator, I have put it at 2
  3. Prepare a list of numbers from which to pick up in a random way
  4. Make the random choices from the numbers list

Code:

from random import seed
from random import choice

seed(2)
numbers = [i for i in range(100)]

print(numbers)

for _ in range(50):
    selection = choice(numbers)
    print(selection)