Programs & Examples On #Wstring

C++ standard library class to hold strings with wide characters. Behaves differently on Windows vs. Linux.

Case insensitive std::string.find()

I love the answers from Kiril V. Lyadvinsky and CC. but my problem was a little more specific than just case-insensitivity; I needed a lazy Unicode-supported command-line argument parser that could eliminate false-positives/negatives when dealing with alphanumeric string searches that could have special characters in the base string used to format alphanum keywords I was searching against, e.g., Wolfjäger shouldn't match jäger but <jäger> should.

It's basically just Kiril/CC's answer with extra handling for alphanumeric exact-length matches.

/* Undefined behavior when a non-alpha-num substring parameter is used. */
bool find_alphanum_string_CI(const std::wstring& baseString, const std::wstring& subString)
{
    /* Fail fast if the base string was smaller than what we're looking for */
    if (subString.length() > baseString.length()) 
        return false;

    auto it = std::search(
        baseString.begin(), baseString.end(), subString.begin(), subString.end(),
        [](char ch1, char ch2)
        {
            return std::toupper(ch1) == std::toupper(ch2);
        }
    );

    if(it == baseString.end())
        return false;

    size_t match_start_offset = it - baseString.begin();

    std::wstring match_start = baseString.substr(match_start_offset, std::wstring::npos);

    /* Typical special characters and whitespace to split the substring up. */
    size_t match_end_pos = match_start.find_first_of(L" ,<.>;:/?\'\"[{]}=+-_)(*&^%$#@!~`");

    /* Pass fast if the remainder of the base string where
       the match started is the same length as the substring. */
    if (match_end_pos == std::wstring::npos && match_start.length() == subString.length()) 
        return true;

    std::wstring extracted_match = match_start.substr(0, match_end_pos);

    return (extracted_match.length() == subString.length());
}

How to convert wstring into string?

Solution from: http://forums.devshed.com/c-programming-42/wstring-to-string-444006.html

std::wstring wide( L"Wide" ); 
std::string str( wide.begin(), wide.end() );

// Will print no problemo!
std::cout << str << std::endl;

Beware that there is no character set conversion going on here at all. What this does is simply to assign each iterated wchar_t to a char - a truncating conversion. It uses the std::string c'tor:

template< class InputIt >
basic_string( InputIt first, InputIt last,
              const Allocator& alloc = Allocator() );

As stated in comments:

values 0-127 are identical in virtually every encoding, so truncating values that are all less than 127 results in the same text. Put in a chinese character and you'll see the failure.

-

the values 128-255 of windows codepage 1252 (the Windows English default) and the values 128-255 of unicode are mostly the same, so if that's teh codepage you're using most of those characters should be truncated to the correct values. (I totally expected á and õ to work, I know our code at work relies on this for é, which I will soon fix)

And note that code points in the range 0x80 - 0x9F in Win1252 will not work. This includes , œ, ž, Ÿ, ...

std::wstring VS std::string

I recommend avoiding std::wstring on Windows or elsewhere, except when required by the interface, or anywhere near Windows API calls and respective encoding conversions as a syntactic sugar.

My view is summarized in http://utf8everywhere.org of which I am a co-author.

Unless your application is API-call-centric, e.g. mainly UI application, the suggestion is to store Unicode strings in std::string and encoded in UTF-8, performing conversion near API calls. The benefits outlined in the article outweigh the apparent annoyance of conversion, especially in complex applications. This is doubly so for multi-platform and library development.

And now, answering your questions:

  1. A few weak reasons. It exists for historical reasons, where widechars were believed to be the proper way of supporting Unicode. It is now used to interface APIs that prefer UTF-16 strings. I use them only in the direct vicinity of such API calls.
  2. This has nothing to do with std::string. It can hold whatever encoding you put in it. The only question is how You treat its content. My recommendation is UTF-8, so it will be able to hold all Unicode characters correctly. It's a common practice on Linux, but I think Windows programs should do it also.
  3. No.
  4. Wide character is a confusing name. In the early days of Unicode, there was a belief that a character can be encoded in two bytes, hence the name. Today, it stands for "any part of the character that is two bytes long". UTF-16 is seen as a sequence of such byte pairs (aka Wide characters). A character in UTF-16 takes either one or two pairs.

C++ Convert string (or char*) to wstring (or wchar_t*)

Based upon my own testing (On windows 8, vs2010) mbstowcs can actually damage original string, it works only with ANSI code page. If MultiByteToWideChar/WideCharToMultiByte can also cause string corruption - but they tends to replace characters which they don't know with '?' question marks, but mbstowcs tends to stop when it encounters unknown character and cut string at that very point. (I have tested Vietnamese characters on finnish windows).

So prefer Multi*-windows api function over analogue ansi C functions.

Also what I've noticed shortest way to encode string from one codepage to another is not use MultiByteToWideChar/WideCharToMultiByte api function calls but their analogue ATL macros: W2A / A2W.

So analogue function as mentioned above would sounds like:

wstring utf8toUtf16(const string & str)
{
   USES_CONVERSION;
   _acp = CP_UTF8;
   return A2W( str.c_str() );
}

_acp is declared in USES_CONVERSION macro.

Or also function which I often miss when performing old data conversion to new one:

string ansi2utf8( const string& s )
{
   USES_CONVERSION;
   _acp = CP_ACP;
   wchar_t* pw = A2W( s.c_str() );

   _acp = CP_UTF8;
   return W2A( pw );
}

But please notice that those macro's use heavily stack - don't use for loops or recursive loops for same function - after using W2A or A2W macro - better to return ASAP, so stack will be freed from temporary conversion.

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

How to kill MySQL connections

In MySQL Workbench:

Left-hand side navigator > Management > Client Connections

It gives you the option to kill queries and connections.

Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here

Java finished with non-zero exit value 2 - Android Gradle

In Your gradle.build file, Use this

"compile fileTree(dir: 'libs', include: ['*.jar'])"

And it works fine.

How can I close a window with Javascript on Mozilla Firefox 3?

function closeWindow() {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
    alert("This will close the window");
    window.open('','_self');
    window.close();
}

closeWindow();

What's "tools:context" in Android layout files?

This is best solution : https://developer.android.com/studio/write/tool-attributes

This is design attributes we can set activty context in xml like

tools:context=".activity.ActivityName"

Adapter:

tools:context="com.PackegaName.AdapterName"

enter image description here

You can navigate to java class when clicking on the marked icon and tools have more features like

tools:text=""
tools:visibility:""
tools:listItems=""//for recycler view 

etx

Understanding React-Redux and mapStateToProps()

This react & redux example is based off Mohamed Mellouki's example. But validates using prettify and linting rules. Note that we define our props and dispatch methods using PropTypes so that our compiler doesn't scream at us. This example also included some lines of code that had been missing in Mohamed's example. To use connect you will need to import it from react-redux. This example also binds the method filterItems this will prevent scope problems in the component. This source code has been auto formatted using JavaScript Prettify.

import React, { Component } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class ItemsContainer extends Component {
  constructor(props) {
    super(props);
    const { items, filters } = props;
    this.state = {
      items,
      filteredItems: filterItems(items, filters),
    };
    this.filterItems = this.filterItems.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    const { itmes } = this.state;
    const { filters } = nextProps;
    this.setState({ filteredItems: filterItems(items, filters) });
  }

  filterItems = (items, filters) => {
    /* return filtered list */
  };

  render() {
    return <View>/*display the filtered items */</View>;
  }
}

/*
define dispatch methods in propTypes so that they are validated.
*/
ItemsContainer.propTypes = {
  items: PropTypes.array.isRequired,
  filters: PropTypes.array.isRequired,
  onMyAction: PropTypes.func.isRequired,
};

/*
map state to props
*/
const mapStateToProps = state => ({
  items: state.App.Items.List,
  filters: state.App.Items.Filters,
});

/*
connect dispatch to props so that you can call the methods from the active props scope.
The defined method `onMyAction` can be called in the scope of the componets props.
*/
const mapDispatchToProps = dispatch => ({
  onMyAction: value => {
    dispatch(() => console.log(`${value}`));
  },
});

/* clean way of setting up the connect. */
export default connect(mapStateToProps, mapDispatchToProps)(ItemsContainer);

This example code is a good template for a starting place for your component.

How to delete a module in Android Studio

Assuming the following:

  • You are working with Android Studio 1.2.1 or 1.2.2 (I don't have the latest yet, will edit this again when I do).
  • Your Project Tool Window is displaying one of the following views: "Project", "Packages", "Android" or "Project Files"

You can delete an Android Studio module as follows:

  1. In the Project Tool Window click the module you want to delete.
  2. Between the Tool Bar and the Project Tool Window the tool bar you will see two "chips" that represent the path to the selected module, similar to: your-project-name > selected-module-name
  3. Right click on the selected-module-name chip. A context menu with multiple sections will appear. In the third section from the bottom there will be a section that contains "Reformat Code..", "Optimize Imports..." and "Delete".
  4. Select "Delete" and follow any prompts.

Replacing last character in a String with java

You can simply use :

if(fieldName.endsWith(","))
{
   StringUtils.chop(fieldName);
}

from commons-lang

creating charts with angularjs

I've created an angular directive for xCharts which is a nice js chart library http://tenxer.github.io/xcharts/. You can install it using bower, quite easy: https://github.com/radu-cigmaian/ng-xCharts

Highcharts is also a solution, but it is not free for comercial use.

JavaFX and OpenJDK

Try obuildfactory.

There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.

Until then enjoy, sir :)

Can regular expressions be used to match nested patterns?

No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a finite automaton.

You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).

There are many parser generators avialable, for instance ANTLR for Java. Finding an existing grammar for Java (or C) is also not difficult.
For more background: Automata Theory at Wikipedia

How does String substring work in Swift

I created a simple extension for this (Swift 3)

extension String {
    func substring(location: Int, length: Int) -> String? {
        guard characters.count >= location + length else { return nil }
        let start = index(startIndex, offsetBy: location)
        let end = index(startIndex, offsetBy: location + length)
        return substring(with: start..<end)
    }
}

How to wait for a process to terminate to execute another process in batch file

This is an updated version of aphoria's Answer.

I Replaced PSLIST and PSEXEC with TASKKILL and TASKLIST`. As they seem to work better, I couldn't get PSLIST to run in Windows 7.

Also replaced Sleep with TIMEOUT.

This Was everything i needed to get the script running well, and all the additions was provided by the great guys who posted the comments.

Also if there is a delay before the .exe starts it might be worth inserting a Timeout before the :loop.

@ECHO OFF

TASKKILL NOTEPAD

START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"

:LOOP
tasklist | find /i "WORDPAD" >nul 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
) ELSE (
  ECHO Wordpad is still running
  Timeout /T 5 /Nobreak
  GOTO LOOP
)

:CONTINUE
NOTEPAD

DataTables: Cannot read property 'length' of undefined

When you have JSON data then the following error appears enter image description here

A better solution is to assign a var data for the local json array object, details see: https://datatables.net/manual/tech-notes/4

This is helps you to display table contents.

 $(document).ready(function(){   

        $('#customer_table').DataTable( {
         "aaData": data,

           "aoColumns": [{
                            "mDataProp": "name_en"
                        }, {
                            "mDataProp": "phone"
                        }, {
                            "mDataProp": "email"
                        }, {
                            "mDataProp": "facebook"
                        }]
            });
        });

Java Does Not Equal (!=) Not Working?

You need to use the method equals() when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:

if (!statusCheck.equals("success")) {

How can I do an OrderBy with a dynamic string parameter?

If you are using plain LINQ-to-objects and don't want to take a dependency on an external library it is not hard to achieve what you want.

The OrderBy() clause accepts a Func<TSource, TKey> that gets a sort key from a source element. You can define the function outside the OrderBy() clause:

Func<Item, Object> orderByFunc = null;

You can then assign it to different values depending on the sort criteria:

if (sortOrder == SortOrder.SortByName)
  orderByFunc = item => item.Name;
else if (sortOrder == SortOrder.SortByRank)
  orderByFunc = item => item.Rank;

Then you can sort:

var sortedItems = items.OrderBy(orderByFunc);

This example assumes that the source type is Item that have properties Name and Rank.

Note that in this example TKey is Object to not constrain the property types that can be sorted on. If the func returns a value type (like Int32) it will get boxed when sorting and that is somewhat inefficient. If you can constrain TKey to a specific value type you can work around this problem.

How do you create a dropdownlist from an enum in ASP.NET MVC?

I know I'm late to the party on this, but thought you might find this variant useful, as this one also allows you to use descriptive strings rather than enumeration constants in the drop down. To do this, decorate each enumeration entry with a [System.ComponentModel.Description] attribute.

For example:

public enum TestEnum
{
  [Description("Full test")]
  FullTest,

  [Description("Incomplete or partial test")]
  PartialTest,

  [Description("No test performed")]
  None
}

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

 ...

 private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
    {
        Type realModelType = modelMetadata.ModelType;

        Type underlyingType = Nullable.GetUnderlyingType(realModelType);
        if (underlyingType != null)
        {
            realModelType = underlyingType;
        }
        return realModelType;
    }

    private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };

    public static string GetEnumDescription<TEnum>(TEnum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ((attributes != null) && (attributes.Length > 0))
            return attributes[0].Description;
        else
            return value.ToString();
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
    {
        return EnumDropDownListFor(htmlHelper, expression, null);
    }

    public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        Type enumType = GetNonNullableModelType(metadata);
        IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

        IEnumerable<SelectListItem> items = from value in values
            select new SelectListItem
            {
                Text = GetEnumDescription(value),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

        // If the enum is nullable, add an 'empty' item to the collection
        if (metadata.IsNullableValueType)
            items = SingleEmptyItem.Concat(items);

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

You can then do this in your view:

@Html.EnumDropDownListFor(model => model.MyEnumProperty)

Hope this helps you!

**EDIT 2014-JAN-23: Microsoft have just released MVC 5.1, which now has an EnumDropDownListFor feature. Sadly it does not appear to respect the [Description] attribute so the code above still stands.See Enum section in Microsoft's release notes for MVC 5.1.

Update: It does support the Display attribute [Display(Name = "Sample")] though, so one can use that.

[Update - just noticed this, and the code looks like an extended version of the code here: https://blogs.msdn.microsoft.com/stuartleeks/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums/, with a couple of additions. If so, attribution would seem fair ;-)]

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Unable to connect to any of the specified mysql hosts. C# MySQL

Update your connection string as shown below (without port variable as well):

MysqlConn.ConnectionString = "Server=127.0.0.1;Database=patholabs;Uid=pankaj;Pwd=master;"

Hope this helps...

How to git-cherry-pick only changes to certain files?

I usually use the -p flag with a git checkout from the other branch which I find easier and more granular than most other methods I have come across.

In principle:

git checkout <other_branch_name> <files/to/grab in/list/separated/by/spaces> -p

example:

git checkout mybranch config/important.yml app/models/important.rb -p

You then get a dialog asking you which changes you want in "blobs" this pretty much works out to every chunk of continuous code change which you can then signal y (Yes) n (No) etc for each chunk of code.

The -p or patch option works for a variety of commands in git including git stash save -p which allows you to choose what you want to stash from your current work

I sometimes use this technique when I have done a lot of work and would like to separate it out and commit in more topic based commits using git add -p and choosing what I want for each commit :)

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

I had the same problem when my plugin was depending on another project, which exported some packages in its manifest file. Instead of changing access rules, I have managed to solve the problem by adding the required packages into its Export-Package section. This makes the packages legally visible. Eclipse actually provides this fix on the "Access restriction" error marker.

All com.android.support libraries must use the exact same version specification

implementation 'com.android.support:appcompat-v7:26.1.0'

after this line You have to add new Line in your gradle

implementation 'com.android.support:design:26.1.0'

Capitalize the first letter of both words in a two word string

Alternative way with substring and regexpr:

substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))

Reading Xml with XmlReader in C#

My experience of XmlReader is that it's very easy to accidentally read too much. I know you've said you want to read it as quickly as possible, but have you tried using a DOM model instead? I've found that LINQ to XML makes XML work much much easier.

If your document is particularly huge, you can combine XmlReader and LINQ to XML by creating an XElement from an XmlReader for each of your "outer" elements in a streaming manner: this lets you do most of the conversion work in LINQ to XML, but still only need a small portion of the document in memory at any one time. Here's some sample code (adapted slightly from this blog post):

static IEnumerable<XElement> SimpleStreamAxis(string inputUrl,
                                              string elementName)
{
  using (XmlReader reader = XmlReader.Create(inputUrl))
  {
    reader.MoveToContent();
    while (reader.Read())
    {
      if (reader.NodeType == XmlNodeType.Element)
      {
        if (reader.Name == elementName)
        {
          XElement el = XNode.ReadFrom(reader) as XElement;
          if (el != null)
          {
            yield return el;
          }
        }
      }
    }
  }
}

I've used this to convert the StackOverflow user data (which is enormous) into another format before - it works very well.

EDIT from radarbob, reformatted by Jon - although it's not quite clear which "read too far" problem is being referred to...

This should simplify the nesting and take care of the "a read too far" problem.

using (XmlReader reader = XmlReader.Create(inputUrl))
{
    reader.ReadStartElement("theRootElement");

    while (reader.Name == "TheNodeIWant")
    {
        XElement el = (XElement) XNode.ReadFrom(reader);
    }

    reader.ReadEndElement();
}

This takes care of "a read too far" problem because it implements the classic while loop pattern:

initial read;
(while "we're not at the end") {
    do stuff;
    read;
}

how to upload a file to my server using html

<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
   <input id="fileupload" name="myfile" type="file" />
   <input type="submit" value="submit" id="submit" />
</form>

To upload a file, it is essential to set enctype="multipart/form-data" on your form

You need that form type and then some php to process the file :)

You should probably check out Uploadify if you want something very customisable out of the box.

creating custom tableview cells in swift

It is Purely swift notation an working for me

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cellIdentifier:String = "CustomFields"
        var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
        if (cell == nil)
        {
            var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
            cell = nib[0] as? CustomCell
        }
        return cell!
    }

IP to Location using Javascript

It's quite easy with an API that maps IP address to location. Run the snippet to get city & country for the IP in the input box.

_x000D_
_x000D_
$('.send').on('click', function(){_x000D_
_x000D_
  $.getJSON('https://ipapi.co/'+$('.ip').val()+'/json', function(data){_x000D_
      $('.city').text(data.city);_x000D_
      $('.country').text(data.country);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input class="ip" value="8.8.8.8">_x000D_
<button class="send">Go</button>_x000D_
<br><br>_x000D_
<span class="city"></span>, _x000D_
<span class="country"></span>
_x000D_
_x000D_
_x000D_

Android: Background Image Size (in Pixel) which Support All Devices

Android Devices Matrices

                            ldpi     mdpi     hdpi    xhdpi    xxhdpi      xxxhdpi
Launcher And Home           36*36    48*48   72*72    96*96    144*144     192*192
Toolbar And Tab             24*24    32*32   48*48    64*64    96*96       128*128
Notification                18*18    24*24   36*36    48*48    72*72       96*96 
Background                 240*320  320*480 480*800  768*1280  1080 *1920  1440*2560 

(For good approach minus Toolbar Size From total height of Background Screen and then Design Graphics of Screens )

For More Help (This link includes tablets also):

https://design.google.com/devices/

Android Native Icons (Recommended) You can change color of these icons programmatically. https://design.google.com/icons/

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;

or maybe

shutdown abort;

or maybe

lsnrctl stop

lsnrctl start

How do I do a case-insensitive string comparison?

How about converting to lowercase first? you can use string.lower().

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

Can enums be subclassed to add new elements?

In the hopes this elegant solution of a colleague of mine is even seen in this long post I'd like to share this approach for subclassing which follows the interface approach and beyond.

Please be aware that we use custom exceptions here and this code won't compile unless you replace it with your exceptions.

The documentation is extensive and I hope it's understandable for most of you.

The interface that every subclassed enum needs to implement.

public interface Parameter {
  /**
   * Retrieve the parameters name.
   *
   * @return the name of the parameter
   */
  String getName();

  /**
   * Retrieve the parameters type.
   *
   * @return the {@link Class} according to the type of the parameter
   */
  Class<?> getType();

  /**
   * Matches the given string with this parameters value pattern (if applicable). This helps to find
   * out if the given string is a syntactically valid candidate for this parameters value.
   *
   * @param valueStr <i>optional</i> - the string to check for
   * @return <code>true</code> in case this parameter has no pattern defined or the given string
   *         matches the defined one, <code>false</code> in case <code>valueStr</code> is
   *         <code>null</code> or an existing pattern is not matched
   */
  boolean match(final String valueStr);

  /**
   * This method works as {@link #match(String)} but throws an exception if not matched.
   *
   * @param valueStr <i>optional</i> - the string to check for
   * @throws ArgumentException with code
   *           <dl>
   *           <dt>PARAM_MISSED</dt>
   *           <dd>if <code>valueStr</code> is <code>null</code></dd>
   *           <dt>PARAM_BAD</dt>
   *           <dd>if pattern is not matched</dd>
   *           </dl>
   */
  void matchEx(final String valueStr) throws ArgumentException;

  /**
   * Parses a value for this parameter from the given string. This method honors the parameters data
   * type and potentially other criteria defining a valid value (e.g. a pattern).
   *
   * @param valueStr <i>optional</i> - the string to parse the parameter value from
   * @return the parameter value according to the parameters type (see {@link #getType()}) or
   *         <code>null</code> in case <code>valueStr</code> was <code>null</code>.
   * @throws ArgumentException in case <code>valueStr</code> is not parsable as a value for this
   *           parameter.
   */
  Object parse(final String valueStr) throws ArgumentException;

  /**
   * Converts the given value to its external form as it is accepted by {@link #parse(String)}. For
   * most (ordinary) parameters this is simply a call to {@link String#valueOf(Object)}. In case the
   * parameter types {@link Object#toString()} method does not return the external form (e.g. for
   * enumerations), this method has to be implemented accordingly.
   *
   * @param value <i>mandatory</i> - the parameters value
   * @return the external form of the parameters value, never <code>null</code>
   * @throws InternalServiceException in case the given <code>value</code> does not match
   *           {@link #getType()}
   */
  String toString(final Object value) throws InternalServiceException;
}

The implementing ENUM base class.

public enum Parameters implements Parameter {
  /**
   * ANY ENUM VALUE
   */
  VALUE(new ParameterImpl<String>("VALUE", String.class, "[A-Za-z]{3,10}"));

  /**
   * The parameter wrapped by this enum constant.
   */
  private Parameter param;

  /**
   * Constructor.
   *
   * @param param <i>mandatory</i> - the value for {@link #param}
   */
  private Parameters(final Parameter param) {
    this.param = param;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getName() {
    return this.param.getName();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getType() {
    return this.param.getType();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    return this.param.match(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) {
    this.param.matchEx(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object parse(final String valueStr) throws ArgumentException {
    return this.param.parse(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString(final Object value) throws InternalServiceException {
    return this.param.toString(value);
  }
}

The subclassed ENUM which "inherits" from base class.

public enum ExtendedParameters implements Parameter {
  /**
   * ANY ENUM VALUE
   */
  VALUE(my.package.name.VALUE);

  /**
   * EXTENDED ENUM VALUE
   */
  EXTENDED_VALUE(new ParameterImpl<String>("EXTENDED_VALUE", String.class, "[0-9A-Za-z_.-]{1,20}"));

  /**
   * The parameter wrapped by this enum constant.
   */
  private Parameter param;

  /**
   * Constructor.
   *
   * @param param <i>mandatory</i> - the value for {@link #param}
   */
  private Parameters(final Parameter param) {
    this.param = param;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String getName() {
    return this.param.getName();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Class<?> getType() {
    return this.param.getType();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    return this.param.match(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) {
    this.param.matchEx(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object parse(final String valueStr) throws ArgumentException {
    return this.param.parse(valueStr);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString(final Object value) throws InternalServiceException {
    return this.param.toString(value);
  }
}

Finally the generic ParameterImpl to add some utilities.

public class ParameterImpl<T> implements Parameter {
  /**
   * The default pattern for numeric (integer, long) parameters.
   */
  private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");

  /**
   * The default pattern for parameters of type boolean.
   */
  private static final Pattern BOOLEAN_PATTERN = Pattern.compile("0|1|true|false");

  /**
   * The name of the parameter, never <code>null</code>.
   */
  private final String name;

  /**
   * The data type of the parameter.
   */
  private final Class<T> type;

  /**
   * The validation pattern for the parameters values. This may be <code>null</code>.
   */
  private final Pattern validator;

  /**
   * Shortcut constructor without <code>validatorPattern</code>.
   *
   * @param name <i>mandatory</i> - the value for {@link #name}
   * @param type <i>mandatory</i> - the value for {@link #type}
   */
  public ParameterImpl(final String name, final Class<T> type) {
    this(name, type, null);
  }

  /**
   * Constructor.
   *
   * @param name <i>mandatory</i> - the value for {@link #name}
   * @param type <i>mandatory</i> - the value for {@link #type}
   * @param validatorPattern - <i>optional</i> - the pattern for {@link #validator}
   *          <dl>
   *          <dt style="margin-top:0.25cm;"><i>Note:</i>
   *          <dd>The default validation patterns {@link #NUMBER_PATTERN} or
   *          {@link #BOOLEAN_PATTERN} are applied accordingly.
   *          </dl>
   */
  public ParameterImpl(final String name, final Class<T> type, final String validatorPattern) {
    this.name = name;
    this.type = type;
    if (null != validatorPattern) {
      this.validator = Pattern.compile(validatorPattern);

    } else if (Integer.class == this.type || Long.class == this.type) {
      this.validator = NUMBER_PATTERN;
    } else if (Boolean.class == this.type) {
      this.validator = BOOLEAN_PATTERN;
    } else {
      this.validator = null;
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public boolean match(final String valueStr) {
    if (null == valueStr) {
      return false;
    }
    if (null != this.validator) {
      final Matcher matcher = this.validator.matcher(valueStr);
      return matcher.matches();
    }
    return true;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void matchEx(final String valueStr) throws ArgumentException {
    if (false == this.match(valueStr)) {
      if (null == valueStr) {
        throw ArgumentException.createEx(ErrorCode.PARAM_MISSED, "The value must not be null",
            this.name);
      }
      throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value must match the pattern: "
          + this.validator.pattern(), this.name);
    }
  }

  /**
   * Parse the parameters value from the given string value according to {@link #type}. Additional
   * the value is checked by {@link #matchEx(String)}.
   *
   * @param valueStr <i>optional</i> - the string value to parse the value from
   * @return the parsed value, may be <code>null</code>
   * @throws ArgumentException in case the parameter:
   *           <ul>
   *           <li>does not {@link #matchEx(String)} the {@link #validator}</li>
   *           <li>cannot be parsed according to {@link #type}</li>
   *           </ul>
   * @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
   *           programming error.
   */
  @Override
  public T parse(final String valueStr) throws ArgumentException, InternalServiceException {
    if (null == valueStr) {
      return null;
    }
    this.matchEx(valueStr);

    if (String.class == this.type) {
      return this.type.cast(valueStr);
    }
    if (Boolean.class == this.type) {
      return this.type.cast(Boolean.valueOf(("1".equals(valueStr)) || Boolean.valueOf(valueStr)));
    }
    try {
      if (Integer.class == this.type) {
        return this.type.cast(Integer.valueOf(valueStr));
      }
      if (Long.class == this.type) {
        return this.type.cast(Long.valueOf(valueStr));
      }
    } catch (final NumberFormatException e) {
      throw ArgumentException.createEx(ErrorCode.PARAM_BAD, "The value cannot be parsed as "
          + this.type.getSimpleName().toLowerCase() + ".", this.name);
    }

    return this.parseOther(valueStr);
  }

  /**
   * Field access for {@link #name}.
   *
   * @return the value of {@link #name}.
   */
  @Override
  public String getName() {
    return this.name;
  }

  /**
   * Field access for {@link #type}.
   *
   * @return the value of {@link #type}.
   */
  @Override
  public Class<T> getType() {
    return this.type;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public final String toString(final Object value) throws InternalServiceException {
    if (false == this.type.isAssignableFrom(value.getClass())) {
      throw new InternalServiceException(ErrorCode.PANIC,
          "Parameter.toString(): Bad type of value. Expected {0} but is {1}.", this.type.getName(),
          value.getClass().getName());
    }
    if (String.class == this.type || Integer.class == this.type || Long.class == this.type) {
      return String.valueOf(value);
    }
    if (Boolean.class == this.type) {
      return Boolean.TRUE.equals(value) ? "1" : "0";
    }

    return this.toStringOther(value);
  }

  /**
   * Parse parameter values of other (non standard types). This method is called by
   * {@link #parse(String)} in case {@link #type} is none of the supported standard types (currently
   * String, Boolean, Integer and Long). It is intended for extensions.
   * <dl>
   * <dt style="margin-top:0.25cm;"><i>Note:</i>
   * <dd>This default implementation always throws an InternalServiceException.
   * </dl>
   *
   * @param valueStr <i>mandatory</i> - the string value to parse the value from
   * @return the parsed value, may be <code>null</code>
   * @throws ArgumentException in case the parameter cannot be parsed according to {@link #type}
   * @throws InternalServiceException in case the type {@link #type} cannot be handled. This is a
   *           programming error.
   */
  protected T parseOther(final String valueStr) throws ArgumentException, InternalServiceException {
    throw new InternalServiceException(ErrorCode.PANIC,
        "ParameterImpl.parseOther(): Unsupported parameter type: " + this.type.getName());
  }

  /**
   * Convert the values of other (non standard types) to their external form. This method is called
   * by {@link #toString(Object)} in case {@link #type} is none of the supported standard types
   * (currently String, Boolean, Integer and Long). It is intended for extensions.
   * <dl>
   * <dt style="margin-top:0.25cm;"><i>Note:</i>
   * <dd>This default implementation always throws an InternalServiceException.
   * </dl>
   *
   * @param value <i>mandatory</i> - the parameters value
   * @return the external form of the parameters value, never <code>null</code>
   * @throws InternalServiceException in case the given <code>value</code> does not match
   *           {@link #getClass()}
   */
  protected String toStringOther(final Object value) throws InternalServiceException {
    throw new InternalServiceException(ErrorCode.PANIC,
        "ParameterImpl.toStringOther(): Unsupported parameter type: " + this.type.getName());
  }
}

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

Defined Edges With CSS3 Filter Blur

I used -webkit-transform: translate3d(0, 0, 0); with overflow:hidden;.

DOM:

<div class="parent">
    <img class="child" src="http://placekitten.com/100" />
</div>

CSS:

.parent {
    width: 100px;
    height: 100px;
    overflow: hidden;
    -webkit-transform: translate3d(0, 0, 0);
}
.child {
    -webkit-filter: blur(10px);
}

DEMO: http://jsfiddle.net/DA5L4/18/

This technic works on Chrome34 and iOS7.1

Update

http://jsfiddle.net/DA5L4/50/

if you use latest version of Chrome, you don't need to use -webkit-transform: translate3d(0, 0, 0); hack. But it doesn't works on Safari(webkit).

Javascript - Append HTML to container element without innerHTML

alnafie has a great answer for this question. I wanted to give an example of his code for reference:

_x000D_
_x000D_
var childNumber = 3;_x000D_
_x000D_
function addChild() {_x000D_
  var parent = document.getElementById('i-want-more-children');_x000D_
  var newChild = '<p>Child ' + childNumber + '</p>';_x000D_
  parent.insertAdjacentHTML('beforeend', newChild);_x000D_
  childNumber++;_x000D_
}
_x000D_
body {_x000D_
  text-align: center;_x000D_
}_x000D_
button {_x000D_
  background: rgba(7, 99, 53, .1);_x000D_
  border: 3px solid rgba(7, 99, 53, 1);_x000D_
  border-radius: 5px;_x000D_
  color: rgba(7, 99, 53, 1);_x000D_
  cursor: pointer;_x000D_
  line-height: 40px;_x000D_
  font-size: 30px;_x000D_
  outline: none;_x000D_
  padding: 0 20px;_x000D_
  transition: all .3s;_x000D_
}_x000D_
button:hover {_x000D_
  background: rgba(7, 99, 53, 1);_x000D_
  color: rgba(255,255,255,1);_x000D_
}_x000D_
p {_x000D_
  font-size: 20px;_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<button type="button" onclick="addChild()">Append Child</button>_x000D_
<div id="i-want-more-children">_x000D_
  <p>Child 1</p>_x000D_
  <p>Child 2</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hopefully this is helpful to others.

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

How should I read a file line-by-line in Python?

Yes,

with open('filename.txt') as fp:
    for line in fp:
        print line

is the way to go.

It is not more verbose. It is more safe.

com.jcraft.jsch.JSchException: UnknownHostKey

Depending on what program you use for ssh, the way to get the proper key could vary. Putty (popular with Windows) uses their own format for ssh keys. With most variants of Linux and BSD that I've seen, you just have to look in ~/.ssh/known_hosts. I usually ssh from a Linux machine and then copy this file to a Windows machine. Then I use something similar to

jsch.setKnownHosts("C:\\Users\\cabbott\\known_hosts");

Assuming I have placed the file in C:\Users\cabbott on my Windows machine. If you don't have access to a Linux machine, try http://www.cygwin.com/

Maybe someone else can suggest another Windows alternative. I find putty's way of handling SSH keys by storing them in the registry in a non-standard format bothersome to extract.

Determine if a String is an Integer in Java

Or you can enlist a little help from our good friends at Apache Commons : StringUtils.isNumeric(String str)

How to programmatically round corners and set random background colors

I think the fastest way to do this is:

GradientDrawable gradientDrawable = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction 
            new int[] {0xFF757775,0xFF151515}); //set the color of gradient
gradientDrawable.setCornerRadius(10f); //set corner radius

//Apply background to your view
View view = (RelativeLayout) findViewById( R.id.my_view );
if(Build.VERSION.SDK_INT>=16)
     view.setBackground(gradientDrawable);
else view.setBackgroundDrawable(gradientDrawable);    

How to add a new schema to sql server 2008?

Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."

Split a large pandas dataframe

I wanted to do the same, and I had first problems with the split function, then problems with installing pandas 0.15.2, so I went back to my old version, and wrote a little function that works very well. I hope this can help!

# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000): 
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i*chunk_size:(i+1)*chunk_size])
    return chunks

jquery function val() is not equivalent to "$(this).value="?

You want:

this.value = ''; // straight JS, no jQuery

or

$(this).val(''); // jQuery

With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.

How to check if a variable is a dictionary in Python?

You could use if type(ele) is dict or use isinstance(ele, dict) which would work if you had subclassed dict:

d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k,' ',v)

Cannot create SSPI context

In vb.net, if you are using a linked server than check your connection string. Integrated Security=true; doesn't work in all SQL providers, it throws an exception when used with the OleDb provider. So basically Integrated Security=SSPI; is preferred since works with both SQLClient & OleDB provide. If you still hit with error, remove the syntax completely.

How to use SQL LIKE condition with multiple values in PostgreSQL?

Perhaps using SIMILAR TO would work ?

SELECT * from table WHERE column SIMILAR TO '(AAA|BBB|CCC)%';

Fatal error: Class 'PHPMailer' not found

I suggest you look into getting composer. https://getcomposer.org Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.

Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php

Delete your C:\Inetpub\wwwroot\php\PHPMailer\ directory.

Use composer.phar to get the phpmailer package using the command line to execute

cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer

After it is finished it will create a C:\Inetpub\wwwroot\php\vendor directory along with all of the phpmailer files and generate an autoloader.

Next in your main project configuration file you need to include the autoload file.

require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';

The vendor\autoload.php will include the information for you to use $mail = new \PHPMailer;

Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer

How to move/rename a file using an Ansible task on a remote system

- name: Move the src file to dest
  command: mv /path/to/src /path/to/dest
  args:
    removes: /path/to/src
    creates: /path/to/dest

This runs the mv command only when /path/to/src exists and /path/to/dest does not, so it runs once per host, moves the file, then doesn't run again.

I use this method when I need to move a file or directory on several hundred hosts, many of which may be powered off at any given time. It's idempotent and safe to leave in a playbook.

Compare two date formats in javascript/jquery

To comapre dates of string format (mm-dd-yyyy).

    var job_start_date = "10-1-2014"; // Oct 1, 2014
    var job_end_date = "11-1-2014"; // Nov 1, 2014
    job_start_date = job_start_date.split('-');
    job_end_date = job_end_date.split('-');

    var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
    var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);

    if(new_end_date <= new_start_date) {
      // your code
    }

How to set up gradle and android studio to do release build?

  1. open the Build Variants pane, typically found along the lower left side of the window:

Build Variants

  1. set debug to release
  2. shift+f10 run!!

then, Android Studio will execute assembleRelease task and install xx-release.apk to your device.

Adding delay between execution of two following lines

You can use gcd to do this without having to create another method

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
  NSLog(@"Do some work");
});

You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions

Bootstrap Accordion button toggle "data-parent" not working

If found this alteration to Krzysztof answer helped my issue

$('#' + parentId + ' .collapse').on('show.bs.collapse', function (e) {            
    var all = $('#' + parentId).find('.collapse');
    var actives = $('#' + parentId).find('.in, .collapsing');
    all.each(function (index, element) {
      $(element).collapse('hide');
    })
    actives.each(function (index, element) {                
      $(element).collapse('show');                
    })
})    

if you have nested panels then you may also need to specify which ones by adding another class name to distinguish between them and add this to the a selector in the above JavaScript

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

How do I open an .exe from another C++ .exe?

Provide the full path of the file openfile.exe and remember not to put forward slash / in the path such as c:/users/username/etc.... instead of that use c:\\Users\\username\etc (for windows)

May be this will help you.

How to get row number in dataframe in Pandas?

You can simply use shape method df[df['LastName'] == 'Smith'].shape

Output
(1,1)

Which indicates 1 row and 1 column. This way you can get the idea of whole datasets

Let me explain the above code DataframeName[DataframeName['Column_name'] == 'Value to match in column']

not None test in Python

From, Programming Recommendations, PEP 8:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

PEP 8 is essential reading for any Python programmer.

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

SOAP PHP fault parsing WSDL: failed to load external entity?

If you use docker there is a chance you get error because of OpenSSL default security level.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876

After that change I can run SoapClient without any additional options


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Selenium IDE - Command to wait for 5 seconds

In Chrome, For "Selenium IDE", I was also struggling that it doesn't pause. It will pause, if you give as below:

  • Command: pause
  • Target: blank
  • Value: 10000

This will pause for 10 seconds.

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Shortcut to comment out a block of code with sublime text

Just in case someone is using the Portuguese ABNT keyboard layout The shortcut is

Ctrl + ;

Container is running beyond memory limits

We also faced this issue recently. If the issue is related to mapper memory, couple of things I would like to suggest that needs to be checked are.

  • Check if combiner is enabled or not? If yes, then it means that reduce logic has to be run on all the records (output of mapper). This happens in memory. Based on your application you need to check if enabling combiner helps or not. Trade off is between the network transfer bytes and time taken/memory/CPU for the reduce logic on 'X' number of records.
    • If you feel that combiner is not much of value, just disable it.
    • If you need combiner and 'X' is a huge number (say millions of records) then considering changing your split logic (For default input formats use less block size, normally 1 block size = 1 split) to map less number of records to a single mapper.
  • Number of records getting processed in a single mapper. Remember that all these records need to be sorted in memory (output of mapper is sorted). Consider setting mapreduce.task.io.sort.mb (default is 200MB) to a higher value if needed. mapred-configs.xml
  • If any of the above didn't help, try to run the mapper logic as a standalone application and profile the application using a Profiler (like JProfiler) and see where the memory getting used. This can give you very good insights.

Remove ALL white spaces from text

Using .replace(/\s+/g,'') works fine;

Example:

this.slug = removeAccent(this.slug).replace(/\s+/g,'');

Drop primary key using script in SQL Server database

The answer I got is that variables and subqueries will not work and we have to user dynamic SQL script. The following works:

DECLARE @SQL VARCHAR(4000)
SET @SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '

SET @SQL = REPLACE(@SQL, '|ConstraintName|', ( SELECT   name
                                               FROM     sysobjects
                                               WHERE    xtype = 'PK'
                                                        AND parent_obj =        OBJECT_ID('Student')))

EXEC (@SQL)

Getting URL hash location, and using it in jQuery

location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL

var hash = document.URL.substr(document.URL.indexOf('#')+1) 

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).

FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

How to get domain root url in Laravel 4?

You also may test any of these:

Request::server ("SERVER_NAME")
Request::server ("HTTP_HOST")

It seems better than making any treatment of

Request::root()

All right.

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I tried the steps mentioned by @bcmoney but for me the current version was already set to the latest version. In my it was Java8.

I had various versions of java installed (java6, java7 and java8). I got the same error but instead of 1.5 and 1.7 i got 1.7 and 1.8. I uninstalled java6 on my windows 8.1 machine. After which i tried java -version in command prompt and the error did not appear.

I am not sure whether this is the right answer but it worked for me so i thought it would help the community too.

Is there a way to change the spacing between legend items in ggplot2?

From Koshke's work on ggplot2 and his blog (Koshke's blog)

... + theme(legend.key.height=unit(3,"line")) # Change 3 to X
... + theme(legend.key.width=unit(3,"line")) # Change 3 to X

Type theme_get() in the console to see other editable legend attributes.

Check file extension in upload form in PHP

i think this might work for you

//<?php
    //checks file extension for images only
    $allowed =  array('gif','png' ,'jpg');
    $file = $_FILES['file']['name'];
    $ext = pathinfo($file, PATHINFO_EXTENSION);
        if(!in_array($ext,$allowed) ) 
            { 
//?>
<script>
       alert('file extension not allowed');
       window.location.href='some_link.php?file_type_not_allowed_error';
</script>

//<?php
exit(0);
    }
//?>

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

You're asking kind of a two-part question. As far as syntax (I think since PHP4?) you can use:

<?=$var?>

... if PHP is configured to allow it. And it is on most servers.

As far as storing user data, you also have the option of storing it in the session:

$_SESSION['bla'] = "so-and-so";

for persistence from page to page. You could also of course use a database. You can even have PHP store the session variables in the db. It just depends on what you need.

No == operator found while comparing structs in C++

Comparison doesn't work on structs in C or C++. Compare by fields instead.

How to use phpexcel to read data and insert into database?

    if($this->mng_auth->get_language()=='en')
          {
                    $excel->getActiveSheet()->setRightToLeft(false); 
          }
                else
                {  
                    $excel->getActiveSheet()->setRightToLeft(true); 
                }

       $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                            'color' => array('argb' => '00000000'),
                    ),
                ),
            );

          //SET property
          $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->applyFromArray($styleArray);


    $objPHPExcel->getActiveSheet()->getStyle('A1:M10001')->getAlignment()->setWrapText(true); 


$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->applyFromArray($styleArray);  

$objPHPExcel->getActiveSheet()->getStyle('A1:'.chr(65+count($fields)-1).$query->num_rows())->getAlignment()->setWrapText(true); 

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

i think it because cv2.imread cannot read .jpg picture, you need to change .jpg to .png.

Drop multiple tables in one shot in MySQL

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

Computed / calculated / virtual / derived columns in PostgreSQL

Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.

STORED generated columns are introduced with Postgres 12. Trivial example:

CREATE TABLE tbl (
  int1    int
, int2    int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);

db<>fiddle here

VIRTUAL generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .

Related:


Until then, you can emulate VIRTUAL generated columns with a function using attribute notation (tbl.col) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:

The expression (looking like a column) is not included in a SELECT * FROM tbl, though. You always have to list it explicitly.

Can also be supported with a matching expression index - provided the function is IMMUTABLE. Like:

CREATE FUNCTION col(tbl) ... AS ...  -- your computed expression here
CREATE INDEX ON tbl(col(tbl));

Alternatives

Alternatively, you can implement similar functionality with a VIEW, optionally coupled with expression indexes. Then SELECT * can include the generated column.

"Persisted" (STORED) computed columns can be implemented with triggers in a functionally identical way.

Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

modal View controllers - how to display and dismiss

Example in Swift, picturing the foundry's explanation above and the Apple's documentation:

  1. Basing on the Apple's documentation and the foundry's explanation above (correcting some errors), presentViewController version using delegate design pattern:

ViewController.swift

import UIKit

protocol ViewControllerProtocol {
    func dismissViewController1AndPresentViewController2()
}

class ViewController: UIViewController, ViewControllerProtocol {

    @IBAction func goToViewController1BtnPressed(sender: UIButton) {
        let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
        vc1.delegate = self
        vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
        self.presentViewController(vc1, animated: true, completion: nil)
    }

    func dismissViewController1AndPresentViewController2() {
        self.dismissViewControllerAnimated(false, completion: { () -> Void in
            let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
            self.presentViewController(vc2, animated: true, completion: nil)
        })
    }

}

ViewController1.swift

import UIKit

class ViewController1: UIViewController {

    var delegate: protocol<ViewControllerProtocol>!

    @IBAction func goToViewController2(sender: UIButton) {
        self.delegate.dismissViewController1AndPresentViewController2()
    }

}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

}
  1. Basing on the foundry's explanation above (correcting some errors), pushViewController version using delegate design pattern:

ViewController.swift

import UIKit

protocol ViewControllerProtocol {
    func popViewController1AndPushViewController2()
}

class ViewController: UIViewController, ViewControllerProtocol {

    @IBAction func goToViewController1BtnPressed(sender: UIButton) {
        let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
        vc1.delegate = self
        self.navigationController?.pushViewController(vc1, animated: true)
    }

    func popViewController1AndPushViewController2() {
        self.navigationController?.popViewControllerAnimated(false)
        let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
        self.navigationController?.pushViewController(vc2, animated: true)
    }

}

ViewController1.swift

import UIKit

class ViewController1: UIViewController {

    var delegate: protocol<ViewControllerProtocol>!

    @IBAction func goToViewController2(sender: UIButton) {
        self.delegate.popViewController1AndPushViewController2()
    }

}

ViewController2.swift

import UIKit

class ViewController2: UIViewController {

}

HTML Script tag: type or language (or omit both)?

The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.

The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

show validation error messages on submit in angularjs

You only need to check if the form is dirty and valid before submitting it. Checkout the following code.

<form name="frmRegister" data-ng-submit="frmRegister.$valid && frmRegister.$dirty ? register() : return false;" novalidate>      

And also you can disable your submit button with the following change:

<input type="submit" value="Save" data-ng-disable="frmRegister.$invalid || !frmRegister.$dirty" />

This should help for your initial

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

I was having this issue with requirejs using the newest boostrap 4 build. I ended up just defining:

<script>
  window.Tether = {};
</script>

in my html head tag to fool bootstrap's check. I then added a second require statement just before the require that loads my app, and subsequently, my bootstrap dependency:

require(['tether'], function (Tether) {
  window.Tether = Tether;
});

require([
  "app",
], function(App){
  App.initialize();
});

Using both of these in tandem and you should have no problem using current bootstrap 4 alpha build.

Why does the Google Play store say my Android app is incompatible with my own device?

I also had the same problem. I published an App in Test mode created with React Native 59. it wasn't compatible for certain tester. The message wasn't clear about why the app is not compatible , after i figured out that i restricted the app to be available only for certain country . that was the problem, but as i said the message wasn't clear. in Play Store WebApp the message is: "this app is not compatible with your device". in the mobile app the message "This app is not available in your country"

What is the maximum length of a table name in Oracle?

Teach a man to fish

Notice the data-type and size

>describe all_tab_columns

VIEW all_tab_columns

Name                                      Null?    Type                        
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)                
 TABLE_NAME                                NOT NULL VARCHAR2(30)                
 COLUMN_NAME                               NOT NULL VARCHAR2(30)                
 DATA_TYPE                                          VARCHAR2(106)               
 DATA_TYPE_MOD                                      VARCHAR2(3)                 
 DATA_TYPE_OWNER                                    VARCHAR2(30)                
 DATA_LENGTH                               NOT NULL NUMBER                      
 DATA_PRECISION                                     NUMBER                      
 DATA_SCALE                                         NUMBER                      
 NULLABLE                                           VARCHAR2(1)                 
 COLUMN_ID                                          NUMBER                      
 DEFAULT_LENGTH                                     NUMBER                      
 DATA_DEFAULT                                       LONG                        
 NUM_DISTINCT                                       NUMBER                      
 LOW_VALUE                                          RAW(32)                     
 HIGH_VALUE                                         RAW(32)                     
 DENSITY                                            NUMBER                      
 NUM_NULLS                                          NUMBER                      
 NUM_BUCKETS                                        NUMBER                      
 LAST_ANALYZED                                      DATE                        
 SAMPLE_SIZE                                        NUMBER                      
 CHARACTER_SET_NAME                                 VARCHAR2(44)                
 CHAR_COL_DECL_LENGTH                               NUMBER                      
 GLOBAL_STATS                                       VARCHAR2(3)                 
 USER_STATS                                         VARCHAR2(3)                 
 AVG_COL_LEN                                        NUMBER                      
 CHAR_LENGTH                                        NUMBER                      
 CHAR_USED                                          VARCHAR2(1)                 
 V80_FMT_IMAGE                                      VARCHAR2(3)                 
 DATA_UPGRADED                                      VARCHAR2(3)                 
 HISTOGRAM                                          VARCHAR2(15)                

Python: convert string from UTF-8 to Latin-1

Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:

>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'

Save file/open file dialog box, using Swing & Netbeans GUI editor

saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html

Vector of structs initialization

After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

But I found new to do this using default_structure_element like following...

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

typedef struct subject {
  string name;
  int marks;
  int credits;
}subject;

int main(){
  subject default_subject;
  default_subject.name="NONE";
  default_subject.marks = 0;
  default_subject.credits = 0;

  vector <subject> sub(10,default_subject);         // default_subject to initialize

  //to check is it initialised
  for(ll i=0;i<sub.size();i++) {
    cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
  } 
}

Then I think its good to way to initialize a vector of the struct, isn't it?

pgadmin4 : postgresql application server could not be contacted.

Deleting the contents of C:\Users\%USERNAME%\AppData\Roaming\pgAdmin directory worked for me!

Using jQuery to test if an input has focus

There is no :focus, but there is :selected http://docs.jquery.com/Selectors/selected

but if you want to change how things look based on what is selected you should probably be working with the blur events.

http://docs.jquery.com/Events/blur

Highcharts - how to have a chart with dynamic height?

Just don't set the height property in HighCharts and it will handle it dynamically for you so long as you set a height on the chart's containing element. It can be a fixed number or a even a percent if position is absolute.

Highcharts docs:

By default the height is calculated from the offset height of the containing element

Example: http://jsfiddle.net/wkkAd/149/

#container {
    height:100%;
    width:100%;
    position:absolute;
}

How do I save and restore multiple variables in python?

You should look at the shelve and pickle modules. If you need to store a lot of data it may be better to use a database

Android Camera : data intent returns null

The default Android camera application returns a non-null intent only when passing back a thumbnail in the returned Intent. If you pass EXTRA_OUTPUT with a URI to write to, it will return a null intent and the picture is in the URI that you passed in.

You can verify this by looking at the camera app's source code on GitHub:

I would guess that you're either passing in EXTRA_OUTPUT somehow, or the camera app on your phone works differently.

How to automatically close cmd window after batch file execution?

Just try /s as listed below.

As the last line in the batch file type:

exit /s

The above command will close the Windows CMD window.

/s - stands for silent as in (it would wait for an input from the keyboard).

Make elasticsearch only return certain fields?

There are several methods that can be useful to achieve field-specific results. One can be through the source method. And another method that can also be useful to receive cleaner and more summarized answers according to our interests is filter_path:

Document Json:

"hits" : [
  {
    "_index" : "xxxxxx",
    "_type" : "_doc",
    "_id" : "xxxxxx",
    "_score" : xxxxxx,
    "_source" : {
      "year" : 2020,
      "created_at" : "2020-01-29",
      "url" : "www.github.com/mbarr0987",
      "name":"github"
    }
  }

Query:

GET bot1/_search?filter_path=hits.hits._source.url
{
  "query": {
    "bool": {
      "must": [
        {"term": {"name.keyword":"github" }}
       ]
    }
  }
}

Output:

{
  "hits" : {
    "hits" : [
      {
        "_source" : {
          "url" : "www.github.com/mbarr0987"
            }
          }
      ]
   }
}

Java: Get month Integer from Date

Joda-Time

Alternatively, with the Joda-Time DateTime class.

//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))

…or…

int month = dateTime.getMonthOfYear();

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

An error in your httpd.conf or other Apache config files will cause this. Revert httpd.conf et al to the pristine, installer versions and see if Apache runs again.

(I tried Skype and other suggestions here, no luck, but logs [XAMPP > Apache > Logs button] showed that it ran once when first installed. That was the giveaway.)

Likely errors:

  • Did you edit with a Windows text editor that changes line endings to non-Unix? (Solution here.)
  • Missing or invalid DSO files (.so)

Read properties file outside JAR file

This works for me. Load your properties file from current directory.

Attention: The method Properties#load uses ISO-8859-1 encoding.

Properties properties = new Properties();
properties.load(new FileReader(new File(".").getCanonicalPath() + File.separator + "java.properties"));
properties.forEach((k, v) -> {
            System.out.println(k + " : " + v);
        });

Make sure, that java.properties is at the current directory . You can just write a little startup script that switches into to the right directory in before, like

#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 
cd $scriptdir
java -jar MyExecutable.jar
cd -

In your project just put the java.properties file in your project root, in order to make this code work from your IDE as well.

C++ preprocessor __VA_ARGS__ number of arguments

There are some C++11 solutions for finding the number of arguments at compile-time, but I'm surprised to see that no one has suggested anything so simple as:

#define VA_COUNT(...) detail::va_count(__VA_ARGS__)

namespace detail
{
    template<typename ...Args>
    constexpr std::size_t va_count(Args&&...) { return sizeof...(Args); }
}

This doesn't require inclusion of the <tuple> header either.

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

How to hide reference counts in VS2013?

In VSCode for Mac (0.10.6) I opened "Preferences -> User Settings" and placed the following code in the settings.json file

enter image description here

"editor.referenceInfos": false

enter image description here

User and Workspace Settings

Concatenating null strings in Java

This is behavior specified in the Java API's String.valueOf(Object) method. When you do concatenation, valueOf is used to get the String representation. There is a special case if the Object is null, in which case the string "null" is used.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters: obj - an Object.

Returns:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

How to represent a DateTime in Excel

The underlying data type of a datetime in Excel is a 64-bit floating point number where the length of a day equals 1 and 1st Jan 1900 00:00 equals 1. So 11th June 2009 17:30 is about 39975.72917.

If a cell contains a numeric value such as this, it can be converted to a datetime simply by applying a datetime format to the cell.

So, if you can convert your datetimes to numbers using the above formula, output them to the relevant cells and then set the cell formats to the appropriate datetime format, e.g. yyyy-mm-dd hh:mm:ss, then it should be possible to achieve what you want.

Also Stefan de Bruijn has pointed out that there is a bug in Excel in that it incorrectly assumes 1900 is a leap year so you need to take that into account when making your calculations (Wikipedia).

Visual Studio Code Tab Key does not insert a tab

[Edit] This answer is for MSVS (the IDE, as opposed to VS Code). It seems Microsoft and Google go out of their way to choose confusing names for new products. I'll leave this answer here for now, while I (continue to) look for the equivalent stackoverflow question about MSVS. Let me know in the comments if you think I should delete it. Or better, point me to the MSVS version of this question.

I installed MSVS 2017 recently. None of the suggestions I've seen fixed the problem. The solution I figured out works for MSVS 2015 and 2017. Add a comment below if you find that it works for other versions.

Under Tools -> Options -> Text Editor -> C/C++ -> Formatting -> General, try unchecking the "Automatically indent when I type a tab" box. It seems counter intuitive, but it fixed the problem for me. enter image description here

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Tried following code

 $db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

Then

 try {
 $db->query('SET NAMES gbk');
 $stmt = $db->prepare('SELECT * FROM 2_1_paidused WHERE NumberRenamed = ? LIMIT 1');
 $stmt->execute(array("\xbf\x27 OR 1=1 /*"));
 }
 catch (PDOException $e){
 echo "DataBase Errorz: " .$e->getMessage() .'<br>';
 }
 catch (Exception $e) {
 echo "General Errorz: ".$e->getMessage() .'<br>';
 }

And got

DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/*' LIMIT 1' at line 1

If added $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); after $db = ...

Then got blank page

If instead SELECT tried DELETE, then in both cases got error like

 DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM 2_1_paidused WHERE NumberRenamed = '¿\' OR 1=1 /*' LIMIT 1' at line 1

So my conclusion that no injection possible...

preg_match in JavaScript?

get matched string back or false

function preg_match (regex, str) {
  if (new RegExp(regex).test(str)){
    return regex.exec(str);
  }
  return false;
}

How to return data from PHP to a jQuery ajax call

I figured it out. Need to use echo in PHP instead of return.

<?php 
  $output = some_function();
  echo $output;
?> 

And the jQ:

success: function(data) {
  doSomething(data);
}

How to make Sonar ignore some classes for codeCoverage metric?

When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift

sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift

Jquery Chosen plugin - dynamically populate list by Ajax

The solution of @Ashivad mostly fixed my problem, but I needed to make this one-line addition to prevent the input to be erased after the results dropdown is displayed:

in success callback of the autocomplete added this line after triggering chosen:updated:

$combosearchChosen.find('input').val(request.term);

Complete listing:

var $combosearch = $('[data-combosearch]');
if (!$combosearch.length) {
  return;
}

var options = $combosearch.data('options');
console.log('combosearch', $combosearch, options);

$combosearch.chosen({
  no_results_text: "Oops, nothing found!",
  width: "60%"
});

// actual chosen container
var $combosearchChosen = $combosearch.next();

$combosearchChosen.find('input').autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: options.remote_source + "&query=" + request.term,
      dataType: "json",
      beforeSend: function(){
        $('ul.chosen-results').empty();
      },
      success: function( data ) {
        response( $.map( data, function( item, index ) {
          $combosearch.append('<option value="' + item.id + '">' + item.label + '</option>');
        }));
        $combosearch.trigger('chosen:updated');
        $combosearchChosen.find('input').val(request.term);
      }
    });
  }
});

How should I escape strings in JSON?

The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
    if (string.IsNullOrEmpty(value))
        return addDoubleQuotes ? "\"\"" : string.Empty;

    int len = value.Length;
    bool needEncode = false;
    char c;
    for (int i = 0; i < len; i++)
    {
        c = value[i];

        if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
        {
            needEncode = true;
            break;
        }
    }

    if (!needEncode)
        return addDoubleQuotes ? "\"" + value + "\"" : value;

    var sb = new System.Text.StringBuilder();
    if (addDoubleQuotes)
        sb.Append('"');

    for (int i = 0; i < len; i++)
    {
        c = value[i];
        if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
            sb.AppendFormat("\\u{0:x4}", (int)c);
        else switch ((int)c)
            {
                case 8:
                    sb.Append("\\b");
                    break;

                case 9:
                    sb.Append("\\t");
                    break;

                case 10:
                    sb.Append("\\n");
                    break;

                case 12:
                    sb.Append("\\f");
                    break;

                case 13:
                    sb.Append("\\r");
                    break;

                case 34:
                    sb.Append("\\\"");
                    break;

                case 92:
                    sb.Append("\\\\");
                    break;

                default:
                    sb.Append(c);
                    break;
            }
    }

    if (addDoubleQuotes)
        sb.Append('"');

    return sb.ToString();
}

This can be compacted into

    // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}

To find first N prime numbers in python

What you want is something like this:

x = int(input("Enter the number:"))
count = 0
num = 2
while count < x:
     if isnumprime(x):
        print(x)
        count += 1
     num += 1

I'll leave it up to you to implement isnumprime() ;) Hint: You only need to test division with all previously found prime numbers.

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

Disable Tensorflow debugging information

I solved with this post Cannot remove all warnings #27045 , and the solution was:

import logging
logging.getLogger('tensorflow').disabled = True

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

Why can't I have abstract static methods in C#?

To add to the previous explanations, static method calls are bound to a specific method at compile-time, which rather rules out polymorphic behavior.

if block inside echo statement?

You will want to use the a ternary operator which acts as a shortened IF/Else statement:

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

Can I remove the URL from my print css, so the web address doesn't print?

This solution will do the trick in Chrome and Opera by setting margin to 0 in a css @page directive. It will not (currently) work for other browsers though...

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

Iterating over every two elements in a list

With unpacking:

l = [1,2,3,4,5,6]
while l:
    i, k, *l = l
    print(f'{i}+{k}={i+k}') 

Note: this will consume l, leaving it empty afterward.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()

For example:

SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
        session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
        session = sessionFactory.openSession();
}

If you use Mysql, you can set autoReconnect property:

    <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>

I hope this helps.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

When you declare

var a=[];

you are declaring a empty array.

But when you are declaring

var a={};

you are declaring a Object .

Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.

So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:

var a={name:"abc",age:"14"}; 

And can access values like

console.log(a.name);

Postman: sending nested JSON object

Select the body tab and select application/json in the Content-Type drop-down and add a body like this:

{
  "Username":"ABC",
  "Password":"ABC"
}

enter image description here

add class with JavaScript

getElementsByClassName() returns HTMLCollection so you could try this

var button = document.getElementsByClassName("navButton")[0];

Edit

var buttons = document.getElementsByClassName("navButton");
for(i=0;buttons.length;i++){
   buttons[i].onmouseover = function(){
     this.className += ' active' //add class
     this.setAttribute("src", "images/arrows/top_o.png");
   }
}

Read Excel sheet in Powershell

This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.

$xlCellTypeLastCell = 11 
$startRow = 5 
$col = 2 

$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")

for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
    $sh = $wb.Sheets.Item($i)
    $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
    $city = $sh.Cells.Item($startRow, $col).Value2
    $rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
    $sh.Range($rangeAddress).Value2 | foreach 
    {
        New-Object PSObject -Property @{ City = $city; Area = $_ }
    }
}

$excel.Workbooks.Close()

How is "mvn clean install" different from "mvn install"?

Maven lets you specify either goals or lifecycle phases on the command line (or both).

clean and install are two different phases of two different lifecycles, to which different plugin goals are bound (either per default or explicitly in your pom.xml)

The clean phase, per convention, is meant to make a build reproducible, i.e. it cleans up anything that was created by previous builds. In most cases it does that by calling clean:clean, which deletes the directory bound to ${project.build.directory} (usually called "target")

Smooth scrolling with just pure css

You need to use the target selector.

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

Unable to ping vmware guest from another vmware guest

I would like to add, that yes. While using the NAT adapter settings in Vmware and turning off windows firewall I was able to ping other guest machines in my test environment.

Sidenote: Best practice would be to implement a hardware firewall in larger environments and turn off windows firewall on the Domain Controller.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

When you open the file you want to write to, open it with a specific encoding that can handle all the characters.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

How to add items into a numpy array

One way to do it (may not be the best) is to create another array with the new elements and do column_stack. i.e.

>>>a = array([[1,3,4],[1,2,3]...[1,2,1]])
[[1 3 4]
 [1 2 3]
 [1 2 1]]

>>>b = array([1,2,3])
>>>column_stack((a,b))
array([[1, 3, 4, 1],
       [1, 2, 3, 2],
       [1, 2, 1, 3]])

ngModel cannot be used to register form controls with a parent formGroup directive

The answer is right on the error message, you need to indicate that it's standalone and therefore it doesn't conflict with the form controls:

[ngModelOptions]="{standalone: true}"

How does a Java HashMap handle different objects with the same hash code?

I will not get into the details of how HashMap works, but will give an example so we can remember how HashMap works by relating it to reality.

We have Key, Value ,HashCode and bucket.

For sometime, we will relate each of them with the following:

  • Bucket -> A Society
  • HashCode -> Society's address(unique always)
  • Value -> A House in the Society
  • Key -> House address.

Using Map.get(key) :

Stevie wants to get to his friend's(Josse) house who lives in a villa in a VIP society, let it be JavaLovers Society. Josse's address is his SSN(which is different for everyone). There's an index maintained in which we find out the Society's name based on SSN. This index can be considered to be an algorithm to find out the HashCode.

  • SSN Society's Name
  • 92313(Josse's) -- JavaLovers
  • 13214 -- AngularJSLovers
  • 98080 -- JavaLovers
  • 53808 -- BiologyLovers

  1. This SSN(key) first gives us a HashCode(from the index table) which is nothing but Society's name.
  2. Now, mulitple houses can be in the same society, so the HashCode can be common.
  3. Suppose, the Society is common for two houses, how are we going to identify which house we are going to, yes, by using the (SSN)key which is nothing but the House address

Using Map.put(key,Value)

This finds a suitable society for this Value by finding the HashCode and then the value is stored.

I hope this helps and this is open for modifications.

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:

php/pci.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*

php/pciconf.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*

php/pear.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/peardev.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/pecl.bat:32

from

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/phar.phar.bat:1

from

%~dp0php.exe %~dp0pharcommand.phar %*

to

"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

Enabling refreshing for specific html elements only

Try this in your script:

$("#YourElement").html(htmlData);

I do this in my table refreshment.

SQL "between" not inclusive

your code

SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'

how SQL reading it

SELECT * FROM Cases WHERE '2013-05-01 22:25:19' BETWEEN '2013-05-01 00:00:00' AND '2013-05-01 00:00:00'

if you don't mention time while comparing DateTime and Date by default hours:minutes:seconds will be zero in your case dates are the same but if you compare time created_at is 22 hours ahead from your end date range

if the above is clear you fix this in many ways like putting ending hours in your end date eg BETWEEN '2013-05-01' AND ''2013-05-01 23:59:59''

OR

simply cast create_at as date like cast(created_at as date) after casting as date '2013-05-01 22:25:19' will be equal to '2013-05-01 00:00:00'

HTML form with side by side input fields

You should put the input for the last name into the same div where you have the first name.

<div>
    <label for="username">First Name</label>
    <input id="user_first_name" name="user[first_name]" size="30" type="text" />
    <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

Then, in your CSS give your #user_first_name and #user_last_name height and float them both to the left. For example:

#user_first_name{
    max-width:100px; /*max-width for responsiveness*/
    float:left;
}

#user_lastname_name{
    max-width:100px;
    float:left;
}

Initializing C dynamic arrays

Instead of using

int * p;
p = {1,2,3};

we can use

int * p;
p =(int[3]){1,2,3};

SVN 405 Method Not Allowed

The currently added directory is already committed in the repository. So delete the directory in the repository and commit the same directory again.

TypeScript sorting an array

let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

let sortFn = (n1 , n2) => number { return n1 - n2; }

const sortedArray: number[] = numericArray.sort(sortFn);

Sort by some field:

let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];

let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }

const sortedArray2:{key:number}[] = arr.sort(sortFn2);

Adding a splash screen to Flutter apps

For Android, go to android > app > src > main > res > drawable > launcher_background.xml

Now uncomment this and replace @mipmap/launch_image, with your image location.

<item>
      <bitmap
          android:gravity="center"
          android:src="@mipmap/launch_image" />
</item>

You can change the colour of your screen here -

<item android:drawable="@android:color/white" />

Using querySelectorAll to retrieve direct children

I created a function to handle this situation, thought I would share it.

getDirectDecendent(elem, selector, all){
    const tempID = randomString(10) //use your randomString function here.
    elem.dataset.tempid = tempID;

    let returnObj;
    if(all)
        returnObj = elem.parentElement.querySelectorAll(`[data-tempid="${tempID}"] > ${selector}`);
    else
        returnObj = elem.parentElement.querySelector(`[data-tempid="${tempID}"] > ${selector}`);

    elem.dataset.tempid = '';
    return returnObj;
}

In essence what you are doing is generating a random-string (randomString function here is an imported npm module, but you can make your own.) then using that random string to guarantee that you get the element you are expecting in the selector. Then you are free to use the > after that.

The reason I am not using the id attribute is that the id attribute may already be used and I don't want to override that.

Java generics - ArrayList initialization

You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

Adding elements to object

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

How to convert an NSString into an NSNumber

I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?

All I pretty much did was:

double myDouble = [myString doubleValue];

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1' 
        // Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

Close Bootstrap modal on form submit

Use that Code

 $('#button').submit(function(e) {
    e.preventDefault();
    // Coding
    $('#IDModal').modal('toggle'); //or  $('#IDModal').modal('hide');
    return false;
});

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I fully agree with Mikko, but if you still want to do it, here is the way:

  • Restart in recovery mode (Hold cmd + R)
  • Open terminal from utilities
  • Use the command csrutil disable

Is a Python dictionary an example of a hash table?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.

How to convert an ArrayList containing Integers to primitive int array?

Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

access arr like normal int[].

How can I make robocopy silent in the command line except for progress?

robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:

robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"

Reading column names alone in a csv file

I am just mentioning how to get all the column names from a csv file. I am using pandas library.

First we read the file.

import pandas as pd
file = pd.read_csv('details.csv')

Then, in order to just get all the column names as a list from input file use:-

columns = list(file.head(0))

How and where to use ::ng-deep?

Use ::ng-deep with caution. I used it throughout my app to set the material design toolbar color to different colors throughout my app only to find that when the app was in testing the toolbar colors step on each other. Come to find out it is because these styles becomes global, see this article Here is a working code solution that doesn't bleed into other components.

<mat-toolbar #subbar>
...
</mat-toolbar>

export class BypartSubBarComponent implements AfterViewInit {
  @ViewChild('subbar', { static: false }) subbar: MatToolbar;
  constructor(
    private renderer: Renderer2) { }
  ngAfterViewInit() {
    this.renderer.setStyle(
      this.subbar._elementRef.nativeElement, 'backgroundColor', 'red');
  }

}

jQuery event handlers always execute in order they were bound - any way around this?

Chris Chilvers' advice should be the first course of action but sometimes we're dealing with third party libraries that makes this challenging and requires us to do naughty things... which this is. IMO it's a crime of presumption similar to using !important in CSS.

Having said that, building on Anurag's answer, here are a few additions. These methods allow for multiple events (e.g. "keydown keyup paste"), arbitrary positioning of the handler and reordering after the fact.

$.fn.bindFirst = function (name, fn) {
    this.bindNth(name, fn, 0);
}

$.fn.bindNth(name, fn, index) {
    // Bind event normally.
    this.bind(name, fn);
    // Move to nth position.
    this.changeEventOrder(name, index);
};

$.fn.changeEventOrder = function (names, newIndex) {
    var that = this;
    // Allow for multiple events.
    $.each(names.split(' '), function (idx, name) {
        that.each(function () {
            var handlers = $._data(this, 'events')[name.split('.')[0]];
            // Validate requested position.
            newIndex = Math.min(newIndex, handlers.length - 1);
            handlers.splice(newIndex, 0, handlers.pop());
        });
    });
};

One could extrapolate on this with methods that would place a given handler before or after some other given handler.

setTimeout / clearTimeout problems

Not sure if this violates some good practice coding rule but I usually come out with this one:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

This prevent the need to declare the timer out of the function.

EDIT: this also don't declare a new variable at each invocation, but always recycle the same.

Hope this helps.

AngularJS : ng-model binding not updating when changed with jQuery

You have to trigger the change event of the input element because ng-model listens to input events and the scope will be updated. However, the regular jQuery trigger didn't work for me. But here is what works like a charm

$("#myInput")[0].dispatchEvent(new Event("input", { bubbles: true })); //Works

Following didn't work

$("#myInput").trigger("change"); // Did't work for me

You can read more about creating and dispatching synthetic events.

How to get screen width without (minus) scrollbar?

You can use vanilla javascript by simply writing:

var width = el.clientWidth;

You could also use this to get the width of the document as follows:

var docWidth = document.documentElement.clientWidth || document.body.clientWidth;

Source: MDN

You can also get the width of the full window, including the scrollbar, as follows:

var fullWidth = window.innerWidth;

However this is not supported by all browsers, so as a fallback, you may want to use docWidth as above, and add on the scrollbar width.

Source: MDN

In Tkinter is there any way to make a widget not visible?

I know this is a couple of years late, but this is the 3rd Google response now for "Tkinter hide Label" as of 10/27/13... So if anyone like myself a few weeks ago is building a simple GUI and just wants some text to appear without swapping it out for another widget via "lower" or "lift" methods, I'd like to offer a workaround I use (Python2.7,Windows):

from Tkinter import *


class Top(Toplevel):
    def __init__(self, parent, title = "How to Cheat and Hide Text"):
        Toplevel.__init__(self,parent)
        parent.geometry("250x250+100+150")
        if title:
            self.title(title)
        parent.withdraw()
        self.parent = parent
        self.result = None
        dialog = Frame(self)
        self.initial_focus = self.dialog(dialog)
        dialog.pack()


    def dialog(self,parent):

        self.parent = parent

        self.L1 = Label(parent,text = "Hello, World!",state = DISABLED, disabledforeground = parent.cget('bg'))
        self.L1.pack()

        self.B1 = Button(parent, text = "Are You Alive???", command = self.hello)
        self.B1.pack()

    def hello(self):
        self.L1['state']="normal"


if __name__ == '__main__':
    root=Tk()   
    ds = Top(root)
    root.mainloop()

The idea here is that you can set the color of the DISABLED text to the background ('bg') of the parent using ".cget('bg')" http://effbot.org/tkinterbook/widget.htm rendering it "invisible". The button callback resets the Label to the default foreground color and the text is once again visible.

Downsides here are that you still have to allocate the space for the text even though you can't read it, and at least on my computer, the text doesn't perfectly blend to the background. Maybe with some tweaking the color thing could be better and for compact GUIs, blank space allocation shouldn't be too much of a hassle for a short blurb.

See Default window colour Tkinter and hex colour codes for the info about how I found out about the color stuff.

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

getMinutes() 0-9 - How to display two digit numbers?

I suggest:

var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;

it is one function call fewer. It is always good to think about performance. It is short as well;

How to edit my Excel dropdown list?

Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.

RESTful API methods; HEAD & OPTIONS

As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

9.2 OPTIONS

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.

If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).

If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.

A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".

The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

How do I skip a header from CSV files in Spark?

If there were just one header line in the first record, then the most efficient way to filter it out would be:

rdd.mapPartitionsWithIndex {
  (idx, iter) => if (idx == 0) iter.drop(1) else iter 
}

This doesn't help if of course there are many files with many header lines inside. You can union three RDDs you make this way, indeed.

You could also just write a filter that matches only a line that could be a header. This is quite simple, but less efficient.

Python equivalent:

from itertools import islice

rdd.mapPartitionsWithIndex(
    lambda idx, it: islice(it, 1, None) if idx == 0 else it 
)

How do I reverse an int array in Java?

There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:

    int[] a = {8, 6, 7, 5, 3, 0, 9};
    int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();

Instagram how to get my user id from username?

Very late answer but I think this is the best answer of this topic. Hope this is useful.

You can get user info when a request is made with the url below:

https://www.instagram.com/{username}/?__a=1

E.g:

This url will get all information about a user whose username is therock

https://www.instagram.com/therock/?__a=1

Update i June-20-2019, the API is public now. No authentication required.

Update in December-11-2018, I needed to confirm that this endpoint still work. You need to login before sending request to this site because it's not public endpoint anymore. The login step is easy also. This is my demo: https://youtu.be/ec5QhwM6fvc


Update in Apr-17-2018, it's look like this endpoint still working (but its not public endpoint anymore), you must send a request with extra information to that endpoint. (Press F12 to open developer toolbar, then click to Network Tab and trace the request.)

Sorry because I'm too busy. Hope this information help you guys. Hmm, feel free to give me a down-vote if you want.


Update in Apr-12-2018, cameronjonesweb said that this endpoint doesn't work anymore. When he/she trying to access this endpoint, 403 status code return.


How to redirect to an external URL in Angular2?

I did it using Angular 2 Location since I didn't want to manipulate the global window object myself.

https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor

It can be done like this:

import {Component} from '@angular/core';
import {Location} from '@angular/common';
@Component({selector: 'app-component'})
class AppCmp {
  constructor(location: Location) {
    location.go('/foo');
  }
}

Get real path from URI, Android KitKat new storage access framework

Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.

You could use the URI to obtain document id, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI (depending on the SD card situation).

To get document id:

// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };     

// where id is equal to             
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = getContentResolver().
                          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                          column, sel, new String[]{ id }, null);

String filePath = "";

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
    filePath = cursor.getString(columnIndex);
}   

cursor.close();

Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.

How to implement Android Pull-to-Refresh

I have very easy way to do this but now sure its the foolproof way There is my code PullDownListView.java

package com.myproject.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

/**
 * @author Pushpan
 * @date Nov 27, 2012
 **/
public class PullDownListView extends ListView implements OnScrollListener {

    private ListViewTouchEventListener mTouchListener;
    private boolean pulledDown;

    public PullDownListView(Context context) {
        super(context);
        init();
    }

    public PullDownListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PullDownListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setOnScrollListener(this);
    }

    private float lastY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            lastY = ev.getRawY();
        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            float newY = ev.getRawY();
            setPulledDown((newY - lastY) > 0);
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isPulledDown()) {
                        if (mTouchListener != null) {
                            mTouchListener.onListViewPulledDown();
                            setPulledDown(false);
                        }
                    }
                }
            }, 400);
            lastY = newY;
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {
            lastY = 0;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        setPulledDown(false);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    public interface ListViewTouchEventListener {
        public void onListViewPulledDown();
    }

    public void setListViewTouchListener(
            ListViewTouchEventListener touchListener) {
        this.mTouchListener = touchListener;
    }

    public ListViewTouchEventListener getListViewTouchListener() {
        return mTouchListener;
    }

    public boolean isPulledDown() {
        return pulledDown;
    }

    public void setPulledDown(boolean pulledDown) {
        this.pulledDown = pulledDown;
    }
}

You just need to implement ListViewTouchEventListener on your activity where you want to use this ListView and set the listener

I have it implemented in PullDownListViewActivity

package com.myproject.activities;

import android.app.Activity;
import android.os.Bundle;

/**
 * @author Pushpan
 *
 */
public class PullDownListViewActivity extends Activity implements ListViewTouchEventListener {

    private PullDownListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView = new PullDownListView(this);
        setContentView(listView);
        listView.setListViewTouchListener(this);

        //setItems in listview
    }

    public void onListViewPulledDown(){
        Log.("PullDownListViewActivity", "ListView pulled down");
    }
}

It works for me :)

How to get div height to auto-adjust to background size?

How about this :)

_x000D_
_x000D_
.fixed-centered-covers-entire-page{_x000D_
    margin:auto;_x000D_
    background-image: url('https://i.imgur.com/Ljd0YBi.jpg');_x000D_
    background-repeat: no-repeat;background-size:cover;_x000D_
    background-position: 50%;_x000D_
    background-color: #fff;_x000D_
    left:0;_x000D_
    right:0;_x000D_
    top:0;_x000D_
    bottom:0;_x000D_
    z-index:-1;_x000D_
    position:fixed;_x000D_
}
_x000D_
<div class="fixed-centered-covers-entire-page"></div>
_x000D_
_x000D_
_x000D_

Demo: http://jsfiddle.net/josephmcasey/KhPaF/

Visual Studio 64 bit?

Is there any 64 bit Visual Studio at all?

Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows

Why not?

Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...

So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:

  • Visual Studio will drop 32bit support and become 64bit,
  • Visual Studio Code will take it's place instead,
  • Visual Studio will have similar functionality like WOW64 for old extensions which is I believe unlikely to happen.

I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,

Python: get key of index in dictionary

Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.

You can only do this in a loop:

[k for (k, v) in i.iteritems() if v == 0]

Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0} is perfectly legal.

If you want ordering you either need to use a list or a OrderedDict instance instead:

items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0]         # gives 'a'

How do I make a file:// hyperlink that works in both IE and Firefox?

file Protocol
Opens a file on a local or network drive.

Syntax

Copy
 file:///sDrives[|sFile]
Tokens 

sDrives
Specifies the local or network drive.

sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.

Remarks

The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.

Available as of Microsoft Internet Explorer 3.0 or later.

Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

Example

The following sample demonstrates four ways to use the File protocol.

Copy

//Specifying a drive and a file name. 

file:///C|/My Documents/ALetter.html

//Specifying only a drive and a path to browse the directory. 

file:///C|/My Documents/

//Specifying a drive and a directory using the command line representation of the directory location. 

C:\My Documents\

//Specifying only the directory on the local primary drive. 

\My Documents\

http://msdn.microsoft.com/en-us/library/aa767731

Twitter Bootstrap - full width navbar

Not sure if the navbar-static-top class was available prior to version 2.2.2 but I think you can accomplish your goal with the following:

<div class="navbar navbar-static-top">
    <div class="navbar-inner">
        <ul class="nav">
            <li class="active"><a href="#">Test1</a></li>
            <li><a href="#">Test2</a></li>
            <li><a href="#">Test3</a></li>
            <li><a href="#">Test4</a></li>
            <li><a href="#">Test5</a></li>
        </ul>
    </div>
</div>
<div class="container">
    ...
</div>

I put together a jsFiddle as an example.

Floating Point Exception C++ Why and what is it?

Problem is in the for loop in the code snippet:
for (i > 0; i--;)

Here, your intention seems to be entering the loop if (i > 0) and decrement the value of i by one after the completion of for loop.

Does it work like that? lets see.

Look at the for() loop syntax:

**for ( initialization; condition check; increment/decrement ) {  
    statements;  
}**

Initialization gets executed only once in the beginning of the loop. Pay close attention to ";" in your code snippet and map it with for loop syntax.

Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.

Condition check : i -- : post decrement.

              Here, i is used for condition check and then it is decremented. 
              Decremented value will be used in statements within for loop. 
              This condition check is working as increment/decrement too in your code. 

Lets stop here and see floating point exception.

what is it? One easy example is Divide by 0. Same is happening with your code.

When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.

Modulo operation at line #9 results in divide by zero operation.  

With this background you should be able to fix the problem in for loop.

read subprocess stdout line by line

A function that allows iterating over both stdout and stderr concurrently, in realtime, line by line

In case you need to get the output stream for both stdout and stderr at the same time, you can use the following function.

The function uses Queues to merge both Popen pipes into a single iterator.

Here we create the function read_popen_pipes():

from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor


def enqueue_output(file, queue):
    for line in iter(file.readline, ''):
        queue.put(line)
    file.close()


def read_popen_pipes(p):

    with ThreadPoolExecutor(2) as pool:
        q_stdout, q_stderr = Queue(), Queue()

        pool.submit(enqueue_output, p.stdout, q_stdout)
        pool.submit(enqueue_output, p.stderr, q_stderr)

        while True:

            if p.poll() is not None and q_stdout.empty() and q_stderr.empty():
                break

            out_line = err_line = ''

            try:
                out_line = q_stdout.get_nowait()
            except Empty:
                pass
            try:
                err_line = q_stderr.get_nowait()
            except Empty:
                pass

            yield (out_line, err_line)

read_popen_pipes() in use:

import subprocess as sp


with sp.Popen(my_cmd, stdout=sp.PIPE, stderr=sp.PIPE, text=True) as p:

    for out_line, err_line in read_popen_pipes(p):

        # Do stuff with each line, e.g.:
        print(out_line, end='')
        print(err_line, end='')

    return p.poll() # return status-code

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

Add Facebook Share button to static HTML page

<a name='fb_share' type='button_count' href='http://www.facebook.com/sharer.php?appId={YOUR APP ID}&link=<?php the_permalink() ?>' rel='nofollow'>Share</a><script src='http://static.ak.fbcdn.net/connect.php/js/FB.Share' type='text/javascript'></script>

Server Error in '/' Application. ASP.NET

Try removing the contents of the <compilers> tag in the web.config file. Depending on who you're hosting with, some don't allow the compiler in production.

Your application is trying to compile when it is called and their servers won't allow it.

How to push a single file in a subdirectory to Github (not master)

Let me start by saying that the way git works is you are not pushing/fetching files; well, at least not directly.

You are pushing/fetching refs, that point to commits. Then a commit in git is a reference to a tree of objects (where files are represented as objects, among other objects).

So, when you are pushing a commit, what git does it pushes a set of references like in this picture:

git commits

If you didn't push your master branch yet, the whole history of the branch will get pushed.

So, in your example, when you commit and push your file, the whole master branch will be pushed, if it was not pushed before.

To do what you asked for, you need to create a clean branch with no history, like in this answer.

Signing a Windows EXE file

And yet another option, if you're developing on Windows 10 but don't have Microsoft's signtool.exe installed, you can use Bash on Ubuntu on Windows to sign your app. Here is a run down:

https://blog.synapp.nz/2017/06/16/code-signing-a-windows-application-on-linux-on-windows/

Fixing Sublime Text 2 line endings?

The EditorConfig project (Github link) is another very viable solution. Similar to sftp-config.json and .sublime-project/workspace sort of file, once you set up a .editorconfig file, either in project folder or in a parent folder, every time you save a file within that directory structure the plugin will automatically apply the settings in the dot file and automate a few different things for you. Some of which are saving Unix-style line endings, adding end-of-file newline, removing whitespace, and adjusting your indent tab/space settings.


QUICK EXAMPLE

Install the EditorConfig plugin in Sublime using Package Control; then place a file named .editorconfig in a parent directory (even your home or the root if you like), with the following content:

[*]
end_of_line = lf

That's it. This setting will automatically apply Unix-style line endings whenever you save a file within that directory structure. You can do more cool stuff, ex. trim unwanted trailing white-spaces or add a trailing newline at the end of each file. For more detail, refer to the example file at https://github.com/sindresorhus/editorconfig-sublime, that is:

# editorconfig.org
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

The root = true line means that EditorConfig won't look for other .editorconfig files in the upper levels of the directory structure.

How to get the top position of an element?

If you want the position relative to the document then:

$("#myTable").offset().top;

but often you will want the position relative to the closest positioned parent:

$("#myTable").position().top;

Bitwise and in place of modulus operator

There is only a simple way to find modulo of 2^i numbers using bitwise.

There is an ingenious way to solve Mersenne cases as per the link such as n % 3, n % 7... There are special cases for n % 5, n % 255, and composite cases such as n % 6.

For cases 2^i, ( 2, 4, 8, 16 ...)

n % 2^i = n & (2^i - 1)

More complicated ones are hard to explain. Read up only if you are very curious.

List all kafka topics

To read messages you should use:

kafka-console-consumer.sh --bootstrap-server kafka1:9092,kafka2:9092,kafka3:9092 --topic messages --from-beginning

--bootstrap-server is required attribute. You can use only single kafka1:9020 node.

Is there a simple way to remove multiple spaces in a string?

import re

Text = " You can select below trims for removing white space!!   BR Aliakbar     "
  # trims all white spaces
print('Remove all space:',re.sub(r"\s+", "", Text), sep='') 
# trims left space
print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='') 
# trims right space
print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')  
# trims both
print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
# replace more than one white space in the string with one white space
print('Remove more than one space:',re.sub(' +', ' ',Text), sep='') 

Result:

Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar Remove leading space:You can select below trims for removing white space!! BR Aliakbar
Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar Remove more than one space: You can select below trims for removing white space!! BR Aliakbar

Android scale animation on view

public void expand(final View v) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1, 1, 0, 0, 0);
        scaleAnimation.setDuration(250);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        v.startAnimation(scaleAnimation);
    }

    public void collapse(final View v) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1, 0, 1, 0, 0);
        scaleAnimation.setDuration(250);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        v.startAnimation(scaleAnimation);
    }

Vim: How to insert in visual block mode?

Try this

After selecting a block of text, press Shift+i or capital I.

Lowercase i will not work.

Then type the things you want and finally to apply it to all lines, press Esc twice.




If this doesn't work...

Check if you have +visualextra enabled in your version of Vim.

You can do this by typing in :ver and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)

Enabling it is outside the scope of this question but I'm sure you can find it somewhere.

TypeError : Unhashable type

A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

A list doesn't use a hash for indexing, so it isn't restricted to hashable items.

Restore a deleted file in the Visual Studio Code Recycle Bin

  1. Go to your computer's Recycle Bin.
  2. Search for the specific file that got deleted.
  3. Right click on that file. Go to Restore in the drop-down list.

Voila! The file is restored and is back in your folder. Happy Coding!

Animation CSS3: display + opacity

I had the same problem. I tried using animations instead of transitions - as suggested by @MichaelMullany and @Chris - but it only worked for webkit browsers even if I copy-pasted with "-moz" and "-o" prefixes.

I was able to get around the problem by using visibility instead of display. This works for me because my child element is position: absolute, so document flow isn't being affected. It might work for others too.

This is what the original code would look like using my solution:

.child {
    position: absolute;
    opacity: 0;
    visibility: hidden;

    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}

.parent:hover .child {
    position: relative;
    opacity: 0.9;
    visibility: visible;
}

Calculate a MD5 hash from a string

Was trying to create a string representation of MD5 hash using LINQ, however, none of the answers were LINQ solutions, therefore adding this to the smorgasbord of available solutions.

string result;
using (MD5 hash = MD5.Create())
{
    result = String.Join
    (
        "",
        from ba in hash.ComputeHash
        (
            Encoding.UTF8.GetBytes(observedText)
        ) 
        select ba.ToString("x2")
    );
}