Programs & Examples On #Powermock

Use this tag for questions about PowerMock, a Java library for creating mock objects for classes and methods. Questions about PowerMock's extension for Mockito should be tagged [powermockito] instead.

Mocking Logger and LoggerFactory with PowerMock and Mockito

Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.

Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...

I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.

When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...

Class under test

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClassWithSomeLogging  {

    private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);

    public void doStuff(boolean b) {
        if(b) {
            LOG.info("true");
        } else {
            LOG.info("false");
        }

    }
}

Test

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;


@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {

    private static Logger mockLOG;

    @BeforeClass
    public static void setup() {
        mockStatic(LoggerFactory.class);
        mockLOG = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
    }

    @Test
    public void testIt() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(true);

        verify(mockLOG, times(1)).info("true");
    }

    @Test
    public void testIt2() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(false);

        verify(mockLOG, times(1)).info("false");
    }

    @AfterClass
    public static void verifyStatic() {
        verify(mockLOG, times(1)).info("true");
        verify(mockLOG, times(1)).info("false");
        verify(mockLOG, times(2)).info(anyString());
    }
}

Note

If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true"); - rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....

Mock a constructor with parameter

With mockito you can use withSettings(), for example if the CounterService required 2 dependencies, you can pass them as a mock:

UserService userService = Mockito.mock(UserService.class); SearchService searchService = Mockito.mock(SearchService.class); CounterService counterService = Mockito.mock(CounterService.class, withSettings().useConstructor(userService, searchService));

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

How do I mock a static method that returns void with PowerMock?

To mock a static method that return void for e.g. Fileutils.forceMKdir(File file),

Sample code:

File file =PowerMockito.mock(File.class);
PowerMockito.doNothing().when(FileUtils.class,"forceMkdir",file);

How to mock private method for testing using PowerMock?

I don't see a problem here. With the following code using the Mockito API, I managed to do just that :

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

And here's the JUnit test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

        when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                .withArguments(anyString(), anyInt())
                .thenReturn(true);

        spy.meaningfulPublicApi();
    }
}

Proper way to get page content

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages 
the_ID();
the_title();

//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}

endwhile;

//if you want specific page of content then write in loop

  if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
    {
    echo get_the_ID();
    the_title();
    the_content();
    }

Python multiprocessing PicklingError: Can't pickle <type 'function'>

I have found that I can also generate exactly that error output on a perfectly working piece of code by attempting to use the profiler on it.

Note that this was on Windows (where the forking is a bit less elegant).

I was running:

python -m profile -o output.pstats <script> 

And found that removing the profiling removed the error and placing the profiling restored it. Was driving me batty too because I knew the code used to work. I was checking to see if something had updated pool.py... then had a sinking feeling and eliminated the profiling and that was it.

Posting here for the archives in case anybody else runs into it.

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

CSS3 100vh not constant in mobile browser

Because it won't be fixed, you can do something like:

# html
<body>
  <div class="content">
    <!-- Your stuff here -->
  </div>
</body>

# css
.content {
  height: 80vh;
}

For me it was the fastest and more pure solution than playing with the JavaScript which could not work on many devices and browsers.

Just use proper value of vh which fits your needs.

Java : Cannot format given Object as a Date

This worked for me:

String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

How does C compute sin() and other math functions?

OK kiddies, time for the pros.... This is one of my biggest complaints with inexperienced software engineers. They come in calculating transcendental functions from scratch (using Taylor's series) as if nobody had ever done these calculations before in their lives. Not true. This is a well defined problem and has been approached thousands of times by very clever software and hardware engineers and has a well defined solution. Basically, most of the transcendental functions use Chebyshev Polynomials to calculate them. As to which polynomials are used depends on the circumstances. First, the bible on this matter is a book called "Computer Approximations" by Hart and Cheney. In that book, you can decide if you have a hardware adder, multiplier, divider, etc, and decide which operations are fastest. e.g. If you had a really fast divider, the fastest way to calculate sine might be P1(x)/P2(x) where P1, P2 are Chebyshev polynomials. Without the fast divider, it might be just P(x), where P has much more terms than P1 or P2....so it'd be slower. So, first step is to determine your hardware and what it can do. Then you choose the appropriate combination of Chebyshev polynomials (is usually of the form cos(ax) = aP(x) for cosine for example, again where P is a Chebyshev polynomial). Then you decide what decimal precision you want. e.g. if you want 7 digits precision, you look that up in the appropriate table in the book I mentioned, and it will give you (for precision = 7.33) a number N = 4 and a polynomial number 3502. N is the order of the polynomial (so it's p4.x^4 + p3.x^3 + p2.x^2 + p1.x + p0), because N=4. Then you look up the actual value of the p4,p3,p2,p1,p0 values in the back of the book under 3502 (they'll be in floating point). Then you implement your algorithm in software in the form: (((p4.x + p3).x + p2).x + p1).x + p0 ....and this is how you'd calculate cosine to 7 decimal places on that hardware.

Note that most hardware implementations of transcendental operations in an FPU usually involve some microcode and operations like this (depends on the hardware). Chebyshev polynomials are used for most transcendentals but not all. e.g. Square root is faster to use a double iteration of Newton raphson method using a lookup table first. Again, that book "Computer Approximations" will tell you that.

If you plan on implmementing these functions, I'd recommend to anyone that they get a copy of that book. It really is the bible for these kinds of algorithms. Note that there are bunches of alternative means for calculating these values like cordics, etc, but these tend to be best for specific algorithms where you only need low precision. To guarantee the precision every time, the chebyshev polynomials are the way to go. Like I said, well defined problem. Has been solved for 50 years now.....and thats how it's done.

Now, that being said, there are techniques whereby the Chebyshev polynomials can be used to get a single precision result with a low degree polynomial (like the example for cosine above). Then, there are other techniques to interpolate between values to increase the accuracy without having to go to a much larger polynomial, such as "Gal's Accurate Tables Method". This latter technique is what the post referring to the ACM literature is referring to. But ultimately, the Chebyshev Polynomials are what are used to get 90% of the way there.

Enjoy.

General guidelines to avoid memory leaks in C++

C++ is designed RAII in mind. There is really no better way to manage memory in C++ I think. But be careful not to allocate very big chunks (like buffer objects) on local scope. It can cause stack overflows and, if there is a flaw in bounds checking while using that chunk, you can overwrite other variables or return addresses, which leads to all kinds security holes.

Subtracting two lists in Python

Python 2.7+ and 3.0 have collections.Counter (a.k.a. multiset). The documentation links to Recipe 576611: Counter class for Python 2.5:

from operator import itemgetter
from heapq import nlargest
from itertools import repeat, ifilter

class Counter(dict):
    '''Dict subclass for counting hashable objects.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> Counter('zyzygy')
    Counter({'y': 3, 'z': 2, 'g': 1})

    '''

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''        
        self.update(iterable, **kwds)

    def __missing__(self, key):
        return 0

    def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abracadabra').most_common(3)
        [('a', 5), ('r', 2), ('b', 2)]

        '''        
        if n is None:
            return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
        return nlargest(n, self.iteritems(), key=itemgetter(1))

    def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        If an element's count has been set to zero or is a negative number,
        elements() will ignore it.

        '''
        for elem, count in self.iteritems():
            for _ in repeat(None, count):
                yield elem

    # Override dict methods where the meaning changes for Counter objects.

    @classmethod
    def fromkeys(cls, iterable, v=None):
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwds):
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''        
        if iterable is not None:
            if hasattr(iterable, 'iteritems'):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    dict.update(self, iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def copy(self):
        'Like dict.copy() but returns a Counter instance instead of a dict.'
        return Counter(self)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            dict.__delitem__(self, elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})


        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] + other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] - other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _max = max
        result = Counter()
        for elem in set(self) | set(other):
            newcount = _max(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in ifilter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result


if __name__ == '__main__':
    import doctest
    print doctest.testmod()

Then you can write

 a = Counter([0,1,2,1,0])
 b = Counter([0, 1, 1])
 c = a - b
 print list(c.elements())  # [0, 2]

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

POSIX 7

First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

That contains a link to a time.h, which as a header should be where structs are defined:

The header shall declare the timespec structure, which shall > include at least the following members:

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

man 2 nanosleep

Pseudo-official glibc docs which you should always check for syscalls:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I don't know if anyone came to this issue while trying to test the outputted URL in browser but if you are using Postman and try to copy the generated url of AWS from the RAW tab, because of escaping backslashes you are going to get the above error.

Use the Pretty tab to copy and paste the url to see if it actually works.

I run into this issue recently and this solution solved my issue. It's for testing purposes to see if you actually retrieve the data through the url.

This answer is a reference to those who try to generate a download, temporary link from AWS or generally generate a URL from AWS to use.

Git Symlinks in Windows

One simple trick we use is to just call git add --all twice in a row.

For example, our Windows 7 commit script calls:

$ git add --all
$ git add --all

The first add treats the link as text and adds the folders for delete.

The second add traverses the link correctly and undoes the delete by restoring the files.

It's less elegant than some of the other proposed solutions but it is a simple fix to some of our legacy environments that got symlinks added.

QtCreator: No valid kits found

In my case, it goes well after I installed CMake in my system:)

sudo pacman -S cmake

for manjaro operating system.

Remove old Fragment from fragment manager

Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid

If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by

ArrayList<Fragment> fragmentList = fragmentManager.getFragments();

The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list

int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);

You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.

I usually use this code for working with fragmentManager

public void replaceFragment(Fragment fragment, Bundle bundle) {

    if (bundle != null)
        fragment.setArguments(bundle);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());

    //if oldFragment already exits in fragmentManager use it
    if (oldFragment != null) {
        fragment = oldFragment;
    }

    fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

    fragmentTransaction.commit();
}

Check if all checkboxes are selected

Part 1 of your question:

var allChecked = true;
$("input.abc").each(function(index, element){
  if(!element.checked){
    allChecked = false;
    return false;
  } 
});

EDIT:

The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.

How do I exit a while loop in Java?

Take a look at the Java™ Tutorials by Oracle.

But basically, as dacwe said, use break.

If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.

How do I drop table variables in SQL-Server? Should I even do this?

Temp table variable is saved to the temp.db and the scope is limited to the current execution. Hence, unlike dropping a Temp tables e.g drop table #tempTable, we don't have to explicitly drop Temp table variable @tempTableVariable. It is automatically taken care by the sql server.

drop table @tempTableVariable -- Invalid

Formatting floats without trailing zeros

You can achieve that in most pythonic way like that:

python3:

"{:0.0f}".format(num)

Android: How to detect double-tap?

As a lightweight alternative to GestureDetector you can use this class

public abstract class DoubleClickListener implements OnClickListener {

    private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

    long lastClickTime = 0;

    @Override
    public void onClick(View v) {
        long clickTime = System.currentTimeMillis();
        if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
            onDoubleClick(v);
        } else {
            onSingleClick(v);
        }
        lastClickTime = clickTime;
    }

    public abstract void onSingleClick(View v);
    public abstract void onDoubleClick(View v);
}

Example:

    view.setOnClickListener(new DoubleClickListener() {

        @Override
        public void onSingleClick(View v) {

        }

        @Override
        public void onDoubleClick(View v) {

        }
    });

Passing arguments to angularjs filters

From what I understand you can't pass an arguments to a filter function (when using the 'filter' filter). What you would have to do is to write a custom filter, sth like this:

.filter('weDontLike', function(){

return function(items, name){

    var arrayToReturn = [];        
    for (var i=0; i<items.length; i++){
        if (items[i].name != name) {
            arrayToReturn.push(items[i]);
        }
    }

    return arrayToReturn;
};

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/myr4a/1/

The other simple alternative, without writing custom filters is to store a name to filter out in a scope and then write:

$scope.weDontLike = function(item) {
  return item.name != $scope.name;
};

How do I paste multi-line bash codes into terminal and run it all at once?

In addition to backslash, if a line ends with | or && or ||, it will be continued on the next line.

CMAKE_MAKE_PROGRAM not found

Previous answers suggested (re)installing or configuring CMake, they all did not help.

Previously MinGW's compilation of Make used the filename mingw32-make.exe and now it is make.exe. Most suggested ways to configure CMake to use the other file dont work.

Just copy make.exe and rename the copy mingw32-make.exe.

Test if a vector contains a given element

Also to find the position of the element "which" can be used as

pop <- c(3,4,5,7,13)

which(pop==13)

and to find the elements which are not contained in the target vector, one may do this:

pop <- c(1,2,4,6,10)

Tset <- c(2,10,7)   # Target set

pop[which(!(pop%in%Tset))]

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

How to copy to clipboard using Access/VBA?

VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.

If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.

However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.

For example, to place some text on the clipboard, you could use the following code:

Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard

Or, to copy text from the clipboard into a string variable:

Dim clipboard As MSForms.DataObject
Dim strContents As String

Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText

Extracting jar to specified directory

This worked for me.

I created a folder then changed into the folder using CD option from command prompt.

Then executed the jar from there.

d:\LS\afterchange>jar xvf ..\mywar.war

How might I force a floating DIV to match the height of another floating DIV?

The correct solution for this problem is to use display: table-cell

Important: This solution doesn't need float since table-cell already turns the div into an element that lines up with the others in the same container. That also means you don't have to worry about clearing floats, overflow, background shining through and all the other nasty surprises that the float hack brings along to the party.

CSS:

.container {
  display: table;
}
.column {
  display: table-cell;
  width: 100px;
}

HTML:

<div class="container">
    <div class="column">Column 1.</div>
    <div class="column">Column 2 is a bit longer.</div>
    <div class="column">Column 3 is longer with lots of text in it.</div>
</div>

Related:

Delete branches in Bitbucket

If you are using a pycharm IDE for development and you already have added Git with it. you can directly delete remote branch from pycharm. From toolbar VCS-->Git-->Branches-->Select branch-->and Delete. It will delete it from remote git server.

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Make sure that you have put a log4j2.* file instead of a log4j.* file under .../src/main/resources folder.

How to get base URL in Web API controller?

I inject this service into my controllers.

 public class LinkFactory : ILinkFactory
 {
    private readonly HttpRequestMessage _requestMessage;
    private readonly string _virtualPathRoot;


    public LinkFactory(HttpRequestMessage requestMessage)
    {
        _requestMessage = requestMessage;
        var configuration = _requestMessage.Properties[HttpPropertyKeys.HttpConfigurationKey] as HttpConfiguration;
        _virtualPathRoot = configuration.VirtualPathRoot;
        if (!_virtualPathRoot.EndsWith("/"))
        {
            _virtualPathRoot += "/";
        }
    }

    public Uri ResolveApplicationUri(Uri relativeUri)
    {

        return new Uri(new Uri(new Uri(_requestMessage.RequestUri.GetLeftPart(UriPartial.Authority)), _virtualPathRoot), relativeUri);
    }

}

How do I reference a cell within excel named range?

"Do you know if there's a way to make this work with relative selections, so that the formula can be "dragged down"/applied across several cells in the same column?"

To make such selection relative simply use ROW formula for a row number in INDEX formula and COLUMN formula for column number in INDEX formula. To make this clearer here is the example:

=INDEX(named_range,ROW(A1),COLUMN(A1))

Assuming the named range starts at A1 this formula simply indexes that range by row and column number of referenced cell and since that reference is relative it changes when you drag the the cell down or to the side, which makes it possible to create whole array of cells easily.

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

How can I clear or empty a StringBuilder?

You should use sb.delete(0, sb.length()) or sb.setLength(0) and NOT create a new StringBuilder().

See this related post for performance: Is it better to reuse a StringBuilder in a loop?

How to get the id of the element clicked using jQuery

update as you loading contents dynamically so you use.

$(document).on('click', 'span', function () {
    alert(this.id);
});

old code

$('span').click(function(){
    alert(this.id);
});

or you can use .on

$('span').on('click', function () {
    alert(this.id);
});

this refers to current span element clicked

this.id will give the id of the current span clicked

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

There are possible solutions here: http://forums.mysql.com/read.php?35,64808,254785#msg-254785 and here: http://forums.mysql.com/read.php?35,23138,254786#msg-254786

All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.

Finally, more or less by accident, I bumped into the file:

...path_to_XAMPP\XAMPP...\mysql\bin\mysqld-debug.exe

Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.

Fastest way of finding differences between two files in unix?

This will work fast:

Case 1 - File2 = File1 + extra text appended.

grep -Fxvf File2.txt File1.txt >> File3.txt

File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines

Trying to get property of non-object MySQLi result

The cause of your problem is simple. So many people will run into the same problem, Because I did too and it took me hour to figure out. Just in case, someone else stumbles, The problem is in your query, your select statement is calling $dbname instead of table name. So its not found whereby returning false which is boolean. Good luck.

Why should I use var instead of a type?

When you say "by warnings" what exactly do you mean? I've usually seen it giving a hint that you may want to use var, but nothing as harsh as a warning.

There's no performance difference with var - the code is compiled to the same IL. The potential benefit is in readability - if you've already made the type of the variable crystal clear on the RHS of the assignment (e.g. via a cast or a constructor call), where's the benefit of also having it on the LHS? It's a personal preference though.

If you don't want R# suggesting the use of var, just change the options. One thing about ReSharper: it's very configurable :)

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

How to Refresh a Component in Angular

After some research and modifying my code as below, the script worked for me. I just added the condition:

this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
    this.router.navigate(['Your actualComponent']);
}); 

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Do copyright dates need to be updated?

Technically, you should update a copyright year only if you made contributions to the work during that year. So if your website hasn't been updated in a given year, there is no ground to touch the file just to update the year.

What is the difference between a static and const variable?

A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.

These two concepts are not mutually exclusive, and can be used together.

Easy way to make a confirmation dialog in Angular?

I'm pretty late to the party, but here is another implementation using : https://stackblitz.com/edit/angular-confirmation-dialog

confirmation-dialog.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ConfirmationDialogComponent } from './confirmation-dialog.component';

@Injectable()
export class ConfirmationDialogService {

  constructor(private modalService: NgbModal) { }

  public confirm(
    title: string,
    message: string,
    btnOkText: string = 'OK',
    btnCancelText: string = 'Cancel',
    dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
    const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.message = message;
    modalRef.componentInstance.btnOkText = btnOkText;
    modalRef.componentInstance.btnCancelText = btnCancelText;

    return modalRef.result;
  }

}

confirmation-dialog.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-confirmation-dialog',
  templateUrl: './confirmation-dialog.component.html',
  styleUrls: ['./confirmation-dialog.component.scss'],
})
export class ConfirmationDialogComponent implements OnInit {

  @Input() title: string;
  @Input() message: string;
  @Input() btnOkText: string;
  @Input() btnCancelText: string;

  constructor(private activeModal: NgbActiveModal) { }

  ngOnInit() {
  }

  public decline() {
    this.activeModal.close(false);
  }

  public accept() {
    this.activeModal.close(true);
  }

  public dismiss() {
    this.activeModal.dismiss();
  }

}

confirmation-dialog.component.html

<div class="modal-header">
  <h4 class="modal-title">{{ title }}</h4>
    <button type="button" class="close" aria-label="Close" (click)="dismiss()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    {{ message }}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-danger" (click)="decline()">{{ btnCancelText }}</button>
    <button type="button" class="btn btn-primary" (click)="accept()">{{ btnOkText }}</button>
  </div>

Use the dialog like this:

public openConfirmationDialog() {
    this.confirmationDialogService.confirm('Please confirm..', 'Do you really want to ... ?')
    .then((confirmed) => console.log('User confirmed:', confirmed))
    .catch(() => console.log('User dismissed the dialog (e.g., by using ESC, clicking the cross icon, or clicking outside the dialog)'));
  }

Mocking static methods with Mockito

As mentioned before you can not mock static methods with mockito.

If changing your testing framework is not an option you can do the following:

Create an interface for DriverManager, mock this interface, inject it via some kind of dependency injection and verify on that mock.

css transition opacity fade background

http://jsfiddle.net/6xJQq/13/

.container {
    display: inline-block;
    padding: 5px; /*included padding to see background when img apacity is 100%*/
    background-color: black;
    opacity: 1;
}

.container:hover {
    background-color: red;
}

img {
    opacity: 1;
}

img:hover {
    opacity: 0.7;
}

.transition {
    transition: all .25s ease-in-out;
    -moz-transition: all .25s ease-in-out;
    -webkit-transition: all .25s  ease-in-out;
}

How to programmatically click a button in WPF?

When using the MVVM Command pattern for Button function (recommended practice), a simple way to trigger the effect of the Button is as follows:

someButton.Command.Execute(someButton.CommandParameter);

This will use the Command object which the button triggers and pass the CommandParameter defined by the XAML.

How to disable HTML links

In Razor (.cshtml) you can do:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

How to add an onchange event to a select box via javascript?

Add

transport_select.setAttribute("onchange", function(){toggleSelect(transport_select_id);});

setAttribute

or try replacing onChange with onchange

How to serve .html files with Spring

Background of the problem

First thing to understand is following: it is NOT spring which renders the jsp files. It is JspServlet (org.apache.jasper.servlet.JspServlet) which does it. This servlet comes with Tomcat (jasper compiler) not with spring. This JspServlet is aware how to compile jsp page and how to return it as html text to the client. The JspServlet in tomcat by default only handles requests matching two patterns: *.jsp and *.jspx.

Now when spring renders the view with InternalResourceView (or JstlView), three things really takes place:

  1. get all the model parameters from model (returned by your controller handler method i.e. "public ModelAndView doSomething() { return new ModelAndView("home") }")
  2. expose these model parameters as request attributes (so that it can be read by JspServlet)
  3. forward request to JspServlet. RequestDispatcher knows that each *.jsp request should be forwarded to JspServlet (because this is default tomcat's configuration)

When you simply change the view name to home.html tomcat will not know how to handle the request. This is because there is no servlet handling *.html requests.

Solution

How to solve this. There are three most obvious solutions:

  1. expose the html as a resource file
  2. instruct the JspServlet to also handle *.html requests
  3. write your own servlet (or pass to another existing servlet requests to *.html).

For complete code examples how to achieve this please reffer to my answer in another post: How to map requests to HTML file in Spring MVC?

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

What about [AllowHtml] attribute above property?

Converting from byte to int in java

Bytes are transparently converted to ints.

Just say

int i= rno[0];

When is a language considered a scripting language?

All scripting languages are programming languages. So strictly speaking, there is no difference.

The term doesn't refer to any fundamental properties of the language, it refers to the typical use of the language. If the typical use is to write short programs that mainly do calls to pre-existing code, and some simple processing on the results, (that is, if the typical use is to write scripts) then it is a scripting language.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

For null or undefined value error, Just add this line to attributes : ,columnDefs: [ { "defaultContent": "-", "targets": "_all" } ]

Example :

_x000D_
_x000D_
oTable = $("#bigtable").dataTable({
  columnDefs: [{
    "defaultContent": "-",
    "targets": "_all"
  }]
});
_x000D_
_x000D_
_x000D_

The alert box will not show again, any empty values will be replaced with what you specified.

The best way to remove duplicate values from NSMutableArray in Objective-C?

Note that if you have a sorted array, you don't need to check against every other item in the array, just the last item. This should be much faster than checking against all items.

// sortedSourceArray is the source array, already sorted
NSMutableArray *newArray = [[NSMutableArray alloc] initWithObjects:[sortedSourceArray objectAtIndex:0]];
for (int i = 1; i < [sortedSourceArray count]; i++)
{
    if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])
    {
        [newArray addObject:[tempArray objectAtIndex:i]];
    }
}

It looks like the NSOrderedSet answers that are also suggested require a lot less code, but if you can't use an NSOrderedSet for some reason, and you have a sorted array, I believe my solution would be the fastest. I'm not sure how it compares with the speed of the NSOrderedSet solutions. Also note that my code is checking with isEqualToString:, so the same series of letters will not appear more than once in newArray. I'm not sure if the NSOrderedSet solutions will remove duplicates based on value or based on memory location.

My example assumes sortedSourceArray contains just NSStrings, just NSMutableStrings, or a mix of the two. If sortedSourceArray instead contains just NSNumbers or just NSDates, you can replace

if (![[sortedSourceArray objectAtIndex:i] isEqualToString:[sortedSourceArray objectAtIndex:(i-1)]])

with

if ([[sortedSourceArray objectAtIndex:i] compare:[sortedSourceArray objectAtIndex:(i-1)]] != NSOrderedSame)

and it should work perfectly. If sortedSourceArray contains a mix of NSStrings, NSNumbers, and/or NSDates, it will probably crash.

Curl to return http status code along with the response

I was able to get a solution by looking at the curl doc which specifies to use - for the output to get the output to stdout.

curl -o - http://localhost

To get the response with just the http return code, I could just do

curl -o /dev/null -s -w "%{http_code}\n" http://localhost

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

As a companion to the answers explaining cleanup and install via homebrew, I found that homebrew itself provided clear indications of the symlink clashes.

Unfortunately it provides these one by one as it encounters them, so it is a little laborious, but it does seem to find all the clashes and was the only way I could get a clean install with homebrew.

Essentially, the process is:

  1. use homebrew to uninstall node
  2. clean homebrew
  3. use homebrew to install node and note any flagged clashing file
  4. delete the flag clashing file (or whole directory if it is a 'node' directory)
  5. goto step 1 until you get a clean install

Diagrammatically:

Here is a screen output from the last steps of my install - you can see it results in a clean install (eventually...):

computer1:DevResources user1$ brew install node
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/node-13.1.0.mojave.bottle.tar.gz
Already downloaded: /Users/user1/Library/Caches/Homebrew/downloads/da904f1fdab6f6b2243a810b685e67b29a642c6e945f086e0022323a37fe85f9--node-13.1.0.mojave.bottle.tar.gz
==> Pouring node-13.1.0.mojave.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink share/systemtap/tapset/node.stp
Target /usr/local/share/systemtap/tapset/node.stp
already exists. You may want to remove it:
  rm '/usr/local/share/systemtap/tapset/node.stp'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

To list all files that would be deleted:
  brew link --overwrite --dry-run node

Possible conflicting files are:
/usr/local/share/systemtap/tapset/node.stp
/usr/local/lib/dtrace/node.d
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
  /usr/local/Cellar/node/13.1.0: 4,591 files, 54.2MB
computer1:DevResources user1$ rm '/usr/local/share/systemtap/tapset/node.stp'
computer1:DevResources user1$ brew uninstall node
Uninstalling /usr/local/Cellar/node/13.1.0... (4,591 files, 54.2MB)
computer1:DevResources user1$ brew cleanup
computer1:DevResources user1$ brew install node
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/node-13.1.0.mojave.bottle.tar.gz
Already downloaded: /Users/user1/Library/Caches/Homebrew/downloads/da904f1fdab6f6b2243a810b685e67b29a642c6e945f086e0022323a37fe85f9--node-13.1.0.mojave.bottle.tar.gz
==> Pouring node-13.1.0.mojave.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink lib/dtrace/node.d
Target /usr/local/lib/dtrace/node.d
already exists. You may want to remove it:
  rm '/usr/local/lib/dtrace/node.d'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

To list all files that would be deleted:
  brew link --overwrite --dry-run node

Possible conflicting files are:
/usr/local/lib/dtrace/node.d
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
  /usr/local/Cellar/node/13.1.0: 4,591 files, 54.2MB
computer1:DevResources user1$ rm '/usr/local/lib/dtrace/node.d'
computer1:DevResources user1$ 
computer1:DevResources user1$ brew uninstall node
Uninstalling /usr/local/Cellar/node/13.1.0... (4,591 files, 54.2MB)
computer1:DevResources user1$ brew cleanup
computer1:DevResources user1$ brew install node
Updating Homebrew...
==> Downloading https://homebrew.bintray.com/bottles/node-13.1.0.mojave.bottle.tar.gz
Already downloaded: /Users/user1/Library/Caches/Homebrew/downloads/da904f1fdab6f6b2243a810b685e67b29a642c6e945f086e0022323a37fe85f9--node-13.1.0.mojave.bottle.tar.gz
==> Pouring node-13.1.0.mojave.bottle.tar.gz
==> Caveats
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
==> Summary
  /usr/local/Cellar/node/13.1.0: 4,591 files, 54.2MB
computer1:DevResources user1$ node -v
v13.1.0

Where to find the complete definition of off_t type?

If you are writing portable code, the answer is "you can't tell", the good news is that you don't need to. Your protocol should involve writing the size as (eg) "8 octets, big-endian format" (Ideally with a check that the actual size fits in 8 octets.)

In Jinja2, how do you test if a variable is undefined?

From the Jinja2 template designer documentation:

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}

The OutputPath property is not set for this project

The error shown in visual studio for the project (Let's say A) does not have issues. When I looked at the output window for the build line by line for each project, I saw that it was complaining about another project (B) that had been referred as assembly in project A. Project B added into the solution. But it had not been referred in the project A as project reference instead as assembly reference from different location. That location contains the assembly which compiled for Platform AnyCpu. Then I removed the assembly reference from the project A and added project B as a reference. It started compiling. Not sure though how this fix worked.

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

Post order traversal of binary tree without recursion

Python with 1 stack and no flag:

def postorderTraversal(self, root):
    ret = []
    if not root:
        return ret
    stack = [root]
    current = None
    while stack:
        previous = current
        current = stack.pop()
        if previous and ((previous is current) or (previous is current.left) or (previous is current.right)):
            ret.append(current.val)
        else:
            stack.append(current)
            if current.right:
                stack.append(current.right)
            if current.left:
                stack.append(current.left)

    return ret

And what is better is with similar statements, in order traversal works too

def inorderTraversal(self, root):
    ret = []
    if not root:
        return ret
    stack = [root]
    current = None
    while stack:
        previous = current
        current = stack.pop()
        if None == previous or previous.left is current or previous.right is current:
            if current.right:
                stack.append(current.right)
            stack.append(current)
            if current.left:
                stack.append(current.left)
        else:
            ret.append(current.val)

    return ret

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

How to easily map c++ enums to strings

MSalters solution is a good one but basically re-implements boost::assign::map_list_of. If you have boost, you can use it directly:

#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>

using boost::assign::map_list_of;

enum eee { AA,BB,CC };

const boost::unordered_map<eee,const char*> eeeToString = map_list_of
    (AA, "AA")
    (BB, "BB")
    (CC, "CC");

int main()
{
    std::cout << " enum AA = " << eeeToString.at(AA) << std::endl;
    return 0;
}

What is the C# version of VB.net's InputDialog?

There is no such thing: I recommend to write it for yourself and use it whenever you need.

How can I merge the columns from two tables into one output?

Specifying the columns on your query should do the trick:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a, items_b b 
where a.category_id = b.category_id

should do the trick with regards to picking the columns you want.

To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:

select 
  coalesce(a.col1, b.col1) as col1, 
  coalesce(a.col2, b.col2) as col2,
  coalesce(a.col3, b.col3) as col3,
  a.category_id
from items_a a, items_b b
where a.category_id = b.category_id

The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.

An item with the same key has already been added

I had same issue. It appeard to me after migrating to MVC 5 from MVC 3.

I had custom editor template and had to use it like this before:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField", this.ViewData)

To resolve issue I had to remove passing ViewData object. So at the end I had:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField")

Hope it helps.

Checking if a collection is empty in Java: which is the best method?

Use CollectionUtils.isEmpty(Collection coll)

Null-safe check if the specified collection is empty. Null returns true.

Parameters: coll - the collection to check, may be null

Returns: true if empty or null

in angularjs how to access the element that triggered the event?

you can get easily like this first write event on element

ng-focus="myfunction(this)"

and in your js file like below

$scope.myfunction= function (msg, $event) {
    var el = event.target
    console.log(el);
}

I have used it as well.

How can I change the thickness of my <hr> tag

I would recommend setting the HR itself to be 0px high and use its border to be visible instead. I have noticed that when you zoom in and out (ctrl + mouse wheel) the thickness of HR itself changes, while when you set the border it always stays the same:

hr {
    height: 0px;
    border: none;
    border-top: 1px solid black;
}

How to send string from one activity to another?

Intents are intense.

Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.

find a minimum value in an array of floats

Python has a min() built-in function:

>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828

How to reset AUTO_INCREMENT in MySQL?

Try Run This Query

 ALTER TABLE tablename AUTO_INCREMENT = value;

Or Try This Query For The Reset Auto Increment

 ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;

And Set Auto Increment Then Run This Query

  ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

How to make an embedded video not autoplay

A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.

However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.

Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

Is there a way to programmatically minimize a window

<form>.WindowState = FormWindowState.Minimized;

Is there a decorator to simply cache function return values?

DISCLAIMER: I'm the author of kids.cache.

You should check kids.cache, it provides a @cache decorator that works on python 2 and python 3. No dependencies, ~100 lines of code. It's very straightforward to use, for instance, with your code in mind, you could use it like this:

pip install kids.cache

Then

from kids.cache import cache
...
class MyClass(object):
    ...
    @cache            # <-- That's all you need to do
    @property
    def name(self):
        return 1 + 1  # supposedly expensive calculation

Or you could put the @cache decorator after the @property (same result).

Using cache on a property is called lazy evaluation, kids.cache can do much more (it works on function with any arguments, properties, any type of methods, and even classes...). For advanced users, kids.cache supports cachetools which provides fancy cache stores to python 2 and python 3 (LRU, LFU, TTL, RR cache).

IMPORTANT NOTE: the default cache store of kids.cache is a standard dict, which is not recommended for long running program with ever different queries as it would lead to an ever growing caching store. For this usage you can plugin other cache stores using for instance (@cache(use=cachetools.LRUCache(maxsize=2)) to decorate your function/property/class/method...)

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

ScrollTo function in AngularJS

Here is a simple directive that will scroll to an element on click:

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm) {
      $elm.on('click', function() {
        $("body").animate({scrollTop: $elm.offset().top}, "slow");
      });
    }
  }
});

Demo: http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=preview

For help creating directives, check out the videos at http://egghead.io, starting at #10 "first directive".

edit: To make it scroll to a specific element specified by a href, just check attrs.href.

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function() {
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
      });
    }
  }
});

Then you could use it like this: <div scroll-on-click></div> to scroll to the element clicked. Or <a scroll-on-click href="#element-id"></div> to scroll to element with the id.

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

SQL: How to properly check if a record exists

I would prefer not use Count function at all:

IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
     <do smth>

For example if you want to check if user exists before inserting it into the database the query can look like this:

IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END

How to convert String into Hashmap in java

You can do it in single line, for any object type not just Map.

(Since I use Gson quite liberally, I am sharing a Gson based approach)

Gson gson = new Gson();    
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);

What it does is:

  1. gson.toJson(value) will serialize your object into its equivalent Json representation.
  2. gson.fromJson will convert the Json string to specified object. (in this example - Map)

There are 2 advantages with this approach:

  1. The flexibility to pass an Object instead of String to toJson method.
  2. You can use this single line to convert to any object even your own declared objects.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

How to sort a list of strings numerically?

You could pass a function to the key parameter to the .sort method. With this, the system will sort by key(x) instead of x.

list1.sort(key=int)

BTW, to convert the list to integers permanently, use the map function

list1 = list(map(int, list1))   # you don't need to call list() in Python 2.x

or list comprehension

list1 = [int(x) for x in list1]

How do you use a variable in a regular expression?

For multiple replace without regular expressions I went with the following:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs

The important part of the solution was found here

Difference between dates in JavaScript

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

_x000D_
_x000D_
function date_units_diff(a, b, unit_amounts) {_x000D_
    var split_to_whole_units = function (milliseconds, unit_amounts) {_x000D_
        // unit_amounts = list/array of amounts of milliseconds in a_x000D_
        // second, seconds in a minute, etc., for example "[1000, 60]"._x000D_
        time_data = [milliseconds];_x000D_
        for (i = 0; i < unit_amounts.length; i++) {_x000D_
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));_x000D_
            time_data[i] = time_data[i] % unit_amounts[i];_x000D_
        }; return time_data.reverse();_x000D_
    }; if (unit_amounts == undefined) {_x000D_
        unit_amounts = [1000, 60, 60, 24];_x000D_
    };_x000D_
    var utc_a = new Date(a.toUTCString());_x000D_
    var utc_b = new Date(b.toUTCString());_x000D_
    var diff = (utc_b - utc_a);_x000D_
    return split_to_whole_units(diff, unit_amounts);_x000D_
}_x000D_
_x000D_
// Example of use:_x000D_
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);_x000D_
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(_x000D_
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));
_x000D_
_x000D_
_x000D_

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

Is there a way to take a screenshot using Java and save it to some sort of image?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File; 
import javax.imageio.ImageIO;
import javax.swing.*;  

public class HelloWorldFrame extends JFrame implements ActionListener {

JButton b;
public HelloWorldFrame() {
    this.setVisible(true);
    this.setLayout(null);
    b = new JButton("Click Here");
    b.setBounds(380, 290, 120, 60);
    b.setBackground(Color.red);
    b.setVisible(true);
    b.addActionListener(this);
    add(b);
    setSize(1000, 700);
}
public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == b) 
    {
        this.dispose();
        try {
            Thread.sleep(1000);
            Toolkit tk = Toolkit.getDefaultToolkit(); 
            Dimension d = tk.getScreenSize();
            Rectangle rec = new Rectangle(0, 0, d.width, d.height);  
            Robot ro = new Robot();
            BufferedImage img = ro.createScreenCapture(rec);
            File f = new File("myimage.jpg");//set appropriate path
            ImageIO.write(img, "jpg", f);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

public static void main(String[] args) {
    HelloWorldFrame obj = new HelloWorldFrame();
}
}

Format Float to n decimal places

Take a look at DecimalFormat. You can easily use it to take a number and give it a set number of decimal places.

Edit: Example

Get month name from number

To print all months at once:

 import datetime

 monthint = list(range(1,13))

 for X in monthint:
     month = datetime.date(1900, X , 1).strftime('%B')
     print(month)

How to deep watch an array in angularjs?

$watchCollection accomplishes what you want to do. Below is an example copied from angularjs website http://docs.angularjs.org/api/ng/type/$rootScope.Scope While it's convenient, the performance needs to be taken into consideration especially when you watch a large collection.

  $scope.names = ['igor', 'matias', 'misko', 'james'];
  $scope.dataCount = 4;

  $scope.$watchCollection('names', function(newNames, oldNames) {
     $scope.dataCount = newNames.length;
  });

  expect($scope.dataCount).toEqual(4);
  $scope.$digest();

  //still at 4 ... no changes
  expect($scope.dataCount).toEqual(4);

  $scope.names.pop();
  $scope.$digest();

  //now there's been a change
  expect($scope.dataCount).toEqual(3);

Focus Next Element In Tab Index

It seems that you can check the tabIndex property of an element to determine if it is focusable. An element that is not focusable has a tabindex of "-1".

Then you just need to know the rules for tab stops:

  • tabIndex="1" has the highest priorty.
  • tabIndex="2" has the next highest priority.
  • tabIndex="3" is next, and so on.
  • tabIndex="0" (or tabbable by default) has the lowest priority.
  • tabIndex="-1" (or not tabbable by default) does not act as a tab stop.
  • For two elements that have the same tabIndex, the one that appears first in the DOM has the higher priority.

Here is an example of how to build the list of tab stops, in sequence, using pure Javascript:

function getTabStops(o, a, el) {
    // Check if this element is a tab stop
    if (el.tabIndex > 0) {
        if (o[el.tabIndex]) {
            o[el.tabIndex].push(el);
        } else {
            o[el.tabIndex] = [el];
        }
    } else if (el.tabIndex === 0) {
        // Tab index "0" comes last so we accumulate it seperately
        a.push(el);
    }
    // Check if children are tab stops
    for (var i = 0, l = el.children.length; i < l; i++) {
        getTabStops(o, a, el.children[i]);
    }
}

var o = [],
    a = [],
    stops = [],
    active = document.activeElement;

getTabStops(o, a, document.body);

// Use simple loops for maximum browser support
for (var i = 0, l = o.length; i < l; i++) {
    if (o[i]) {
        for (var j = 0, m = o[i].length; j < m; j++) {
            stops.push(o[i][j]);
        }
    }
}
for (var i = 0, l = a.length; i < l; i++) {
    stops.push(a[i]);
}

We first walk the DOM, collecting up all tab stops in sequence with their index. We then assemble the final list. Notice that we add the items with tabIndex="0" at the very end of the list, after the items with a tabIndex of 1, 2, 3, etc.

For a fully working example, where you can tab around using the "enter" key, check out this fiddle.

Changing Background Image with CSS3 Animations

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

_x000D_
_x000D_
#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; }
@keyframes changeBg{
   0%,100%  {background-image: url("https://i.stack.imgur.com/YdrqG.png");}
   25% {background-image: url("https://i.stack.imgur.com/2wKWi.png");}
   50% {background-image: url("https://i.stack.imgur.com/HobHO.png");}
   75% {background-image: url("https://i.stack.imgur.com/3hiHO.png");}
}
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_


Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

In my case, the problem was with PUT requests (GET and POST were passing successfully).

Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...

Problem was solved after exception was added to the firewall for my IP address.

import error: 'No module named' *does* exist

In case this is of interest to anyone, I had the same problem when I was running Python in Cygwin, in my case it was complaning that pandas wasn't installed even though it was. The problem was that I had 2 installations of python - one in windows and another one in cygwin (using the cygwin installer) and although both were the same versions of Python, the Cygwin installation was confused about where Pandas was installed. When i uninstalled cygwin's Python and pointed Cygwin at the windows installation everything was fine

Setting a max height on a table

I had a coworker ask how to do this today, and this is what I came up with. I don't love it but it is a way to do it without js and have headers respected. The main drawback however is you lose some semantics due to not having a true table header anymore.

Basically I wrap a table within a table, and use a div as the scroll container by giving it a max-height. Since I wrap the table in a parent table "colspanning" the fake header rows it appears as if the table respects them, but in reality the child table just has the same number of rows.

One small issue due to the scroll bar taking up space the child table column widths wont match up exactly.

Live Demo

Markup

<table class="table-container">
    <tbody>
        <tr>
            <td>header col 1</td>
            <td>header col 2</td>
        </tr>
        <tr>
            <td colspan="2">
                <div class="scroll-container">
                    <table>
                        <tr>
                            <td>entry1</td>
                            <td>entry1</td>
                        </tr>
                       ........ all your entries
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>

CSS

.table-container {
    border:1px solid #ccc;
    border-radius: 3px;
    width:50%;
}
.table-container table {
    width: 100%;
}
.scroll-container{
    max-height: 150px;
    overflow-y: scroll;
}

String, StringBuffer, and StringBuilder

Also, StringBuffer is thread-safe, which StringBuilder is not.

So in a real-time situation when different threads are accessing it, StringBuilder could have an undeterministic result.

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

It was definitely because missing dependencies that were not in my maven pom.xml.

For example, I wanted to create integration tests for my implementation of the broadleaf ecommerce demo site.

I had included a broadleaf jar with integration tests from broadleaf commerce in order to reuse their configuration files and base testing classes. That project had other testing dependencies that I had not included and I received the "inconsistent hierarchy" error.

After copying the "test dependencies" from broadleaf/pom.xml and the associated properties variables that provided the versions for each dependency in broadleaf/pom.xml, the error went away.

The properties were:

    <geb.version>0.9.3</geb.version>
    <spock.version>0.7-groovy-2.0</spock.version>
    <selenium.version>2.42.2</selenium.version>
    <groovy.version>2.1.8</groovy.version>

The dependencies were:

<dependency>
            <groupId>org.broadleafcommerce</groupId>
            <artifactId>integration</artifactId>
            <type>jar</type>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.broadleafcommerce</groupId>
            <artifactId>broadleaf-framework</artifactId>
            <version>${blc.version}</version><!--$NO-MVN-MAN-VER$ -->
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>com.icegreen</groupId>
            <artifactId>greenmail</artifactId>
            <version>1.3</version>
            <type>jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>2.5.1</version>
            <type>jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymockclassextension</artifactId>
            <version>2.4</version>
            <type>jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>5.9</version>
            <type>jar</type>
            <classifier>jdk15</classifier>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>${groovy.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.gebish</groupId>
            <artifactId>geb-core</artifactId>
            <version>${geb.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.gebish</groupId>
            <artifactId>geb-spock</artifactId>
            <version>${geb.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>${spock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-support</artifactId>
            <version>${selenium.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-firefox-driver</artifactId>
            <version>${selenium.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>${selenium.version}</version>
            <scope>test</scope>
        </dependency>
  <!-- Logging -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.12</version>
                <type>jar</type>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.6.1</version>
                <type>jar</type>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>1.6.1</version>
                <type>jar</type>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.6.1</version>
                <type>jar</type>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.hsqldb</groupId>
                <artifactId>hsqldb</artifactId>
                <version>2.3.1</version>
                <type>jar</type>
                <scope>test</scope>
            </dependency>

How to select the Date Picker In Selenium WebDriver

From Java 8 you can use this simple method for picking a random date from the date picker

List<WebElement> datePickerDays = driver.findElements(By.tagName("td"));
datePickerDays.stream().filter(e->e.getText().equals(whichDateYouWantToClick)).findFirst().get().click();

Calling Scalar-valued Functions in SQL

You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.

https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx

How to use @Nullable and @Nonnull annotations more effectively?

In Java I'd use Guava's Optional type. Being an actual type you get compiler guarantees about its use. It's easy to bypass it and obtain a NullPointerException, but at least the signature of the method clearly communicates what it expects as an argument or what it might return.

Implementing a Custom Error page on an ASP.Net website

Try this way, almost same.. but that's what I did, and working.

<configuration>
    <system.web>
       <customErrors mode="On" defaultRedirect="apperror.aspx">
          <error statusCode="404" redirect="404.aspx" />
          <error statusCode="500" redirect="500.aspx" />
       </customErrors>
    </system.web>
</configuration> 

or try to change the 404 error page from IIS settings, if required urgently.

A simple jQuery form validation script

You can simply use the jQuery Validate plugin as follows.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

DEMO: http://jsfiddle.net/xs5vrrso/

Options: http://jqueryvalidation.org/validate

Methods: http://jqueryvalidation.org/category/plugin/

Standard Rules: http://jqueryvalidation.org/category/methods/

Optional Rules available with the additional-methods.js file:

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

Why doesn't TFS get latest get the latest?

Sometimes Get specific version even checking both checkboxes won't get you the latest file. You've probably made a change to a file, and want to undo those changes by re-getting the latest version. Well... that's what Undo pending changes is for and not the purpose of Get specific version.

If in doubt:

  • undo pending check in on the file(s)
  • do a compare afterwards to make sure your file matches the expected version
  • run a recursive 'compare' on your whole project afterwards to see what else is different
  • keep an eye on pending changes window and sometimes you may need to check 'take server version' to resolve an incompatible pending change

And this one's my favorite that I just discovered :

  • keep an eye out in the the Output window for messages such as this :

    Warning - Unable to refresh R:\TFS-PROJECTS\www.example.com\ExampleMVC\Example MVC\Example MVC.csproj because you have a pending edit.

This critical message appears in the output window. No other notifications! Nothing in pending changes and no other dialog message telling you that the file you just requested explicitly was not retrieved! And yes - you resolve this by just running Undo pending changes and getting the file.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

How to use jQuery Plugin with Angular 4?

Try this:

import * as $ from 'jquery/dist/jquery.min.js';

Or add scripts to angular-cli.json:

"scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ]

and in your .ts file:

declare var $: any;

How to check whether a pandas DataFrame is empty?

I prefer going the long route. These are the checks I follow to avoid using a try-except clause -

  1. check if variable is not None
  2. then check if its a dataframe and
  3. make sure its not empty

Here, DATA is the suspect variable -

DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty

How to get Maven project version to the bash command line

This worked for me, offline and without depending on mvn:

VERSION=$(grep --max-count=1 '<version>' <your_path>/pom.xml | awk -F '>' '{ print $2 }' | awk -F '<' '{ print $1 }')
echo $VERSION

Define global constants

Updated for Angular 4+

Now we can simply use environments file which angular provide default if your project is generated via angular-cli.

for example

In your environments folder create following files

  • environment.prod.ts
  • environment.qa.ts
  • environment.dev.ts

and each file can hold related code changes such as:

  • environment.prod.ts

    export const environment = {
         production: true,
         apiHost: 'https://api.somedomain.com/prod/v1/',
         CONSUMER_KEY: 'someReallyStupidTextWhichWeHumansCantRead', 
         codes: [ 'AB', 'AC', 'XYZ' ],
    };
    
  • environment.qa.ts

    export const environment = {
         production: false,
         apiHost: 'https://api.somedomain.com/qa/v1/',
         CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead', 
         codes: [ 'AB', 'AC', 'XYZ' ],
    };
    
  • environment.dev.ts

    export const environment = {
         production: false,
         apiHost: 'https://api.somedomain.com/dev/v1/',
         CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead', 
         codes: [ 'AB', 'AC', 'XYZ' ],
    };
    

Use-case in application

You can import environments into any file such as services clientUtilServices.ts

import {environment} from '../../environments/environment';

getHostURL(): string {
    return environment.apiHost;
  }

Use-case in build

Open your angular cli file .angular-cli.json and inside "apps": [{...}] add following code

 "apps":[{
        "environments": {
            "dev": "environments/environment.ts",
            "prod": "environments/environment.prod.ts",
            "qa": "environments/environment.qa.ts",
           }
         }
       ]

If you want to build for production, run ng build --env=prod it will read configuration from environment.prod.ts , same way you can do it for qa or dev

## Older answer

I have been doing something like below, in my provider:

import {Injectable} from '@angular/core';

@Injectable()
export class ConstantService {

API_ENDPOINT :String;
CONSUMER_KEY : String;

constructor() {
    this.API_ENDPOINT = 'https://api.somedomain.com/v1/';
    this.CONSUMER_KEY = 'someReallyStupidTextWhichWeHumansCantRead'
  }
}

Then i have access to all Constant data at anywhere

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

import {ConstantService} from  './constant-service'; //This is my Constant Service


@Injectable()
export class ImagesService {
    constructor(public http: Http, public ConstantService: ConstantService) {
    console.log('Hello ImagesService Provider');

    }

callSomeService() {

    console.log("API_ENDPOINT: ",this.ConstantService.API_ENDPOINT);
    console.log("CONSUMER_KEY: ",this.ConstantService.CONSUMER_KEY);
    var url = this.ConstantService.API_ENDPOINT;
    return this.http.get(url)
  }
 }

Spring Boot REST API - request timeout?

You can configure the Async thread executor for your Springboot REST services. The setKeepAliveSeconds() should consider the execution time for the requests chain. Set the ThreadPoolExecutor's keep-alive seconds. Default is 60. This setting can be modified at runtime, for example through JMX.

@Bean(name="asyncExec")
public Executor asyncExecutor()
{
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(3);
    executor.setMaxPoolSize(3);
    executor.setQueueCapacity(10);
    executor.setThreadNamePrefix("AsynchThread-");
    executor.setAllowCoreThreadTimeOut(true);
    executor.setKeepAliveSeconds(10);
    executor.initialize();

    return executor;
}

Then you can define your REST endpoint as follows

@Async("asyncExec")
@PostMapping("/delayedService")
public CompletableFuture<String> doDelay()
{ 
    String response = service.callDelayedService();
    return CompletableFuture.completedFuture(response);
}

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Template not provided using create-react-app

One of the easiest way to do it is by using

npx --ignore-existing create-react-app [project name]

This will remove the old cached version of create-react-app and then get the new version to create the project.

Note: Adding the name of the project is important as just ignoring the existing create-react-app version is stale and the changes in your machines global env is temporary and hence later just using npx create-react-app [project name] will not provide the desired result.

How to enter command with password for git pull?

Using the credentials helper command-line option:

git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin

How to disable the ability to select in a DataGridView?

If you don't need to use the information in the selected cell then clearing selection works but if you need to still use the information in the selected cell you can do this to make it appear there is no selection and the back color will still be visible.

private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView.SelectedRows)
        {
            dataGridView.RowsDefaultCellStyle.SelectionBackColor = row.DefaultCellStyle.BackColor;
        }
    }

How to make a select with array contains value clause in psql

Note that this may also work:

SELECT * FROM table WHERE s=ANY(array)

How to view the list of compile errors in IntelliJ?

A more up to date answer for anyone else who comes across this:

(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)

Compile automatically:

To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option

Show all errors in one place:

The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.

Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.

While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

How to view data saved in android database(SQLite)?

1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

100% height minus header?

For "100% of the browser window", if you mean this literally, you should use fixed positioning. The top, bottom, right, and left properties are then used to offset the divs edges from the respective edges of the viewport:

#nav, #content{position:fixed;top:0px;bottom:0px;}
#nav{left:0px;right:235px;}
#content{left:235px;right:0px}

This will set up a screen with the left 235 pixels devoted to the nav, and the right rest of the screen to content.

Note, however, you won't be able to scroll the whole screen at once. Though you can set it to scroll either pane individually, by applying overflow:auto to either div.

Note also: fixed positioning is not supported in IE6 or earlier.

Creating and throwing new exception

To call a specific exception such as FileNotFoundException use this format

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

To throw a general exception use the throw command followed by a string.

throw "Error trying to do a task"

When used inside a catch, you can provide additional information about what triggered the error

Sorted array list in Java

You could subclass ArrayList, and call Collections.sort(this) after any element is added - you would need to override two versions of add, and two of addAll, to do this.

Performance would not be as good as a smarter implementation which inserted elements in the right place, but it would do the job. If addition to the list is rare, the cost amortised over all operations on the list should be low.

htaccess "order" Deny, Allow, Deny

In apache2, linux configuration

Require all granted

How to add parameters to an external data query in Excel which can't be displayed graphically?

Easy Workaround (no VBA required)

  1. Right Click Table, expand "Table" context manu, select "External Data Properties"
  2. Click button "Connection Properties" (labelled in tooltip only)
  3. Go-to Tab "Definition"

From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.

Parsing JSON from XmlHttpRequest.responseJSON

Use nsIJSON if this is for a FF extension:

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url) + BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};
req.send(null);

parseJSON: function(req, url) {
if (req.status == 200) {
  var jsonResponse = Components.classes["@mozilla.org/dom/json;1"]
      .createInstance(Components.interfaces.nsIJSON.decode(req.responseText);
  var bitlyUrl = jsonResponse.results[url].shortUrl;
}

For a webpage, just use JSON.parse instead of Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode

How can I get the name of an object in Python?

And the reason I want to have the name of the function is because I want to create fun_dict without writing the names of the functions twice, since that seems like a good way to create bugs.

For this purpose you have a wonderful getattr function, that allows you to get an object by known name. So you could do for example:

funcs.py:

def func1(): pass
def func2(): pass

main.py:

import funcs
option = command_line_option()
getattr(funcs, option)()

How to make a gui in python

If you're looking to build a GUI interface to trace an IP address, I would recommend VB.

But if you insist on sticking with Python, TkInter and wxPython are the best choices.

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

Favorite Visual Studio keyboard shortcuts

One that other editors should take up: Ctrl+C with nothing selected will copy the current line.

Most other editors will do nothing. After copying a line, pasting will place the line before the current one, even if you're in the middle of the line. Most other editors will start pasting from where you are, which is almost never what you want.

Duplicating a line is just: Hold Ctrl, press c, then v. (Ctrl+C, Ctrl+V)

Select the first 10 rows - Laravel Eloquent

Another way to do it is using a limit method:

Listing::limit(10)->get();

This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:

Listing::inRandomOrder()->limit(10)->get();

How to convert XML to java.util.Map and vice versa

I have written a piece of code that transforms a XML content into a multi-layer structure of maps:

public static Object convertNodesFromXml(String xml) throws Exception {

    InputStream is = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(is);
    return createMap(document.getDocumentElement());
}

public static Object createMap(Node node) {
    Map<String, Object> map = new HashMap<String, Object>();
    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        String name = currentNode.getNodeName();
        Object value = null;
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            value = createMap(currentNode);
        }
        else if (currentNode.getNodeType() == Node.TEXT_NODE) {
            return currentNode.getTextContent();
        }
        if (map.containsKey(name)) {
            Object os = map.get(name);
            if (os instanceof List) {
                ((List<Object>)os).add(value);
            }
            else {
                List<Object> objs = new LinkedList<Object>();
                objs.add(os);
                objs.add(value);
                map.put(name, objs);
            }
        }
        else {
            map.put(name, value);
        }
    }
    return map;
}

This code transforms this:

<house>
    <door>blue</door>
    <living-room>
        <table>wood</table>
        <chair>wood</chair>
    </living-room>
</house>

into

{
    "house": {
        "door": "blue",
        "living-room": {
            "table": "wood",
            "chair": "wood"
        }
     }
 }

I don't have the inverse process, but that must not be very difficult to write.

Indenting code in Sublime text 2?

Select everything, or whatever you want to re-indent and do Alt+ E+L+R. This is really quick and painless.

Whitespaces in java

From sun docs:

\s A whitespace character: [ \t\n\x0B\f\r]

The simplest way is to use it with regex.

What is the purpose of a self executing function in javascript?

Short answer is : to prevent pollution of the Global (or higher) scope.

IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.

This is the other way to write IIFE expression. I personally prefer this following method:

void function() {
  console.log('boo!');
  // expected output: "boo!"
}();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.

Why should C++ programmers minimize use of 'new'?

Because the stack is faster and leak-proof

In C++, it takes but a single instruction to allocate space -- on the stack -- for every local scope object in a given function, and it's impossible to leak any of that memory. That comment intended (or should have intended) to say something like "use the stack and not the heap".

Set a div width, align div center and text align left

Try:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

Multiprocessing vs Threading Python

Process may have multiple threads. These threads may share memory and are the units of execution within a process.

Processes run on the CPU, so threads are residing under each process. Processes are individual entities which run independently. If you want to share data or state between each process, you may use a memory-storage tool such as Cache(redis, memcache), Files, or a Database.

Reading CSV files using C#

private static DataTable ConvertCSVtoDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }

            return dt;
        }

        private static void WriteToDb(DataTable dt)
        {
            string connectionString =
                "Data Source=localhost;" +
                "Initial Catalog=Northwind;" +
                "Integrated Security=SSPI;";

            using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("spInsertTest", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@policyID", SqlDbType.Int).Value = 12;
                        cmd.Parameters.Add("@statecode", SqlDbType.VarChar).Value = "blagh2";
                        cmd.Parameters.Add("@county", SqlDbType.VarChar).Value = "blagh3";

                        con.Open();
                        cmd.ExecuteNonQuery();
                    }
                }

         }

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How to create a delay in Swift?

Comparison between different approaches in swift 3.0

1. Sleep

This method does not have a call back. Put codes directly after this line to be executed in 4 seconds. It will stop user from iterating with UI elements like the test button until the time is gone. Although the button is kind of frozen when sleep kicks in, other elements like activity indicator is still spinning without freezing. You cannot trigger this action again during the sleep.

sleep(4)
print("done")//Do stuff here

enter image description here

2. Dispatch, Perform and Timer

These three methods work similarly, they are all running on the background thread with call backs, just with different syntax and slightly different features.

Dispatch is commonly used to run something on the background thread. It has the callback as part of the function call

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
    print("done")
})

Perform is actually a simplified timer. It sets up a timer with the delay, and then trigger the function by selector.

perform(#selector(callback), with: nil, afterDelay: 4.0)

func callback() {
    print("done")
}}

And finally, timer also provides ability to repeat the callback, which is not useful in this case

Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(callback), userInfo: nil, repeats: false)


func callback() {
    print("done")
}}

For all these three method, when you click on the button to trigger them, UI will not freeze and you are allowed to click on it again. If you click on the button again, another timer is set up and the callback will be triggered twice.

enter image description here

In conclusion

None of the four method works good enough just by themselves. sleep will disable user interaction, so the screen "freezes"(not actually) and results bad user experience. The other three methods will not freeze the screen, but you can trigger them multiple times, and most of the times, you want to wait until you get the call back before allowing user to make the call again.

So a better design will be using one of the three async methods with screen blocking. When user click on the button, cover the entire screen with some translucent view with a spinning activity indicator on top, telling user that the button click is being handled. Then remove the view and indicator in the call back function, telling user that the the action is properly handled, etc.

How to filter rows in pandas by regex

Write a Boolean function that checks the regex and use apply on the column

foo[foo['b'].apply(regex_function)]

How to import JSON File into a TypeScript file?

As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:

  1. Add those three lines to compilerOptions in your tsconfig.json file:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
  1. Import your json data:
import myData from '../assets/data/my-data.json';

And that's it. You can now use myDatain your components/services.

How to Code Double Quotes via HTML Codes

Google recommend that you don't use any of them, source.

There is no need to use entity references like &mdash, &rdquo, or &#x263a, assuming the same encoding (UTF-8) is used for files and editors as well as among teams.

Is there a reason you can't simply use "?

UICollectionView cell selection and cell reuse

The problem you encounter comes from the lack of call to super.prepareForReuse().

Some other solutions above, suggesting to update the UI of the cell from the delegate's functions, are leading to a flawed design where the logic of the cell's behaviour is outside of its class. Furthermore, it's extra code that can be simply fixed by calling super.prepareForReuse(). For example :

class myCell: UICollectionViewCell {

    // defined in interface builder
    @IBOutlet weak var viewSelection : UIView!

    override var isSelected: Bool {
        didSet {
            self.viewSelection.alpha = isSelected ? 1 : 0
        }
    }

    override func prepareForReuse() {
        // Do whatever you want here, but don't forget this :
        super.prepareForReuse()
        // You don't need to do `self.viewSelection.alpha = 0` here 
        // because `super.prepareForReuse()` will update the property `isSelected`

    }


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.viewSelection.alpha = 0
    }

}

With such design, you can even leave the delegate's functions collectionView:didSelectItemAt:/collectionView:didDeselectItemAt: all empty, and the selection process will be totally handled, and behave properly with the cells recycling.

Razor/CSHTML - Any Benefit over what we have?

Ex Microsoft Developer's Opinion

I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.

Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.

One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

I had this error happen when I had 2 scripts I was running. I had:

  • A SQL*Plus session connected directly using a schema user account (account #1)
  • Another SQL*Plus session connected using a different schema user account (account #2), but connecting across a database link as the first account

I ran a table drop, then table creation as account #1. I ran a table update on account #2's session. Did not commit changes. Re-ran table drop/creation script as account #1. Got error on the drop table x command.

I solved it by running COMMIT; in the SQL*Plus session of account #2.

Convert JSON array to Python list

Tested on Ideone.


import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data  = json.loads(array)
fruits_list = data['fruits']
print fruits_list

How to increase application heap size in Eclipse?

In the run configuration you want to customize (just click on it) open the tab Arguments and add -Xmx2048min the VM arguments section. You might want to set the -Xms as well (small heap size).

what is the size of an enum type data in C++?

An enum is kind of like a typedef for the int type (kind of).

So the type you've defined there has 12 possible values, however a single variable only ever has one of those values.

Think of it this way, when you define an enum you're basically defining another way to assign an int value.

In the example you've provided, january is another way of saying 0, feb is another way of saying 1, etc until december is another way of saying 11.

How to restrict UITextField to take only numbers in Swift?

Here is a simple solution, you need to connect the event "Editing changed" to this method in your controller

Swift 4

@IBAction func valueChanged(_ sender: UITextField) {
    if let last = sender.text?.last {
        let zero: Character = "0"
        let num: Int = Int(UnicodeScalar(String(last))!.value - UnicodeScalar(String(zero))!.value)
        if (num < 0 || num > 9) {
            //remove the last character as it is invalid
            sender.text?.removeLast()
        }
    }
}

Label on the left side instead above an input field

<div class="control-group">
   <label class="control-label" for="firstname">First Name</label>
   <div class="controls">
    <input type="text" id="firstname" name="firstname"/>
   </div>
</div>

Also we can use it Simply as

<label>First name:
    <input type="text" id="firstname" name="firstname"/>
</label>

Single huge .css file vs. multiple smaller specific .css files?

I'm using Jammit to deal with my css files and use many different files for readability. Jammit doest all the dirty work of combining and compressing the files before deployment in production. This way, I've got many files in development but only one file in production.

"The import org.springframework cannot be resolved."

Add these dependencies

</dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
</dependencies>

How to pad a string with leading zeros in Python 3

There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:

print(f"{1:03}")

Adding IN clause List to a JPA Query

The proper JPA query format would be:

el.name IN :inclList

If you're using an older version of Hibernate as your provider you have to write:

el.name IN (:inclList)

but that is a bug (HHH-5126) (EDIT: which has been resolved by now).

How to analyze disk usage of a Docker container

I use docker stats $(docker ps --format={{.Names}}) --no-stream to get :

  1. CPU usage,
  2. Mem usage/Total mem allocated to container (can be allocate with docker run command)
  3. Mem %
  4. Block I/O
  5. Net I/O

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

Get first date of current month in java

You can use withDayOfMonth(int dayOfMonth) method from java8 to return first day of month:

LocalDate firstDay = LocalDate.now().withDayOfMonth(1);
System.out.println(firstDay);   // 2019-09-01

Problems with Android Fragment back stack

executePendingTransactions() , commitNow() not worked (

Worked in androidx (jetpack).

private final FragmentManager fragmentManager = getSupportFragmentManager();

public void removeFragment(FragmentTag tag) {
    Fragment fragmentRemove = fragmentManager.findFragmentByTag(tag.toString());
    if (fragmentRemove != null) {
        fragmentManager.beginTransaction()
                .remove(fragmentRemove)
                .commit();

        // fix by @Ogbe
        fragmentManager.popBackStackImmediate(tag.toString(), 
            FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
}

UL list style not applying

Turns out that YUI's reset CSS strips the list style from 'ul li' instead of just 'ul', which is why setting it just in 'ul' never worked.

Creating a very simple linked list

The selected answer doesn't have an iterator; it is more basic, but perhaps not as useful.

Here is one with an iterator/enumerator. My implementation is based on Sedgewick's bag; see http://algs4.cs.princeton.edu/13stacks/Bag.java.html

void Main()
{
    var b = new Bag<string>();
    b.Add("bike");
    b.Add("erasmus");
    b.Add("kumquat");
    b.Add("beaver");
    b.Add("racecar");
    b.Add("barnacle");

    foreach (var thing in b)
    {
        Console.WriteLine(thing);
    }
}

// Define other methods and classes here

public class Bag<T> : IEnumerable<T>
{
    public Node<T> first;// first node in list

    public class Node<T>
    {
        public T item;
        public Node<T> next;

        public Node(T item)
        {
            this.item = item;
        }
    }


    public void Add(T item)
    {
        Node<T> oldFirst = first;
        first = new Node<T>(item);
        first.next = oldFirst;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new BagEnumerator<T>(this);
    }

    public class BagEnumerator<V> : IEnumerator<T>
    {
        private Node<T> _head;
        private Bag<T> _bag;
        private Node<T> _curNode;


        public BagEnumerator(Bag<T> bag)
        {

            _bag = bag;
            _head = bag.first;
            _curNode = default(Node<T>);

        }

        public T Current
        {
            get { return _curNode.item; }
        }


        object IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            if (_curNode == null)
            {
                _curNode = _head;
                if (_curNode == null)
                return false;
                return true;
            }
            if (_curNode.next == null)
            return false;
            else
            {
                _curNode = _curNode.next;
                return true;
            }

        }

        public void Reset()
        {
            _curNode = default(Node<T>); ;
        }


        public void Dispose()
        {
        }
    }
}

Force a screen update in Excel VBA

This is not directly answering your question at all, but simply providing an alternative. I've found in the many long Excel calculations most of the time waiting is having Excel update values on the screen. If this is the case, you could insert the following code at the front of your sub:

Application.ScreenUpdating = False
Application.EnableEvents = False

and put this as the end

Application.ScreenUpdating = True
Application.EnableEvents = True

I've found that this often speeds up whatever code I'm working with so much that having to alert the user to the progress is unnecessary. It's just an idea for you to try, and its effectiveness is pretty dependent on your sheet and calculations.

How do I get interactive plots again in Spyder/IPython/matplotlib?

As said in the comments, the problem lies in your script. Actually, there are 2 problems:

  • There is a matplotlib error, I guess that you're passing an argument as None somewhere. Maybe due to the defaultdict ?
  • You call show() after each subplot. show() should be called once at the end of your script. The alternative is to use interactive mode, look for ion in matplotlib's documentation.

How do you access the value of an SQL count () query in a Java program

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

git: patch does not apply

Try using the solution suggested here: https://www.drupal.org/node/1129120

patch -p1 < example.patch

This helped me .

Make Bootstrap 3 Tabs Responsive

I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive:

<div class="nav-tabs-responsive">
  <ul class="nav nav-tabs" role="tablist">
    <li>...</li>
  </ul>
</div>

And two css lines:

.nav-tabs { min-width: 600px; }
.nav-tabs-responsive { overflow: auto; }

600px is the point over you will be responsive (you can set it using bootstrap variables)

How do I check if an element is really visible with JavaScript?

Interesting question.

This would be my approach.

  1. At first check that element.style.visibility !== 'hidden' && element.style.display !== 'none'
  2. Then test with document.elementFromPoint(element.offsetLeft, element.offsetTop) if the returned element is the element I expect, this is tricky to detect if an element is overlapping another completely.
  3. Finally test if offsetTop and offsetLeft are located in the viewport taking scroll offsets into account.

Hope it helps.

How to print colored text to the terminal?

To address this problem I created a mind-numbingly simple package to print strings with interpolated color codes, called icolor.

icolor includes two functions: cformat and cprint, each of which takes a string with substrings that are interpolated to map to ANSI escape sequences e.g.

from icolor import cformat # there is also cprint

cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'

All the ANSI colors are included (e.g. #RED;, #BLUE;, etc.), as well as #RESET;, #BOLD; and others.

Background colors have an x prefix, so a green background would be #xGREEN;.

One can escape # with ##.

Given its simplicity, the best documentation is probably the code itself.

It is on PYPI, so one can sudo easy_install icolor.

JavaScript: changing the value of onclick with or without jQuery

One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.

So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.

The click event in JQuery is the click function $("myelt").click (function ....).

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

How to host google web fonts on my own server?

Please keep in mind that my answer has aged a lot.

There are other more technically sophisticated answers below, e.g.:

so don't let the fact that this is the currently accepted answer give you the impression that this is still the best one.


You can also now also download google's entire font set via on github at their google/font repository. They also provide a ~420MB zip snapshot of their fonts.


You first download your font selection as a zipped package, providing you with a bunch of true type fonts. Copy them somewhere public, somewhere you can link to from your css.

On the google webfont download page, you'll find a include link like so:

http://fonts.googleapis.com/css?family=Cantarell:400,700,400italic,700italic|Candal

It links to a CSS defining the fonts via a bunch of @font-face defintions.

Open it in a browser to copy and paste them into your own CSS and modify the urls to include the right font file and format types.

So this:

    @font-face {
      font-family: 'Cantarell';
      font-style: normal;
      font-weight: 700;
      src: local('Cantarell Bold'), local('Cantarell-Bold'), url(http://themes.googleusercontent.com/static/fonts/cantarell/v3/Yir4ZDsCn4g1kWopdg-ehHhCUOGz7vYGh680lGh-uXM.woff) format('woff');
    }

becomes this:

    /* Your local CSS File */
    @font-face {
        font-family: 'Cantarell';
        font-style: normal;
        font-weight: 700;
        src: local('Cantarell Bold'), local('Cantarell-Bold'), url(../font/Cantarell-Bold.ttf) format('truetype');
    }

As you can see, a downside of hosting the fonts on your own system this way is, that you restrict yourself to the true type format, whilst the google webfont service determines by the accessing device which formats will be transmitted.

Furthermore, I had to add a .htaccess file to my the directory holding the fonts containing mime types to avoid errors from popping up in Chrome Dev Tools.

For this solution, only true type is needed, but defining more does not hurt when you want to include different fonts as well, like font-awesome.

#.htaccess
AddType application/vnd.ms-fontobject .eot
AddType font/ttf .ttf
AddType font/otf .otf
AddType application/x-font-woff .woff

Remove trailing spaces automatically or with a shortcut

Visual Studio Code, menu FilePreferenceSettings → search for "trim":

Visual Studio Code screenshot

How to Update/Drop a Hive Partition?

You may also need to make database containing table active

use [dbname]

otherwise you may get error (even if you specify database i.e. dbname.table )

FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.

Setting up PostgreSQL ODBC on Windows

Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards

How to add SHA-1 to android application

Try pasting this code in CMD:

keytool -list -v -alias androiddebugkey -keystore  %USERPROFILE%\.android\debug.keystore

How do I select an element that has a certain class?

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

How to set Spring profile from system variable?

You can set the spring profile by supplying -Dspring.profiles.active=<env>

For java files in source(src) directory, you can use by System.getProperty("spring.profiles.active")

For java files in test directory you can supply

  • SPRING_PROFILES_ACTIVE to <env>

OR

Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle add a task to set jvm property and environment variable.

test {
    def profile = System.properties["spring.profiles.active"]
    systemProperty "spring.profiles.active",profile
    environment "SPRING.PROFILES_ACTIVE", profile
    println "Running ${project} tests with profile: ${profile}"
}

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

Is there a command to undo git init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

It might be a conflict with the same port specified in docker-compose.yml and docker-compose.override.yml or the same port specified explicitly and using an environment variable.

I had a docker-compose.yml with ports on a container specified using environment variables, and a docker-compose.override.yml with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a listed neither because the container could not start and list the ports.

Passing structs to functions

First, the signature of your data() function:

bool data(struct *sampleData)

cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:

bool data(struct sampleData *samples)

But in C++, you don't need to use struct at all actually. So this can simply become:

bool data(sampleData *samples)

Second, the sampleData struct is not known to data() at that point. So you should declare it before that:

struct sampleData {
    int N;
    int M;
    string sample_name;
    string speaker;
};

bool data(sampleData *samples)
{
    samples->N = 10;
    samples->M = 20;
    // etc.
}

And finally, you need to create a variable of type sampleData. For example, in your main() function:

int main(int argc, char *argv[]) {
    sampleData samples;
    data(&samples);
}

Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.

However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:

// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
    samples.N = 10;
    samples.M = 20;
    // etc.
}

int main(int argc, char *argv[]) {
    sampleData samples;

    // No need to pass a pointer here, since data() takes the
    // passed argument by reference.
    data(samples);
}

What's the difference between an Angular component and module

Angular Component

A component is one of the basic building blocks of an Angular app. An app can have more than one component. In a normal app, a component contains an HTML view page class file, a class file that controls the behaviour of the HTML page and the CSS/scss file to style your HTML view. A component can be created using @Component decorator that is part of @angular/core module.

import { Component } from '@angular/core';

and to create a component

@Component({selector: 'greet', template: 'Hello {{name}}!'})
class Greet {
  name: string = 'World';
}

To create a component or angular app here is the tutorial

Angular Module

An angular module is set of angular basic building blocks like component, directives, services etc. An app can have more than one module.

A module can be created using @NgModule decorator.

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Delete directories recursively in Java

rm -rf was much more performant than FileUtils.deleteDirectory.

After extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.deleteDirectory.

Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.deleteDirectory and only 1 minute with rm -rf.

Here's our rough Java implementation to do that:

// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean deleteDirectory( File file ) throws IOException, InterruptedException {

    if ( file.exists() ) {

        String deleteCommand = "rm -rf " + file.getAbsolutePath();
        Runtime runtime = Runtime.getRuntime();

        Process process = runtime.exec( deleteCommand );
        process.waitFor();

        return true;
    }

    return false;

}

Worth trying if you're dealing with large or complex directories.

Best timing method in C?

High resolution is relative... I was looking at the examples and they mostly cater for milliseconds. However for me it is important to measure microseconds. I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull. I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.

    #ifdef WIN32
      #ifndef PERFTIME
        #include <windows.h>
        #include <winbase.h>
        #define PERFTIME_INIT unsigned __int64 freq;  QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq);  unsigned __int64 startTime;  unsigned __int64 endTime;  double timeDifferenceInMilliseconds;
        #define PERFTIME_START QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
        #define PERFTIME_END QueryPerformanceCounter((LARGE_INTEGER *)&endTime); timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);  printf("Timing %fms\n",timeDifferenceInMilliseconds);
    #define PERFTIME(funct) {unsigned __int64 freq;  QueryPerformanceFrequency((LARGE_INTEGER*)&freq);  double timerFrequency = (1.0/freq);  unsigned __int64 startTime;  QueryPerformanceCounter((LARGE_INTEGER *)&startTime);  unsigned __int64 endTime;  funct; QueryPerformanceCounter((LARGE_INTEGER *)&endTime);  double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);  printf("Timing %fms\n",timeDifferenceInMilliseconds);}
      #endif
    #else
      //AIX/Linux gettimeofday() implementation here
    #endif

Usage:

PERFTIME(ProcessIntenseFunction());

or

PERFTIME_INIT
PERFTIME_START
ProcessIntenseFunction()
PERFTIME_END

What is difference between sleep() method and yield() method of multi threading?

Yield(): method will stop the currently executing thread and give a chance to another thread of same priority which are waiting in queue. If thier is no thread then current thread will continue to execute. CPU will never be in ideal state.

Sleep(): method will stop the thread for particular time (time will be given in milisecond). If this is single thread which is running then CPU will be in ideal state at that period of time.

Both are static menthod.

Value cannot be null. Parameter name: source

Take a Row in the database and make all the column null in that row like this "NULL".Now pass that NULL value using try catch or if else.

Java function for arrays like PHP's join()?

I do it this way using a StringBuilder:

public static String join(String[] source, String delimiter) {
    if ((null == source) || (source.length < 1)) {
        return "";
    }

    StringBuilder stringbuilder = new StringBuilder();
    for (String s : source) {
        stringbuilder.append(s + delimiter);
    }
    return stringbuilder.toString();
} // join((String[], String)

How can I set / change DNS using the command-prompt at windows 8

Batch file for setting a new dns server

@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

Your code can simplified a lot to

$('img', resp).attr('src', function(idx, urlRelative ) {
    return self.config.proxy_server + self.config.location_images + urlRelative;
});

Which is better: <script type="text/javascript">...</script> or <script>...</script>

You need to use <script type="text/javascript"> </script> unless you're using html5. In that case you are encouraged to prefer <script> ... </script> (because type attribute is specified by default to that value)

How to access random item in list?

ArrayList ar = new ArrayList();
        ar.Add(1);
        ar.Add(5);
        ar.Add(25);
        ar.Add(37);
        ar.Add(6);
        ar.Add(11);
        ar.Add(35);
        Random r = new Random();
        int index = r.Next(0,ar.Count-1);
        MessageBox.Show(ar[index].ToString());

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

How can I echo a newline in a batch file?

If anybody comes here because they are looking to echo a blank line from a MINGW make makefile, I used

@cmd /c echo.

simply using echo. causes the dreaded process_begin: CreateProcess(NULL, echo., ...) failed. error message.

I hope this helps at least one other person out there :)

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

How to erase the file contents of text file in Python?

From user @jamylak an alternative form of open("filename","w").close() is

with open('filename.txt','w'): pass