Programs & Examples On #Smartxls

ASP.NET Identity DbContext confusion

This is a late entry for folks, but below is my implementation. You will also notice I stubbed-out the ability to change the the KEYs default type: the details about which can be found in the following articles:

It should be noted that you cannot use Guid's for your keys. This is because under the hood they are a Struct, and as such, have no unboxing which would allow their conversion from a generic <TKey> parameter.


public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
    #region <Constructors>

    public ApplicationDbContext() : base(Settings.ConnectionString.Database.AdministrativeAccess)


    #region <Properties>

    //public DbSet<Case> Case { get; set; }


    #region <Methods>


    protected override void OnModelCreating(DbModelBuilder modelBuilder)

        //modelBuilder.Configurations.Add(new ResourceConfiguration());
        //modelBuilder.Configurations.Add(new OperationsToRolesConfiguration());



    public static ApplicationDbContext Create()
        return new ApplicationDbContext();



    public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole, CustomUserClaim>
        #region <Constructors>

        public ApplicationUser()


        #region <Properties>

        public string FirstName { get; set; }

        public string LastName { get; set; }


        #region <Methods>

        #region private

        private void Init()
            Id = Guid.Empty.ToString();


        #region public

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here

            return userIdentity;



    public class CustomUserStore : UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
        #region <Constructors>

        public CustomUserStore(ApplicationDbContext context) : base(context)


    public class CustomUserRole : IdentityUserRole<string>

    public class CustomUserLogin : IdentityUserLogin<string>

    public class CustomUserClaim : IdentityUserClaim<string> 

    public class CustomRoleStore : RoleStore<CustomRole, string, CustomUserRole>
        #region <Constructors>

        public CustomRoleStore(ApplicationDbContext context) : base(context)


    public class CustomRole : IdentityRole<string, CustomUserRole>
        #region <Constructors>

        public CustomRole() { }
        public CustomRole(string name) 
            Name = name; 


How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    <echo>deployment ok!</echo>

${jboss.deploy.dir} is set to standalone/deployments

Tkinter module not found on Ubuntu

In python 3 Tkinter renamed tkinter

Sorting multiple keys with Unix sort

The -k option is what you want.

-k 1.4,1.5n -k 1.14,1.15n

Would use character positions 4-5 in the first field (it's all one field for fixed width) and sort numerically as the first key.

The second key would be characters 14-15 in the first field also.


Example (all I have is DOS/cygwin handy):

dir | \cygwin\bin\sort.exe -k 1.4,1.5n -k 1.40,1.60r

for the data:

12/10/2008  01:10 PM         1,564,990 outfile.txt

Sorts the directory listing by month number (pos 4-5) numerically, and then by filename (pos 40-60) in reverse. Since there are no tabs, it's all field 1 to sort.

Handling optional parameters in javascript

You should check type of received parameters. Maybe you should use arguments array since second parameter can sometimes be 'parameters' and sometimes 'callback' and naming it parameters might be misleading.

How to find out the MySQL root password

As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf. (and the cpanel service resets it back on change, so the other answers here won't help)

What is the difference between an interface and abstract class?

In an interface all methods must be only definitions, not single one should be implemented.

But in an abstract class there must an abstract method with only definition, but other methods can be also in the abstract class with implementation...

Standard way to embed version into python package?

Though this is probably far too late, there is a slightly simpler alternative to the previous answer:

__version_info__ = ('1', '2', '3')
__version__ = '.'.join(__version_info__)

(And it would be fairly simple to convert auto-incrementing portions of version numbers to a string using str().)

Of course, from what I've seen, people tend to use something like the previously-mentioned version when using __version_info__, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, int() and str() can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)

This is, of course, my own view, and I would gladly like others' input on using a numerical tuple.

As shezi reminded me, (lexical) comparisons of number strings do not necessarily have the same result as direct numerical comparisons; leading zeroes would be required to provide for that. So in the end, storing __version_info__ (or whatever it would be called) as a tuple of integer values would allow for more efficient version comparisons.

python plot normal distribution

Unutbu answer is correct. But because our mean can be more or less than zero I would still like to change this :

x = np.linspace(-3 * sigma, 3 * sigma, 100)

to this :

x = np.linspace(-3 * sigma + mean, 3 * sigma + mean, 100)

Subtract one day from datetime

Try this

SELECT DATEDIFF(DAY,  DATEADD(day, -1, '2013-03-13 00:00:00.000'), GETDATE())



Trigger function when date is selected with jQuery UI datepicker

If you are also interested in the case where the user closes the date selection dialog without selecting a date (in my case choosing no date also has meaning) you can bind to the onClose event:

         onClose: function (dateText, inst) {
            //you will get here once the user is done "choosing" - in the dateText you will have 
            //the new date or "" if no date has been selected             

Pandas (python): How to add column to dataframe for index?

How about:

df['new_col'] = range(1, len(df) + 1)

Alternatively if you want the index to be the ranks and store the original index as a column:

df = df.reset_index()

Section vs Article HTML5

My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).

So a section is like a div-container that holds articles.

Replace first occurrence of pattern in a string

public string ReplaceFirst(string text, string search, string replace)
  int pos = text.IndexOf(search);
  if (pos < 0)
    return text;
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);

here is an Extension Method that could also work as well per VoidKing request

public static class StringExtensionMethods
    public static string ReplaceFirst(this string text, string search, string replace)
      int pos = text.IndexOf(search);
      if (pos < 0)
        return text;
      return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);

How to return PDF to browser in MVC?

I know this question is old but I thought I would share this as I could not find anything similar.

I wanted to create my views/models as normal using Razor and have them rendered as Pdfs.

This way I had control over the pdf presentation using standard html output rather than figuring out how to layout the document using iTextSharp.

The project and source code is available here with nuget installation instructions:

Install-Package MvcRazorToPdf

Node.js Error: Cannot find module express

  • sudo brew uninstall node
  • brew update
  • brew upgrade
  • brew cleanup
  • brew install node
  • sudo chown -R $(whoami) /usr/local
  • brew link --overwrite node
  • sudo brew postinstall node

This worked for me on MacOS X Sierra

Display Adobe pdf inside a div

Yes you can.

See the code from the following thread from 2007: PDF within a DIV

    <object data="test.pdf" type="application/pdf" width="300" height="200">
        alt : <a href="test.pdf">test.pdf</a>

It uses <object>, which can be styled with CSS, and so you can float them, give them borders, etc.

(In the end, I edited my pdf files to remove large borders and converted them to jpg images.)

Constraint Layout Vertical Align Center

Two buttons one centered one below to the left of it

Showing it graphically.

Centering on parent is done by constraining both sides to the parent. You can the constrain additional objects off of the centered object.

Note. Each arrow represents a "app:layout_constraintXXX_toYYY=" attribute. (6 in the picture)

PowerShell and the -contains operator

-Contains is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.

-match and -imatch are regular expression string matchers, and set automatic variables to use with captures.

-like, -ilike are SQL-like matchers.

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

Where can I find free WPF controls and control templates?

Syncfusion has a free community version available with over 650 controls.


You will find an FAQ there with any licensing questions you may have, it sound great to be honest. Have fun!

Edit: The WPF controls themselves are 100+, the number of 650+ refers to all controls for all areas (WPF, Windows Forms etc).

Persist javascript variables across pages?

Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.

If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.

Note that cookies are stored client side.

Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Encrypt and decrypt a String in java

I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??

This depends strongly on the crypto algorithm you use:

  • One goal of some/most (mature) algorithms is that the encrypted text is different when encryption done twice. One reason to do this is, that an attacker how known the plain and the encrypted text is not able to calculate the key.
  • Other algorithm (mainly one way crypto hashes) like MD5 or SHA based on the fact, that the hashed text is the same for each encryption/hash.

Normalize data in pandas

In [92]: df
           a         b          c         d
A  -0.488816  0.863769   4.325608 -4.721202
B -11.937097  2.993993 -12.916784 -1.086236
C  -5.569493  4.672679  -2.168464 -9.315900
D   8.892368  0.932785   4.535396  0.598124

In [93]: df_norm = (df - df.mean()) / (df.max() - df.min())

In [94]: df_norm
          a         b         c         d
A  0.085789 -0.394348  0.337016 -0.109935
B -0.463830  0.164926 -0.650963  0.256714
C -0.158129  0.605652 -0.035090 -0.573389
D  0.536170 -0.376229  0.349037  0.426611

In [95]: df_norm.mean()
a   -2.081668e-17
b    4.857226e-17
c    1.734723e-17
d   -1.040834e-17

In [96]: df_norm.max() - df_norm.min()
a    1
b    1
c    1
d    1

JPA OneToMany not deleting child

class Employee {
     private Address address;

See here.

How do I make a Mac Terminal pop-up/alert? Applescript?

Use this command to trigger the notification center notification from the terminal.

osascript -e 'display notification "Lorem ipsum dolor sit amet" with title "Title"'

How do I configure the proxy settings so that Eclipse can download new plugins?

I installed HandyCache, in them install link on my general proxy.

In IE set proxy

In Eclipse, Window > Preferences > General > Network Connections, set Active Provider = Native.

How to change an Eclipse default project into a Java project

Open the .project file and add java nature and builders.


And in .classpath, reference the Java libs:

    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>

Scanner vs. StringTokenizer vs. String.Split

Split is slow, but not as slow as Scanner. StringTokenizer is faster than split. However, I found that I could obtain double the speed, by trading some flexibility, to get a speed-boost, which I did at JFastParser

Testing on a string containing one million doubles:

Scanner: 10642 ms
Split: 715 ms
StringTokenizer: 544ms
JFastParser: 290ms

rand() returns the same number each time the program is run

You need to change the seed.

int main() {

    cout << (rand() % 101);
    return 0;

the srand seeding thing is true also for a c language code.

See also:

How to write data to a text file without overwriting the current data

You have to open as new StreamWriter(filename, true) so that it appends to the file instead of overwriting.

Is there any option to limit mongodb memory usage?

mongod --wiredTigerCacheSizeGB 2 xx

JavaScript: Is there a way to get Chrome to break on all errors?

Edit: The original link I answered with is now invalid.The newer URL would be as of 2016-11-11.

I realize this question has an answer, but it's no longer accurate. Use the link above ^

(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)

Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.

Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)

Hashmap with Streams in Java 8 Streams to collect value of Map

Using keySet-

        .filter(x -> x == 1)
        .map(x -> id1.get(x))

How to bind an enum to a combobox control in WPF?

There are many excellent answers to this question and I humbly submit mine. I find that mine is somewhat simpler and more elegant. It requires only a value converter.

Given an enum...

public enum ImageFormat
    [Description("Windows Bitmap")]
    [Description("Graphics Interchange Format")]
    [Description("Joint Photographic Experts Group Format")]
    [Description("Portable Network Graphics Format")]
    [Description("Tagged Image Format")]
    [Description("Windows Media Photo Format")]

and a value converter...

public class ImageFormatValueConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        if (value is ImageFormat format)
            return GetString(format);

        return null;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        if (value is string s)
            return Enum.Parse(typeof(ImageFormat), s.Substring(0, s.IndexOf(':')));
        return null;

    public string[] Strings => GetStrings();

    public static string GetString(ImageFormat format)
        return format.ToString() + ": " + GetDescription(format);

    public static string GetDescription(ImageFormat format)
        return format.GetType().GetMember(format.ToString())[0].GetCustomAttribute<DescriptionAttribute>().Description;

    public static string[] GetStrings()
        List<string> list = new List<string>();
        foreach (ImageFormat format in Enum.GetValues(typeof(ImageFormat)))

        return list.ToArray();


    <local:ImageFormatValueConverter x:Key="ImageFormatValueConverter"/>

XAML declaration...

    <ComboBox Grid.Row="9" ItemsSource="{Binding Source={StaticResource ImageFormatValueConverter}, Path=Strings}"
              SelectedItem="{Binding Format, Converter={StaticResource ImageFormatValueConverter}}"/>

View model...

    private ImageFormat _imageFormat = ImageFormat.JPG;
    public ImageFormat Format
        get => _imageFormat;
            if (_imageFormat != value)
                _imageFormat = value;

Resulting combobox...

ComboBox bound to enum

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

Get name of currently executing test in JUnit 4

JUnit 4.9.x and higher

Since JUnit 4.9, the TestWatchman class has been deprecated in favour of the TestWatcher class, which has invocation:

public TestRule watcher = new TestWatcher() {
   protected void starting(Description description) {
      System.out.println("Starting test: " + description.getMethodName());

Note: The containing class must be declared public.

JUnit 4.7.x - 4.8.x

The following approach will print method names for all tests in a class:

public MethodRule watchman = new TestWatchman() {
   public void starting(FrameworkMethod method) {
      System.out.println("Starting test: " + method.getName());

Entity Framework .Remove() vs. .DeleteObject()

If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()

ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)

Find Number of CPUs and Cores per CPU using Command Prompt

In order to check the absence of physical sockets run:

wmic cpu get SocketDesignation

Save ArrayList to SharedPreferences

The best way i have been able to find is a make a 2D Array of keys and put the custom items of the array in the 2-D array of keys and then retrieve it through the 2D arra on startup. I did not like the idea of using string set because most of the android users are still on Gingerbread and using string set requires honeycomb.

Sample Code: here ditor is the shared pref editor and rowitem is my custom object.

editor.putString(genrealfeedkey[j][1], Rowitemslist.get(j).getname());
        editor.putString(genrealfeedkey[j][2], Rowitemslist.get(j).getdescription());
        editor.putString(genrealfeedkey[j][3], Rowitemslist.get(j).getlink());
        editor.putString(genrealfeedkey[j][4], Rowitemslist.get(j).getid());
        editor.putString(genrealfeedkey[j][5], Rowitemslist.get(j).getmessage());

warning: implicit declaration of function

When you get the error: implicit declaration of function it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname and look at the SYNOPSIS section at the top, as this section will list any header files that need to be included. Or try This is the online man pages they are hyperlinked and easy to search. Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,

You are using a function for which the compiler has not seen a declaration ("prototype") yet.

Searching a list of objects in Python

[x for x in myList if x.n == 30]               # list of all matches
[x.n_squared for x in myList if x.n == 30]     # property of matches
any(x.n == 30 for x in myList)                 # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30]  # indices of all matches

def first(iterable, default=None):
  for item in iterable:
    return item
  return default

first(x for x in myList if x.n == 30)          # the first match, if any

What is "pom" packaging in maven?

Packaging an artifact as POM means that it has a very simple lifecycle

package -> install -> deploy

This is useful if you are deploying a pom.xml file or a project that doesn't fit with the other packaging types.

We use pom packaging for many of our projects and bind extra phases and goals as appropriate.

For example some of our applications use:

prepare-package -> test -> package -> install -> deploy

When you mvn install the application it should add it to your locally .m2 repository. To publish elsewhere you will need to set up correct distribution management information. You may also need to use the maven builder helper plugin, if artifacts aren't automatically attached to by Maven.

Data access object (DAO) in Java

Spring JPA DAO

For example we have some entity Group.

For this entity we create the repository GroupRepository.

public interface GroupRepository extends JpaRepository<Group, Long> {   

Then we need to create a service layer with which we will use this repository.

public interface Service<T, ID> {

    T save(T entity);

    void deleteById(ID id);

    List<T> findAll();

    T getOne(ID id);

    T editEntity(T entity);

    Optional<T> findById(ID id);

public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {

    private final R repository;

    protected AbstractService(R repository) {
        this.repository = repository;

    public T save(T entity) {

    public void deleteById(ID id) {

    public List<T> findAll() {
        return repository.findAll();

    public T getOne(ID id) {
        return repository.getOne(id);

    public Optional<T> findById(ID id) {
        return repository.findById(id);

    public T editEntity(T entity) {
        return repository.saveAndFlush(entity);

public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {

    private final GroupRepository groupRepository;

    protected GroupServiceImpl(GroupRepository repository) {
        this.groupRepository = repository;

And in the controller we use this service.

class GroupController {

    private final Logger log = LoggerFactory.getLogger(GroupController.class);

    private final GroupServiceImpl groupService;

    public GroupController(GroupServiceImpl groupService) {
        this.groupService = groupService;

    Collection<Group> groups() {
        return groupService.findAll();

    ResponseEntity<?> getGroup(@PathVariable Long id) {
        Optional<Group> group = groupService.findById(id);
        return -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));

    ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {"Request to create group: {}", group);
        Group result =;
        return ResponseEntity.created(new URI("/api/group/" + result.getId()))

    ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {"Request to update group: {}", group);
        Group result =;
        return ResponseEntity.ok().body(result);

    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {"Request to delete group: {}", id);
        return ResponseEntity.ok().build();

Java string to date conversion

While on dealing with the SimpleDateFormat class, it's important to remember that Date is not thread-safe and you can not share a single Date object with multiple threads.

Also there is big difference between "m" and "M" where small case is used for minutes and capital case is used for month. The same with "d" and "D". This can cause subtle bugs which often get overlooked. See Javadoc or Guide to Convert String to Date in Java for more details.

How to get error message when ifstream open fails

You could try letting the stream throw an exception on failure:

std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;

try {;
catch (std::ios_base::failure& e) {
  std::cerr << e.what() << '\n';

e.what(), however, does not seem to be very helpful:

  • I tried it on Win7, Embarcadero RAD Studio 2010 where it gives "ios_base::failbit set" whereas strerror(errno) gives "No such file or directory."
  • On Ubuntu 13.04, gcc 4.7.3 the exception says "basic_ios::clear" (thanks to arne)

If e.what() does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition (C++11 only):

catch (std::ios_base::failure& e) {
  if ( e.code() == std::make_error_condition(std::io_errc::stream) )
    std::cerr << "Stream error!\n"; 
    std::cerr << "Unknown failure opening file.\n";

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

Official reasons for "Software caused connection abort: socket write error"

To prove which component fails I would monitor the TCP/IP communication using wireshark and look who is actaully closing the port, also timeouts could be relevant.

Vim clear last search highlighting

My original solution (below) was dirty and wasteful. I now use :noh

Like many features in Vim, the right way is often not easily discoverable.



Search for an unlikely character sequence (mash the keys on the home row):


This works in vim and less, and it's easier to remember/type than @ShaunBouckaert's logically cleaner solution "to clear the last used search pattern":

:let @/ = ""

A potential downside is that it adds junk to your search history.

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".

Simplest way to merge ES6 Maps/Sets?

No, there are no builtin operations for these, but you can easily create them your own:

Map.prototype.assign = function(...maps) {
    for (const m of maps)
        for (const kv of m)
    return this;

Set.prototype.concat = function(...sets) {
    const c = this.constructor;
    let res = new (c[Symbol.species] || c)();
    for (const set of [this, ...sets])
        for (const v of set)
    return res;

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

This type of issue crops up for me now that I've moved to Python 3. I had no idea Python 2 was simply steam rolling any issues with file encoding.

I found this nice explanation of the differences and how to find a solution after none of the above worked for me.

In short, to make Python 3 behave as similarly as possible to Python 2 use:

with open(filename, encoding="latin-1") as datafile:
    # work on datafile here

However, read the article, there is no one size fits all solution.

How can I get the count of line in a file in an efficient way?

The buffered reader is overkill

Reader r = new FileReader("f.txt");

int count = 0;
int nextchar = 0;
while (nextchar != -1){
        nextchar =;
        if (nextchar == Character.getNumericValue('\n') ){

My search for a simple example has createde one thats actually quite poor. calling read() repeadedly for a single character is less than optimal. see here for examples and measurements.

Java: Get first item from a collection

You could do this:

String strz[] = strs.toArray(String[strs.size()]);
String theFirstOne = strz[0];

The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
>>> y=complex(3,4)
>>> print y
>>> z=x+y
>>> print x
>>> print z
>>> z=x*y
>>> print z
>>> z=x/y
>>> print z
>>> print x.conjugate()
>>> print x.imag
>>> print x.real
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y

TypeError: 'str' object is not callable (Python)

It is important to note (in case you came here by Google) that "TypeError: 'str' object is not callable" means only that a variable that was declared as String-type earlier is attempted to be used as a function (e.g. by adding parantheses in the end.)

You can get the exact same error message also, if you use any other built-in method as variable name.

.NET console application as Windows service

So here's the complete walkthrough:

  1. Create new Console Application project (e.g. MyService)
  2. Add two library references: System.ServiceProcess and System.Configuration.Install
  3. Add the three files printed below
  4. Build the project and run "InstallUtil.exe c:\path\to\MyService.exe"
  5. Now you should see MyService on the service list (run services.msc)

*InstallUtil.exe can be usually found here: C:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.ex??e


using System;
using System.IO;
using System.ServiceProcess;

namespace MyService
    class Program
        public const string ServiceName = "MyService";

        static void Main(string[] args)
            if (Environment.UserInteractive)
                // running as console app

                Console.WriteLine("Press any key to stop...");

                // running as service
                using (var service = new Service())

        public static void Start(string[] args)
            File.AppendAllText(@"c:\temp\MyService.txt", String.Format("{0} started{1}", DateTime.Now, Environment.NewLine));

        public static void Stop()
            File.AppendAllText(@"c:\temp\MyService.txt", String.Format("{0} stopped{1}", DateTime.Now, Environment.NewLine));


using System.ServiceProcess;

namespace MyService
    class Service : ServiceBase
        public Service()
            ServiceName = Program.ServiceName;

        protected override void OnStart(string[] args)

        protected override void OnStop()


using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace MyService
    public class MyServiceInstaller : Installer
        public MyServiceInstaller()
            var spi = new ServiceProcessInstaller();
            var si = new ServiceInstaller();

            spi.Account = ServiceAccount.LocalSystem;
            spi.Username = null;
            spi.Password = null;

            si.DisplayName = Program.ServiceName;
            si.ServiceName = Program.ServiceName;
            si.StartType = ServiceStartMode.Automatic;


How do I detect a page refresh using jquery?

There are two events on client side as given below.

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

2. window.onload (calls on Page Load)

On server Side

public JsonResult TestAjax( string IsRefresh)
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);

On Client Side

 <script type="text/javascript">_x000D_
    window.onbeforeunload = function (e) {_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: { IsRefresh: 'Close' }_x000D_
    window.onload = function (e) {_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: {IsRefresh:'Load'}_x000D_

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

Get number of digits with JavaScript

Since this came up on a Google search for "javascript get number of digits", I wanted to throw it out there that there is a shorter alternative to this that relies on internal casting to be done for you:

var int_number = 254;
var int_length = (''+int_number).length;

var dec_number = 2.12;
var dec_length = (''+dec_number).length;

console.log(int_length, dec_length);


3 4

How to create a HashMap with two keys (Key-Pair, Value)?

You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.

Create an object called Index that takes an x and y value.

public class Index {

    private int x;
    private int y;

    public Index(int x, int y) {
        this.x = x;
        this.y = y;

    public int hashCode() {
        return this.x ^ this.y;

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Index other = (Index) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;

Then have your HashMap<Index, Value> to get your result. :)

Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

return str.replace(/\s/g, '');

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

Explicitly mention the ubuntu version in the docker file which you are trying to RUN,

FROM ubuntu:14.04

Dont use like FROM ubuntu:Latest. This resolved my above "Cannot Start Container: stat /bin/sh: no such file or directory" issue

Installing mcrypt extension for PHP on OSX Mountain Lion

Brew base solution worked for me

  1. Install these packages

    $brew install brew install mcrypt php54-mcrypt

  2. Copy default php.ini.default to php.ini

    $sudo cp /private/etc/php.ini.default /private/etc/php.ini

  3. Add this line to php.ini file extension section - please verify extension path with install location in your machine


  4. Restart your apache server

    $apache restart

jQuery: how to change title of document during .ready()?

Like this:

$(document).ready(function ()
    document.title = "Hello World!";

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 

How to force open links in Chrome not download them?

Google, as of now, cannot open w/out saving. As a workaround, I use IE Tab from the Chrome Store. It is an extension that runs IE - which does allow opening w/ out saving- inside of the Chrome browser application.

Not the best solution, but it's an effective "patch" for now.

System.currentTimeMillis vs System.nanoTime

For game graphics & smooth position updates, use System.nanoTime() rather than System.currentTimeMillis(). I switched from currentTimeMillis() to nanoTime() in a game and got a major visual improvement in smoothness of motion.

While one millisecond may seem as though it should already be precise, visually it is not. The factors nanoTime() can improve include:

  • accurate pixel positioning below wall-clock resolution
  • ability to anti-alias between pixels, if you want
  • Windows wall-clock inaccuracy
  • clock jitter (inconsistency of when wall-clock actually ticks forward)

As other answers suggest, nanoTime does have a performance cost if called repeatedly -- it would be best to call it just once per frame, and use the same value to calculate the entire frame.

href="javascript:" vs. href="javascript:void(0)"

This method seems ok in all browsers, if you set the onclick with a jQuery event:

<a href="javascript:;">Click me!</a>

As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.

How do you strip a character out of a column in SQL Server?

This is done using the REPLACE function

To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:

SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn]  FROM [SomeTable]

To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"

UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')

Check if selected dropdown value is empty using jQuery

You forgot the # on the id selector:

if ($("#EventStartTimeMin").val() === "") {
    // ...

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

Eloquent: find() and where() usage laravel

Your code looks fine, but there are a couple of things to be aware of:

Post::find($id); acts upon the primary key, if you have set your primary key in your model to something other than id by doing:

protected  $primaryKey = 'slug';

then find will search by that key instead.

Laravel also expects the id to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:

public $incrementing = false;

Why can't static methods be abstract in Java?

You can't override a static method, so making it abstract would be meaningless. Moreover, a static method in an abstract class would belong to that class, and not the overriding class, so couldn't be used anyway.

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

Strip Leading and Trailing Spaces From Java String

To trim specific char, you can use:

String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")

Here will strip leading and trailing space and comma.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

pass $connect as your first parameter in mysqli_real_escape_string for this first make connection then do here

How to sort a list of objects based on an attribute of the objects?

# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

More on sorting by keys.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Access elements in json object like an array

var coordinates = [jsonObject[3][0], 

How to select distinct rows in a datatable and store into an array

Following single line of code will avoid the duplicate rows of a DataTable:

dataTable.DefaultView.ToTable(true, "employeeid");


  • first parameter in ToTable() is a boolean which indicates whether you want distinct rows or not.

  • second parameter in the ToTable() is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable.

The same can be done from a DataSet, by accessing a specific DataTable:

dataSet.Tables["Employee"].DefaultView.ToTable(true, "employeeid");

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

    CTE_Sysession (AgentStartDate)
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

HTTP GET Request in Node.js Express

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for GET method request:

var requestify = require('requestify');

  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)

Adding values to Arraylist

First simple rule: never use the String(String) constructor, it is absolutely useless (*).

So arr.add("ss") is just fine.

With 3 it's slightly different: 3 is an int literal, which is not an object. Only objects can be put into a List. So the int will need to be converted into an Integer object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3) which can (and will) avoid creating a new Integer instance in some cases.

So actually writing arr.add(3) is usually a better idea than using arr.add(new Integer(3)), because it can avoid creating a new Integer object and instead reuse and existing one.

Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.

(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)

Laravel update model with unique validation rule for attribute

A simple example for roles update

// model/User.php
class User extends Eloquent

    public static function rolesUpdate($id)
        return array(
            'username'              => 'required|alpha_dash|unique:users,username,' . $id,
            'email'                 => 'required|email|unique:users,email,'. $id,
            'password'              => 'between:4,11',


// controllers/UsersControllers.php
class UsersController extends Controller

    public function update($id)
        $user = User::find($id);
        $validation = Validator::make($input, User::rolesUpdate($user->id));

        if ($validation->passes())

            return Redirect::route('', $id);

        return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);


How do I know if jQuery has an Ajax request pending?

The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:

1) null, meaning that no request has been sent yet

2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.

In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)

Use CSS to automatically add 'required field' asterisk to form inputs

input[required], select[required] {
    background-image: url('/img/star.png');
    background-repeat: no-repeat;
    background-position-x: right;

Image has some 20px space on the right not to overlap with select dropdown arrow

enter image description here

And it looks like this: enter image description here

How do I add a newline to a TextView in Android?

Side note: Capitalising text using


or similar seems to stop the \n from working.

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;


Get the date of next monday, tuesday, etc

I know it's a bit of a late answer but I would like to add my answer for future references.

// Create a new DateTime object
$date = new DateTime();

// Modify the date it contains
$date->modify('next monday');

// Output
echo $date->format('Y-m-d');

The nice thing is that you can also do this with dates other than today:

// Create a new DateTime object
$date = new DateTime('2006-05-20');

// Modify the date it contains
$date->modify('next monday');

// Output
echo $date->format('Y-m-d');

To make the range:

$monday = new DateTime('monday');

// clone start date
$endDate = clone $monday;

// Add 7 days to start date
$endDate->modify('+7 days');

// Increase with an interval of one day
$dateInterval = new DateInterval('P1D');

$dateRange = new DatePeriod($monday, $dateInterval, $endDate);

foreach ($dateRange as $day) {
    echo $day->format('Y-m-d')."<br />";


PHP Manual - DateTime

PHP Manual - DateInterval

PHP Manual - DatePeriod

PHP Manual - clone

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Sort a list by multiple attributes?

A key can be a function that returns a tuple:

s = sorted(s, key = lambda x: (x[1], x[2]))

Or you can achieve the same using itemgetter (which is faster and avoids a Python function call):

import operator
s = sorted(s, key = operator.itemgetter(1, 2))

And notice that here you can use sort instead of using sorted and then reassigning:

s.sort(key = operator.itemgetter(1, 2))

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

MySQL and PHP - insert NULL rather than empty string

To pass a NULL to MySQL, you do just that.

INSERT INTO table (field,field2) VALUES (NULL,3)

So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

Safely turning a JSON string into an object

Try this.This one is written in typescript.

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;

Check if a string is a date value

Use Regular expression to validate it.


        const _regExp  = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$');
        return _regExp.test(_date);

How to make Java honor the DNS Caching Timeout?

This has obviously been fixed in newer releases (SE 6 and 7). I experience a 30 second caching time max when running the following code snippet while watching port 53 activity using tcpdump.

 * Result: Java 6 distributed with Ubuntu 12.04 and Java 7 u15 downloaded from Oracle have
 * an expiry time for dns lookups of approx. 30 seconds.

import java.util.*;
import java.text.*;


public class Test {
    final static String hostname = "";
    public static void main(String[] args) {
        // only required for Java SE 5 and lower:
        //Security.setProperty("networkaddress.cache.ttl", "30");


        while(true) {
            int i = 0;
            try {
                InetAddress inetAddress = InetAddress.getLocalHost();
                System.out.println(new Date());
                inetAddress = InetAddress.getByName(hostname);
                displayStuff(hostname, inetAddress);
            } catch (UnknownHostException e) {
            try {
            } catch(Exception ex) {}

    public static void displayStuff(String whichHost, InetAddress inetAddress) {
        System.out.println("Which Host:" + whichHost);
        System.out.println("Canonical Host Name:" + inetAddress.getCanonicalHostName());
        System.out.println("Host Name:" + inetAddress.getHostName());
        System.out.println("Host Address:" + inetAddress.getHostAddress());

    public static void makeRequest() {
        try {
            URL url = new URL("http://"+hostname+"/");
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            InputStreamReader ird = new InputStreamReader(is);
            BufferedReader rd = new BufferedReader(ird);
            String res;
            while((res = rd.readLine()) != null) {
        } catch(Exception ex) {

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

Getting Hour and Minute in PHP

Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use date_default_timezone_set() then use one of the supported timezones.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I was having this issue as well and the problem was in the view controllers. I'm not sure how your application is structured, so I'll just explain what I found. I'm pretty new to xcode and coding, so bear with me.

I was trying to programmatically change the text on a UILabel. Using "self.mylabel.text" worked fine until I added another view controller under the same class that didn't also include that label. That is when I got the error that you're seeing. When I added the same UILabel and connected it into that additional view controller, the error went away.

In short, it seems that in Swift, all view controllers assigned to the same class have to reference the code you have in there, or else you get an error. If you have two different view controllers with different code, assign them to different classes. This worked for me and hopefully applies to what you're doing.

$apply already in progress error

If scope must be applied in some cases, then you can set a timeout so that the $apply is deferred until the next tick

setTimeout(function(){ scope.$apply(); });

or wrap your code in a $timeout(function(){ .. }); because it will automatically $apply the scope at the end of execution. If you need your function to behave synchronously, I'd do the first.

How to load all modules in a folder?

This is the best way i've found so far:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

How do you create a static class in C++?

You can also create a free function in a namespace:

In BitParser.h

namespace BitParser
    bool getBitAt(int buffer, int bitIndex);

In BitParser.cpp

namespace BitParser
    bool getBitAt(int buffer, int bitIndex)
        //get the bit :)

In general this would be the preferred way to write the code. When there's no need for an object don't use a class.

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Just open the R(software) and copy and paste

system("defaults write org.R-project.R force.LANG en_US.UTF-8")

Hope this will work fine or use the other method

open(on mac): Utilities/Terminal copy and paste

defaults write org.R-project.R force.LANG en_US.UTF-8

and close both terminal and R and reopen R.

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Yes even I got the same error. So I did the following changes

-> Check the error in the Problems tab located near the Console tab

-> See where the error persists, Its possible that some jar file may be corrupted or is outdated so, pom isn't activated in the Project.

-> I found one of my jar was outdated version so I updated it by getting the dependencies from maven repository from this link

So to conclude, do check where the error persist and which jar file is outdated and make changes accordingly

How do I upload a file to an SFTP server in C# (.NET)?

There is no solution for this within the .net framework. outlines a list of un-free options.

your best free bet is to extend SSH using Granados.

How to run a Command Prompt command with Visual Basic code?

Or, you could do it the really simple way.

Dim OpenCMD 
OpenCMD = CreateObject("")"Command Goes Here")

Getting Python error "from: can't read /var/mail/Bio"

No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named, you have to execute it as python, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).

Another possibility is to add the following line to the top of the script:

#!/usr/bin/env python

This will instruct your shell to execute the script via python instead of trying to interpret it on its own.

Getting the current Fragment instance in the viewpager

You can declare an Array of fragment as register fragments

class DashboardPagerAdapter(fm: FragmentManager?) : FragmentStatePagerAdapter(fm!!) {
    val registeredFragments = SparseArray<Fragment>()

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val fragment = super.instantiateItem(container, position) as Fragment
        registeredFragments.put(position, fragment)
        return fragment

    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> HomeFragment.newInstance()
            1 -> ConverterDashboardFragment.newInstance()
            2 -> CartFragment.newInstance()
            3 -> CustomerSupportFragment.newInstance()
            4 -> ProfileFragment.newInstance()
            else -> ProfileFragment.newInstance()

    override fun getCount(): Int {
        return 5


Then you can use it as

adapter?.let {
    val cartFragment = it.registeredFragments[2] as CartFragment?

How to lock specific cells but allow filtering and sorting

I had a simular problem. I wanted the user to be able to filter "Table3" in a protected worksheet. But the user is not able to edit the table. I accomplished above, using the vba code below:

Selection.Locked = True
Selection.FormulaHidden = False 
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
    , allowfiltering:=True

In the following code I filtered the code using VBA:

ActiveSheet.ListObjects("Table3").Range.AutoFilter Field:=8, Criteria1:= _
    Array("1", "12", "2", "24", "4", "6"), Operator:=xlFilterValues

Pushing empty commits to remote

Is there any disadvantages/consequences of pushing empty commits?

Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.

You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f back to remote.

extract the date part from DateTime in C#

There is no way to "discard" the time component.

DateTime.Today is the same as:

DateTime d = DateTime.Now.Date;

If you only want to display only the date portion, simply do that - use ToString with the format string you need.

For example, using the standard format string "D" (long date format specifier):


Leader Not Available Kafka in Console Producer

If you are running kafka on local machine, try updating $KAFKA_DIR/config/ with below line: listeners=PLAINTEXT://localhost:9092 and then restarting kafka.

javascript password generator

This is my function for generating a 8-character crypto-random password:

function generatePassword() {
    var buf = new Uint8Array(6);
    return btoa(String.fromCharCode.apply(null, buf));

What it does: Retrieves 6 crypto-random 8-bit integers and encodes them with Base64.

Since the result is in the Base64 character set the generated password may consist of A-Z, a-z, 0-9, + and /.

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

MySQL: Quick breakdown of the types of joins

I have 2 tables like this:

> SELECT * FROM table_a;
| id   | name |
|    1 | row1 |
|    2 | row2 |

> SELECT * FROM table_b;
| id   | name | aid  |
|    3 | row3 |    1 |
|    4 | row4 |    1 |
|    5 | row5 | NULL |

INNER JOIN cares about both tables

INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.

> SELECT * FROM table_a a INNER JOIN table_b b ON;
| id   | name | id   | name | aid  |
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |

It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:

> SELECT * FROM table_b b INNER JOIN table_a a ON;
| id   | name | aid  | id   | name |
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |

You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.

LEFT JOIN only cares about the first table

LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:

> SELECT * FROM table_a a LEFT JOIN table_b b ON;
| id   | name | id   | name | aid  |
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
|    2 | row2 | NULL | NULL | NULL |

Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.

If we reverse the order of the tables, LEFT JOIN behaves differently:

> SELECT * FROM table_b b LEFT JOIN table_a a ON;
| id   | name | aid  | id   | name |
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
|    5 | row5 | NULL | NULL | NULL |

Now we get all rows of table_b, but only matching rows of table_a.

RIGHT JOIN only cares about the second table

a RIGHT JOIN b gets you exactly the same rows as b LEFT JOIN a. The only difference is the default order of the columns.

> SELECT * FROM table_a a RIGHT JOIN table_b b ON;
| id   | name | id   | name | aid  |
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
| NULL | NULL |    5 | row5 | NULL |

This is the same rows as table_b LEFT JOIN table_a, which we saw in the LEFT JOIN section.


> SELECT * FROM table_b b RIGHT JOIN table_a a ON;
| id   | name | aid  | id   | name |
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
| NULL | NULL | NULL |    2 | row2 |

Is the same rows as table_a LEFT JOIN table_b.

No join at all gives you copies of everything

If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:

> SELECT * FROM table_b b, table_a;
| id   | name | aid  | id   | name |
|    3 | row3 | 1    |    1 | row1 |
|    3 | row3 | 1    |    2 | row2 |
|    4 | row4 | 1    |    1 | row1 |
|    4 | row4 | 1    |    2 | row2 |
|    5 | row5 | NULL |    1 | row1 |
|    5 | row5 | NULL |    2 | row2 |

(This is from my blog post Examples of SQL join types)

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

This answer may have to be modified depending on what you were trying to achieve with position: fixed;. If all you want is two columns side by side then do the following:

I floated both columns to the left.

Note: I added min-height to each column for illustrative purposes and I simplified your CSS.

body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  float: left;_x000D_
  min-height: 450px;_x000D_
  color: white;_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
  <div id="rightcolumn">_x000D_

If you would like the left column to stay in place as you scroll do the following:

Here we float the right column to the right while adding position: relative; to #wrapper and position: fixed; to #leftcolumn.

Note: I again used min-height for illustrative purposes and can be removed for your needs.

body {_x000D_
  background-color: #444;_x000D_
  margin: 0;_x000D_
#wrapper {_x000D_
  width: 1005px;_x000D_
  margin: 0 auto;_x000D_
  position: relative;_x000D_
#rightcolumn {_x000D_
  border: 1px solid white;_x000D_
  min-height: 750px;_x000D_
  color: white;_x000D_
#leftcolumn {_x000D_
  width: 250px;_x000D_
  background-color: #111;_x000D_
  min-height: 100px;_x000D_
  position: fixed;_x000D_
#rightcolumn {_x000D_
  width: 750px;_x000D_
  background-color: #777;_x000D_
  float: right;_x000D_
<div id="wrapper">_x000D_
  <div id="leftcolumn">_x000D_
  <div id="rightcolumn">_x000D_

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

How do I send a cross-domain POST request via JavaScript?

If you control the remote server, you should probably use CORS, as described in this answer; it's supported in IE8 and up, and all recent versions of FF, GC, and Safari. (But in IE8 and 9, CORS won't allow you to send cookies in the request.)

So, if you don't control the remote server, or if you have to support IE7, or if you need cookies and you have to support IE8/9, you'll probably want to use an iframe technique.

  1. Create an iframe with a unique name. (iframes use a global namespace for the entire browser, so pick a name that no other website will use.)
  2. Construct a form with hidden inputs, targeting the iframe.
  3. Submit the form.

Here's sample code; I tested it on IE6, IE7, IE8, IE9, FF4, GC11, S5.

function crossDomainPost() {
  // Add the iframe with a unique name
  var iframe = document.createElement("iframe");
  document.body.appendChild(iframe); = "none"; = uniqueString;

  // construct a form with hidden inputs, targeting the iframe
  var form = document.createElement("form"); = uniqueString;
  form.action = "http://INSERT_YOUR_URL_HERE";
  form.method = "POST";

  // repeat for each parameter
  var input = document.createElement("input");
  input.type = "hidden"; = "INSERT_YOUR_PARAMETER_NAME_HERE";


Beware! You won't be able to directly read the response of the POST, since the iframe exists on a separate domain. Frames aren't allowed to communicate with each other from different domains; this is the same-origin policy.

If you control the remote server but you can't use CORS (e.g. because you're on IE8/IE9 and you need to use cookies), there are ways to work around the same-origin policy, for example by using window.postMessage and/or one of a number of libraries allowing you to send cross-domain cross-frame messages in older browsers:

If you don't control the remote server, then you can't read the response of the POST, period. It would cause security problems otherwise.

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

Download JSON object as a file from browser

Simple, clean solution for those who only target modern browsers:

function downloadTextFile(text, name) {
  const a = document.createElement('a');
  const type = name.split(".").pop();
  a.href = URL.createObjectURL( new Blob([text], { type:`text/${type === "txt" ? "plain" : type}` }) ); = name;;

downloadTextFile(JSON.stringify(myObj), 'myObj.json');

What size do you use for varchar(MAX) in your parameter declaration?

If you do something like this:

    cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

size will be taken from "some large text".Length

This can be problematic when it's an output parameter, you get back no more characters then you put as input.

What is "Connect Timeout" in sql server connection string?

How a connection works in a nutshell

A connection between a program and a database server relies on a handshake.

What this means is that when a connection is opened then the thread establishing the connection will send network packets to the database server. This thread will then pause until either network packets about this connection are received from the database server or when the connection timeout expires.

The connection timeout

The connection timeout is measured in seconds from the point the connection is opened.

When the timeout expires then the thread will continue, but it will do so having reported a connection failure.

  • If there is no value specified for connection timeout in the connection string then the default value is 30.

  • A value greater than zero means how many seconds before it gives up e.g. a value of 10 means to wait 10 seconds.

  • A value of 0 means to never give up waiting for the connection

Note: A value of 0 is not advised since it is possible for either the connection request packets or the server response packets to get lost. Will you seriously be prepared to wait even a day for a response that may never come?

What should I set my Connection Timeout value to?

This setting should depend on the speed of your network and how long you are prepared to allow a thread to wait for a response.

As an example, on a task that repeats hourly during the day, I know my network has always responded within one second so I set the connection timeout to a value of 2 just to be safe. I will then try again three times before giving up and either raising a support ticket or escalating a similar existing support ticket.

Test your own network speed and consider what to do when a connection fails as a one off, and also when it fails repeatedly and sporadically.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:



Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:


UITextField border color

If you use a TextField with rounded corners use this code:

    self.TextField.layer.borderColor=[[UIColor redColor]CGColor];
    self.TextField.layer.borderWidth= 1.0f;

To remove the border:

self.TextField.layer.borderColor=[[UIColor clearColor]CGColor];

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem


Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

Flash CS4 refuses to let go

Do you have several swf-files? If your class is imported in one of the swf's, other swf's will also use the same version of the class. One old import with * in one swf will do it. Recompile everything and see if it works.

Python: Finding differences between elements of a list

I suspect this is what the numpy diff command does anyway, but just for completeness you can simply difference the sub-vectors:

from numpy import array as a

In addition, I wanted to add these solutions to generalizations of the question:

Solution with periodic boundaries

Sometimes with numerical integration you will want to difference a list with periodic boundary conditions (so the first element calculates the difference to the last. In this case the numpy.roll function is helpful:


Solutions with zero prepended

Another numpy solution (just for completeness) is to use


This works as numpy.diff, but only on a vector (it flattens the input array). It offers the ability to prepend or append numbers to the resulting vector. This is useful when handling accumulated fields that is often the case fluxes in meteorological variables (e.g. rain, latent heat etc), as you want a resulting list of the same length as the input variable, with the first entry untouched.

Then you would write


Of course, you can also do this with the np.diff command, in this case though you need to prepend zero to the series with the prepend keyword:


All the above solutions return a vector that is the same length as the input.

What is the Python equivalent of static variables inside a function?

Other answers have demonstrated the way you should do this. Here's a way you shouldn't:

>>> def foo(counter=[0]):
...   counter[0] += 1
...   print("Counter is %i." % counter[0]);
>>> foo()
Counter is 1.
>>> foo()
Counter is 2.

Default values are initialized only when the function is first evaluated, not each time it is executed, so you can use a list or any other mutable object to store static values.

Docker compose port mapping

It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container. helped me get to the right answer.

First, you'll need to install the nc command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.

Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.

# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY /usr/local/bin/
RUN chmod +x /usr/local/bin/
CMD ["/usr/local/bin/"]

Finally, we'll need to set up port-forwarding in I found that nc, even with the -l and -k options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.

#! /usr/bin/env bash

while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &

tail -f /dev/null # Or any other command that never exits

How do you add an in-app purchase to an iOS application?

RMStore is a lightweight iOS library for In-App Purchases. It wraps StoreKit API and provides you with handy blocks for asynchronous requests. Purchasing a product is as easy as calling a single method.

For the advanced users, this library also provides receipt verification, content downloads and transaction persistence.

Jenkins pipeline how to change to another folder

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

    sh "pwd"

How to replace multiple patterns at once with sed?

echo "C:\Users\San.Tan\My Folder\project1" | sed -e 's/C:\\/mnt\/c\//;s/\\/\//g'


C:\Users\San.Tan\My Folder\project1


mnt/c/Users/San.Tan/My Folder/project1

in case someone needs to replace windows paths to Windows Subsystem for Linux(WSL) paths

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(;
ArrayList<String> myStringArray1 = new ArrayList<String>();
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    public void onClick(View v) {
        adapter = null;
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);

Can I hide the HTML5 number input’s spin box?

This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):

input::-webkit-inner-spin-button {_x000D_
    /* display: none; <- Crashes Chrome on hover */_x000D_
    -webkit-appearance: none;_x000D_
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */_x000D_
input[type=number] {_x000D_
    -moz-appearance:textfield; /* Firefox */_x000D_
<input type="number" step="0.01" />

You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":

Inspector for input type=number (Chrome)

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

How can I easily add storage to a VirtualBox machine with XP installed?

I am glad you were able to get this done in this manner, but you can (and I did) use the GParted tool for my Windows XP host by following the helpful entry by Eric. To re-iterate/expand on his solution (don't be afraid of the # steps, I'm trying to help newbies here, so there are necessarily more detailed instructions!):

  1. change the size of the virtual hard disk via the VBoxManage modifyhd command, which is well-documented here and in the VirtualBox documentation.

  2. download the GParted-live ( or search the internet for GParted-live ISO. The important part is to get the live (.iso) verison, which is in the form of a bootable .ISO (CD) image.

  3. Mount this new .ISO to the CD virtual drive in the host machine's Storage settings

  4. If necessary/desired, change the boot order in the System settings for the host machine, to boot from CD before Hard Disk (alternatively, you can press F12 when it's booting up, and select the device)

  5. start your VM; if you changed the boot order, it will boot to the GParted-live ISO; otherwise press F12 to do this.

  6. do not be afraid or get too confused/wrapped up in the initial options you are presented; I selected all the defaults (booting to GParted default, default key mapping, language (assuming English - sorry for my non-English friends!), display, etc.). Read it, but just press enter at each prompt. With a Windows VM you should be fine with all the defaults, and if you're not, you're not going to break anything, and the instructions are pretty good about what to do if the defaults don't work.

  7. it will boot to a GUI environment and start the GParted utility. Highlight the c: drive (assuming that's the drive you want to increase the size on) and select resize/move.

  8. change to the new size you want in MB (they abbreviate MiB) - just add the new amount available (represented in the bottom number - MiB following) to the middle number. E.g: I changed mine from like 4000 MiB (e.g., 4GB - my initial size) to 15000 MiB (15 GB) because I'd added 10 GB to my virtual disk. Then click OK.

  9. Click Apply. Once it's done you'll have to reboot - for whatever reason my mouse did not work on the desktop icons on the GUI (I could not click exit) so I just closed the VM window and selected reboot. I did not even have to unmount the ISO, it apparently did it automatically.

  10. Let Windows go through the disk check - remember, you just changed the size outside of Windows, so it has no record of this. This will presumably allow it to update itself with the new info. Once it completes and you log in, you'll likely be told that Windows needs to reboot to use your 'new device' (at least in XP it did for me). Just reboot and you are done!

python ValueError: invalid literal for float()

I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.

In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.

I was getting the error:

> '     0.00'
> 3 0 fast loop, delta =  10.0 weight =  0.0 
> '     0.00'
> 1 800 fast loop, delta = 10.0 weight =  0.0 
> '     0.00'
> 6 0 fast loop, delta =  10.0 weight =  0.0
> '     0\x00.0' 
> Traceback (most recent call last):
>   File "", line 172, in start
>     valueScale = float(answer_string) 
>     ValueError: invalid literal for float(): 0

After some research I wrote few lines of code that work in my case.

replyScale =
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
valueScale = float(answer_strip)

The answers in these posts helped:

  1. How to get rid of \x00 in my array of bytes?
  2. Invalid literal for float(): 0.000001, how to fix error?

How to change the default docker registry from to my private registry?

Earlier this could be achieved using DOCKER_OPTS in the /etc/default/docker config file which worked on Ubuntu 14:04 and had some issues on Ubuntu 15:04. Not sure if this has been fixed.

The below line needs to go into the file /etc/default/docker on the host which runs the docker daemon. The change points to the private registry is installed in your local network. Note: you would require to restart the docker service followed with this change.

DOCKER_OPTS="--insecure-registry <priv registry hostname/ip>:<port>"

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

vertical divider between two columns in bootstrap

Well here's another option which I've been using for some time now. It works great for me since I mostly need it do visually separate 2 cols. And it's also responsive. Which means that if I have columns next to each other in medium and large screen sizes, then I would use the class col-md-border, which would hide the separator on smaller screen sizes.


@media (min-width: 992px) {
    .col-md-border:not(:last-child) {
        border-right: 1px solid #d7d7d7;
    .col-md-border + .col-md-border {
        border-left: 1px solid #d7d7d7;
        margin-left: -1px;

In scss you can generate all needed classes probably from this:


@media(min-width: $screen-md-min) {
    .col-md-border {
        &:not(:last-child) {
            border-right: 1px solid #d7d7d7;

        & + .col-md-border {
            border-left: 1px solid #d7d7d7;
            margin-left: -1px;


<div class="row">
    <div class="col-md-6 col-md-border"></div>
    <div class="col-md-6 col-md-border"></div>

How it works:

The cols must be inside an element where there are no other cols otherwise the selectors might not work as expected.

.col-md-border:not(:last-child) matches all but the last element before .row close and adds right border to it.

.col-md-border + .col-md-border matches the second div with the same class if these two are next to each other and adds left border and -1px negative margin. Negative margin is why it doesn't matter anymore which column has greater height and the separator will be 1px the same height as the highest column.

It does also have some problems...

  1. When you try to be clever/lazy and use col-XX-X class together with hidden-XX/visible-XX classes inside the same row element.
  2. When you have a lot of columns and need a pixel perfect thing. Since it moves n-1 column 1px to the left.

... But on the other hand it's responsive, works great for simple html and it's easy to create these classes for all bootstrap screen sizes.

How to do a non-greedy match in grep?

Sorry I am 9 years late, but this might work for the viewers in 2020.

So suppose you have a line like "Hello my name is Jello". Now you want to find the words that start with 'H' and end with 'o', with any number of characters in between. And we don't want lines we just want words. So for that we can use the expression:

grep "H[^ ]*o" file

This will return all the words. The way this works is that: It will allow all the characters instead of space character in between, this way we can avoid multiple words in the same line.

Now you can replace the space character with any other character you want. Suppose the initial line was "Hello-my-name-is-Jello", then you can get words using the expression:

grep "H[^-]*o" file

How to run Pip commands from CMD

Make sure to also add "C:\Python27\Scripts" to your path. pip.exe should be in that folder. Then you can just run:

C:\> pip install modulename

Is embedding background image data into CSS as Base64 good or bad practice?

It's not a good idea when you want your images and style information to be cached separately. Also if you encode a large image or a significant number of images in to your css file it will take the browser longer to download the file leaving your site without any of the style information until the download completes. For small images that you don't intend on changing often if ever it is a fine solution.

as far as generating the base64 encoding:

Html.DropdownListFor selected value not being set

For me general solution :)

     var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
     if (selectedCity != null)
         @Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
         @Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

The provider is not compatible with the version of Oracle client

After several hours of troubleshooting, I found this issue to be caused by having Oracle.DataAccess.dll (v4.0) in my projects bin directory, but the runtime also loading Oracle.DataAccess.dll (v2.x) from the GAC. Removing and readding the Oracle.DataAccess entry in the project references solved the problem for me.

The other files mentioned here did not appear to be necessary in my situation.


The root cause of the "The provider is not compatible with the version of Oracle client" error is (generally) that the managed assembly is attempting to load unmanaged libraries which do not match versions. It appears you can force the Oracle driver to use the correct libraries by specifying the library path in the web.config1

      <add name="DllPath" value="C:\oracle\bin"/>
      <!-- ... -->

Passing command line arguments in Visual Studio 2010?

Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)

Greetings mic enter image description here

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!



<div class="wrapper">
  <div class="img">
    <img src="original.png">

How to put a horizontal divisor line between edit text's in a activity

How about defining your own view? I have used the class below, using a LinearLayout around a view whose background color is set. This allows me to pre-define layout parameters for it. If you don't need that just extend View and set the background color instead.

public class HorizontalRulerView extends LinearLayout {

    static final int COLOR = Color.DKGRAY;
    static final int HEIGHT = 2;
    static final int VERTICAL_MARGIN = 10;
    static final int HORIZONTAL_MARGIN = 5;
    static final int TOP_MARGIN = VERTICAL_MARGIN;
    static final int BOTTOM_MARGIN = VERTICAL_MARGIN;
    static final int LEFT_MARGIN = HORIZONTAL_MARGIN;
    static final int RIGHT_MARGIN = HORIZONTAL_MARGIN;

    public HorizontalRulerView(Context context) {
        this(context, null);

    public HorizontalRulerView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);

    public HorizontalRulerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        View v = new View(context);
        LayoutParams lp = new LayoutParams(
        lp.topMargin = TOP_MARGIN;
        lp.bottomMargin = BOTTOM_MARGIN;
        lp.leftMargin = LEFT_MARGIN;
        lp.rightMargin = RIGHT_MARGIN;
        addView(v, lp);


Use it programmatically or in Eclipse (Custom & Library Views -- just pull it into your layout).

Why plt.imshow() doesn't display the image?

plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add

How to import a Python class that is in a directory above?

from ..subpkg2 import mod

Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328 deals with absolute/relative imports.

VSCode: How to Split Editor Vertically

In version 1.23.1, it is Ctrl+Shift+P and Split Editor This will divide the screens vertically and you can move through them using Ctrl+K+LeftArrow

Screenshot of the Split Editor

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

Python String and Integer concatenation

You can use a generator to do this !

def sequence_generator(limit):  
    """ A generator to create strings of pattern -> string1,string2..stringN """
    inc  = 0
    while inc < limit:
        yield 'string'+str(inc)
        inc += 1

# to generate a generator. notice i have used () instead of []
a_generator  =  (s for s in sequence_generator(10))

# to generate a list
a_list  =  [s for s in sequence_generator(10)]

# to generate a string
a_string =  '['+", ".join(s for s in sequence_generator(10))+']'

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

Capture Image from Camera and Display in Activity

Capture photo + Choose from Gallery:

        a = (ImageButton)findViewById(;

        a.setOnClickListener(new View.OnClickListener() {


            public void onClick(View v) {



    private File savebitmap(Bitmap bmp) {
      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
      OutputStream outStream = null;
     // String temp = null;
        File file = new File(extStorageDirectory, "temp.png");
      if (file.exists()) {
       file = new File(extStorageDirectory, "temp.png");


      try {
       outStream = new FileOutputStream(file);
       bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);

      } catch (Exception e) {
       return null;
      return file;
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;
     private void selectImage() {

            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            builder.setTitle("Add Photo!");

            builder.setItems(options, new DialogInterface.OnClickListener() {


                public void onClick(DialogInterface dialog, int item) {

                    if (options[item].equals("Take Photo"))


                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        //pic = f;

                        startActivityForResult(intent, 1);


                    else if (options[item].equals("Choose from Gallery"))


                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                        startActivityForResult(intent, 2);


                    else if (options[item].equals("Cancel")) {








        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == RESULT_OK) {

                if (requestCode == 1) {
                    File f = new File(Environment.getExternalStorageDirectory().toString());

                    for (File temp : f.listFiles()) {

                        if (temp.getName().equals("temp.jpg")) {

                            f = temp;
                            File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                           //pic = photo;



                    try {

                        Bitmap bitmap;

                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),



                        String path = android.os.Environment


                                + File.separator

                                + "Phoenix" + File.separator + "default";
                        //p = path;


                        OutputStream outFile = null;

                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

                        try {

                            outFile = new FileOutputStream(file);

                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);


                        } catch (FileNotFoundException e) {


                        } catch (IOException e) {


                        } catch (Exception e) {



                    } catch (Exception e) {



                } else if (requestCode == 2) {

                    Uri selectedImage = data.getData();
                   // h=1;
    //imgui = selectedImage;
                    String[] filePath = { MediaStore.Images.Media.DATA };

                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);


                    int columnIndex = c.getColumnIndex(filePath[0]);

                    String picturePath = c.getString(columnIndex);


                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));

                    Log.w("path of image from gallery......******************.........", picturePath+"");




SQL Update to the SUM of its joined values

With postgres, I had to adjust the solution with this to work for me:

UPDATE BookingPitches AS p
SET extrasPrice = t.sumPrice
        SELECT PitchID, SUM(Price) sumPrice
        FROM BookingPitchExtras
        WHERE [required] = 1
        GROUP BY PitchID 
    ) t
WHERE t.PitchID = p.ID AND p.bookingID = 1

What's the most appropriate HTTP status code for an "item not found" error page

That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like

400 (bad request) - indicates a bad request
412 (Precondition Failed) e.g. conflict by performing conditional update

More info in free InfoQ Explores: REST book.

Create a date from day month and year with T-SQL

You can also use

select DATEFROMPARTS(year, month, day) as ColDate, Col2, Col3 
From MyTable Where DATEFROMPARTS(year, month, day) Between @DateIni and @DateEnd

Works in SQL since ver.2012 and AzureSQL

How can I uninstall an application using PowerShell?

$app = Get-WmiObject -Class Win32_Product | Where-Object { 
    $_.Name -match "Software Name" 


Edit: Rob found another way to do it with the Filter parameter:

$app = Get-WmiObject -Class Win32_Product `
                     -Filter "Name = 'Software Name'"

SSIS Text was truncated with status value 4

In my case, some of my rows didn't have the same number of columns as the header. Example, Header has 10 columns, and one of your rows has 8 or 9 columns. (Columns = Count number of you delimiter characters in each line)

Tools for making latex tables in R

Thanks Joris for creating this question. Hopefully, it will be made into a community wiki.

The booktabs packages in latex produces nice looking tables. Here is a blog post on how to use xtable to create latex tables that use booktabs

I would also add the apsrtable package to the mix as it produces nice looking regression tables.

Another Idea: Some of these packages (esp. memisc and apsrtable) allow easy extensions of the code to produce tables for different regression objects. One such example is the lme4 memisc code shown in the question. It might make sense to start a github repository to collect such code snippets, and over time maybe even add it to the memisc package. Any takers?

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:


dunno about performance but, it is more flexible than a gsub, ie:


How to convert a DataTable to a string in C#?

I created my variant of class for your needs. I believe it is a bit more configurable than already provided variants. You can use it with all default settings just create an instance of a class and call StringifyDataTable method, or you can set additional options if needed.

public class DataTableStringifier
    public bool IsOuterBordersPresent { get; set; } //Whether outer borders of table needed
    public bool IsHeaderHorizontalSeparatorPresent { get; set; } // Whether horizontal line separator between table title and data is needed. Useful to set 'false' if you expect only 1 or 2 rows of data - no need for additional lines then
    public char ValueSeparator { get; set; } //Vertical line character
    public char HorizontalLinePadChar { get; set; } // Horizontal line character
    public char HorizontalLineSeparator { get; set; } // Horizontal border (between header and data) column separator (crossing of horizontal and vertical borders)
    public int ValueMargin { get; set; } // Horizontal margin from table borders (inner and outer) to cell values
    public int MaxColumnWidth { get; set; } // To avoid too wide columns with thousands of characters. Longer values will be cropped in the center
    public string LongValuesEllipses { get; set; } // Cropped values wil be inserted this string in the middle to mark the point of cropping

    public DataTableStringifier()
        MaxColumnWidth = int.MaxValue;
        IsHeaderHorizontalSeparatorPresent = true;
        ValueSeparator = '|';
        ValueMargin = 1;
        HorizontalLinePadChar = '-';
        HorizontalLineSeparator = '+';
        LongValuesEllipses = "...";
        IsOuterBordersPresent = false;

    public string StringifyDataTable(DataTable table)
        int colCount = table.Columns.Count;
        int rowCount = table.Rows.Count;
        string[] colHeaders = new string[colCount];
        string[,] cells = new string[rowCount, colCount];
        int[] colWidth = new int[colCount];

        for (int i = 0; i < colCount; i++)
            var column = table.Columns[i];
            var colName = ValueToLimitedLengthString(column.ColumnName);
            colHeaders[i] = colName;
            if (colWidth[i] < colName.Length)
                colWidth[i] = colName.Length;

        for (int i = 0; i < rowCount; i++)
            DataRow row = table.Rows[i];
            for (int j = 0; j < colCount; j++)
                var valStr = ValueToLimitedLengthString(row[j]);
                cells[i, j] = valStr;
                if (colWidth[j] < valStr.Length)
                    colWidth[j] = valStr.Length;

        string valueSeparatorWithMargin = string.Concat(new string(' ', ValueMargin), ValueSeparator, new string(' ', ValueMargin));
        string leftBorder = IsOuterBordersPresent ? string.Concat(ValueSeparator, new string(' ', ValueMargin)) : "";
        string rightBorder = IsOuterBordersPresent ? string.Concat(new string(' ', ValueMargin), ValueSeparator) : "";
        string horizLine = new string(HorizontalLinePadChar, colWidth.Sum() + (colCount - 1)*(ValueMargin*2 + 1) + (IsOuterBordersPresent ? (ValueMargin + 1)*2 : 0));

        StringBuilder tableBuilder = new StringBuilder();

        if (IsOuterBordersPresent)

        for (int i = 0; i < colCount; i++)
            if (i < colCount - 1)

        if (IsHeaderHorizontalSeparatorPresent)
            if (IsOuterBordersPresent)
                tableBuilder.Append(HorizontalLinePadChar, ValueMargin);
            for (int i = 0; i < colCount; i++)
                tableBuilder.Append(new string(HorizontalLinePadChar, colWidth[i]));
                if (i < colCount - 1)
                    tableBuilder.Append(HorizontalLinePadChar, ValueMargin);
                    tableBuilder.Append(HorizontalLinePadChar, ValueMargin);
            if (IsOuterBordersPresent)
                tableBuilder.Append(HorizontalLinePadChar, ValueMargin);

        for (int i = 0; i < rowCount; i++)
            for(int j=0; j<colCount; j++)
                tableBuilder.Append(cells[i, j].PadRight(colWidth[j]));

        if (IsOuterBordersPresent)

        return tableBuilder.ToString(0, tableBuilder.Length - 1); //Trim last enter char

    private string ValueToLimitedLengthString(object value)
        string strValue = value.ToString();
        if (strValue.Length > MaxColumnWidth)
            int beginningLength = (MaxColumnWidth) / 2;
            int endingLength = (MaxColumnWidth + 1) / 2 - LongValuesEllipses.Length;
            return string.Concat(strValue.Substring(0, beginningLength), LongValuesEllipses, strValue.Substring(strValue.Length - endingLength, endingLength));
            return strValue;

MySQL timezone change?

While Bryon's answer is helpful, I'd just add that his link is for PHP timezone names, which are not the same as MySQL timezone names.

If you want to set your timezone for an individual session to GMT+1 (UTC+1 to be precise) just use the string '+01:00' in that command. I.e.:

SET time_zone = '+01:00';

To see what timezone your MySQL session is using, just execute this:

SELECT @@global.time_zone, @@session.time_zone;

This is a great reference with more details: MySQL 5.5 Reference on Time Zones

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

adb devices command not working

I fixed this issue on my debian GNU/Linux system by overiding system rules that way :

mv  /etc/udev/rules.d/51-android.rules /etc/udev/rules.d/99-android.rules

I used contents from files linked at :

Tooltip on image

Using javascript, you can set tooltips for all the images on the page.

<!DOCTYPE html>
    <img src="" alt="Food">
    <img src="" alt="Pizza">
     //image objects
     var imageEls = document.getElementsByTagName("img");
     for(var i=0;i<imageEls.length;i++){
        //imageEls[i].title="Title of your choice";

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I stumbled upon another solution, which is quite nice.

Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)

public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 

Works as long as the component is in a package scanned by Spring. (Using @Primary is not mandatory in my case, but why not make things explicit.)

For me there are two benefits compared to the other approach:

  • This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
  • I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

Event system in Python

If you wanted to do more complicated things like merging events or retry you can use the Observable pattern and a mature library that implements that. . Observables are very common in Javascript and Java and very convenient to use for some async tasks.

from rx import Observable, Observer

def push_five_strings(observer):

class PrintObserver(Observer):

    def on_next(self, value):
        print("Received {0}".format(value))

    def on_completed(self):

    def on_error(self, error):
        print("Error Occurred: {0}".format(error))

source = Observable.create(push_five_strings)



Received Alpha
Received Beta
Received Gamma
Received Delta
Received Epsilon

Border color on default input style

I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;


Check if string contains only whitespace

for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :

if mystring and mystring.strip():
    print "not blank string"
    print "blank string"

Trim whitespace from a String

Here is how you can do it:

std::string & trim(std::string & str)
   return ltrim(rtrim(str));

And the supportive functions are implemeted as:

std::string & ltrim(std::string & str)
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   

std::string & rtrim(std::string & str)
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   

And once you've all these in place, you can write this as well:

std::string trim_copy(std::string const & str)
   auto s = str;
   return ltrim(rtrim(s));

Try this

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

jQuery/JavaScript: accessing contents of an iframe



instead of


How to scroll to an element?

You can also use scrollIntoView method to scroll to a given element.

handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
 if (some_logic){

 render() {
  return (
     <div ref="test"></div>

the MySQL service on local computer started and then stopped

Search for services.msc and look up through your services that are running if there is a mysql service running already other than the one you want to run (it could be xampp or wamp) or another service (for example Skype) using the same port as mysql and stop the service so you can run your mysql service.

Fastest method to replace all instances of a character in a string

Also you can try:


OSError: [Errno 8] Exec format error

OSError: [Errno 8] Exec format error can happen if there is no shebang line at the top of the shell script and you are trying to execute the script directly. Here's an example that reproduces the issue:

>>> with open('a','w') as f: f.write('exit 0') # create the script
>>> import os
>>> os.chmod('a', 0b111101101) # rwxr-xr-x make it executable                       
>>> os.execl('./a', './a')     # execute it                                            
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/", line 312, in execl
    execv(file, args)
OSError: [Errno 8] Exec format error

To fix it, just add the shebang e.g., if it is a shell script; prepend #!/bin/sh at the top of your script:

>>> with open('a','w') as f: f.write('#!/bin/sh\nexit 0')
>>> os.execl('./a', './a')

It executes exit 0 without any errors.

On POSIX systems, shell parses the command line i.e., your script won't see spaces around = e.g., if script is:

#!/usr/bin/env python
import sys

then running it in the shell:

$ /usr/local/bin/script hostname = '<hostname>' -p LONGLIST


['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no spaces around '='. I've added quotes around <hostname> to escape the redirection metacharacters <>.

To emulate the shell command in Python, run:

from subprocess import check_call

cmd = ['/usr/local/bin/script', 'hostname', '=', '<hostname>', '-p', 'LONGLIST']

Note: no shell=True. And you don't need to escape <> because no shell is run.

"Exec format error" might indicate that your script has invalid format, run:

$ file /usr/local/bin/script

to find out what it is. Compare the architecture with the output of:

$ uname -m

I can't install python-ldap

To correct the error due to dependencies to install the python-ldap : Windows 7/10

download the whl file

python 3.6 suit with


Deploy the file in :


install it with

python -m pip install python_ldap-3.2.0-cp36-cp36m-win_amd64.whl

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():


Android: Access child views from a ListView

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
        View v;
        int count = parent.getChildCount();
        v = parent.getChildAt(position);
        parent.requestChildFocus(v, view);
        for (int i = 0; i < count; i++) {
            if (i != position) {
                v = parent.getChildAt(i);

Basically, create two Drawables - one that is transparent, and another that is the desired color. Request focus at the clicked position (int position as defined) and change the color of the said row. Then walk through the parent ListView, and change all other rows accordingly. This accounts for when a user clicks on the listview multiple times. This is done with a custom layout for each row in the ListView. (Very simple, just create a new layout file with a TextView - do not set focusable or clickable!).

No custom adapter required - use ArrayAdapter

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);

It will move all .txt files on the desktop to the folder TextFiles.

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

How to change an input button image using CSS?

This article about CSS image replacement for submit buttons could help.

"Using this method you'll get a clickable image when style sheets are active, and a standard button when style sheets are off. The trick is to apply the image replace methods to a button tag and use it as the submit button, instead of using input.

And since button borders are erased, it's also recommendable change the button cursor to the hand shaped one used for links, since this provides a visual tip to the users."

The CSS code:

#replacement-1 {
  width: 100px;
  height: 55px;
  margin: 0;
  padding: 0;
  border: 0;
  background: transparent url(image.gif) no-repeat center top;
  text-indent: -1000em;
  cursor: pointer; /* hand-shaped cursor */
  cursor: hand; /* for IE 5.x */

#replacement-2 {
  width: 100px;
  height: 55px;
  padding: 55px 0 0;
  margin: 0;
  border: 0;
  background: transparent url(image.gif) no-repeat center top;
  overflow: hidden;
  cursor: pointer; /* hand-shaped cursor */
  cursor: hand; /* for IE 5.x */
form>#replacement-2 { /* For non-IE browsers*/
  height: 0px;

Which SchemaType in Mongoose is Best for Timestamp?

var ItemSchema = new Schema({
    name : { type: String }

ItemSchema.set('timestamps', true); // this will add createdAt and updatedAt timestamps


How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );

   $("#refresh-btn").on("click", RefreshTable);

   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


List<Object> and List<?>

To answer your second question, yes, you can cast the List<?> as a List<Object> or a List<T> of any type, since the ? (Wildcard) parameter indicates that the list contains a homogenous collection of an any Object. However, there's no way to know at compile what the type is since it's part of the exported API only - meaning you can't see what's being inserted into the List<?>.

Here's how you would make the cast:

List<?> wildcardList = methodThatReturnsWildcardList();
// generates Unchecked cast compiler warning
List<Object> objectReference = (List<Object>)wildcardList;

In this case you can ignore the warning because in order for an object to be used in a generic class it must be a subtype of Object. Let's pretend that we're trying to cast this as a List<Integer> when it actually contains a collection of Strings.

// this code will compile safely
List<?> wildcardList = methodThatReturnsWildcardList();
List<Integer> integerReference = (List<Integer>)wildcardList;

// this line will throw an invalid cast exception for any type other than Integer
Integer myInteger = integerRefence.get(0);

Remember: generic types are erased at runtime. You won't know what the collection contains, but you can get an element and call .getClass() on it to determine its type.

Class objectClass = wildcardList.get(0).getClass();

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")


With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions:

In [43]:



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

[8 rows x 4 columns]

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

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

In [47]:



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

[4 rows x 8 columns]

Bootstrap Alert Auto Close

This is a good approach to show animation in and out using jQuery

  $(document).ready(function() {
      // show the alert
      $(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {