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....
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));
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.
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);
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();
}
}
$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();
}
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.
Just in case for data.table
users, the following works for me:
df[, grep("ABC", names(df)), with = FALSE]
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.
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);
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"...
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.
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.
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]
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 */
};
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.
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.
In my case, it goes well after I installed CMake in my system:)
sudo pacman -S cmake
for manjaro operating system.
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();
}
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.
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.
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
You can achieve that in most pythonic way like that:
python3:
"{:0.0f}".format(num)
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) {
}
});
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;
};
In addition to backslash, if a line ends with |
or &&
or ||
, it will be continued on the next line.
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
.
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))]
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',)
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
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
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:
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.
Make sure that you have put a log4j2.*
file instead of a log4j.*
file under .../src/main/resources
folder.
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);
}
}
"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.
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!
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
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?
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
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.
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
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.
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 :)
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.
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']);
});
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");
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.
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.
I'm pretty late to the party, but here is another implementation using ng-bootstrap: 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">×</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)'));
}
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.
.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;
}
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.
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>
Add
transport_select.setAttribute("onchange", function(){toggleSelect(transport_select_id);});
or try replacing onChange
with onchange
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:
"public ModelAndView doSomething() { return new ModelAndView("home") }"
)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:
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?
What about [AllowHtml]
attribute above property?
Bytes are transparently converted to ints.
Just say
int i= rno[0];
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.
For null or undefined value error, Just add this line to attributes : ,columnDefs: [ { "defaultContent": "-", "targets": "_all" } ]
Example :
oTable = $("#bigtable").dataTable({
columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
_x000D_
The alert box will not show again, any empty values will be replaced with what you specified.
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 NSString
s, just NSMutableString
s, or a mix of the two. If sortedSourceArray
instead contains just NSNumber
s or just NSDate
s, 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 NSString
s, NSNumber
s, and/or NSDate
s, it will probably crash.
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
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:
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
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.)
From the Jinja2 template designer documentation:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
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.
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)
}
}
For PHP - this Work for me on Chrome, safari and firefox
header('Access-Control-Allow-Origin: null');
using axios call php live services with file://
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
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.
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;
}
There is no such thing: I recommend to write it for yourself and use it whenever you need.
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.
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.
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
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.
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;
}
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.
Python has a min()
built-in function:
>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828
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;
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.)
<form>.WindowState = FormWindowState.Minimized;
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...)
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);
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.
If you want an synchronous request set the async
property to false
for the request. Check out the jQuery AJAX Doc
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
(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:
gson.toJson(value)
will serialize your object into its equivalent Json representation. gson.fromJson
will convert the Json string to specified object. (in this example - Map
)There are 2 advantages with this approach:
toJson
method.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]
}
]
}
]
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]
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
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.
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_
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.
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();
}
}
in
is definitely more pythonic.
In fact has_key()
was removed in Python 3.x.
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
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)
$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);
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.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.
Updated for 2020: Yes, it can be done! Here's how.
Snippet demo:
#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_
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.
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.
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
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.
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;
}
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.
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>
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();
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
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.
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.
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
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:
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.
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 onlyv
: visual and selecto
: operator-pendingx
: visual onlys
: select onlyi
: insertc
: command-linel
: 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:
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.
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;
I prefer going the long route. These are the checks I follow to avoid using a try-except clause -
Here, DATA
is the suspect variable -
DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty
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
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' ],
};
You can import environments into any file such as services clientUtilServices.ts
import {environment} from '../../environments/environment';
getHostURL(): string {
return environment.apiHost;
}
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
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)
}
}
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);
}
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.
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.
Using the credentials helper command-line option:
git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin
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;
}
}
Note that this may also work:
SELECT * FROM table WHERE s=ANY(array)
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.
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!
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.
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.
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.
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
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.
Easy Workaround (no VBA required)
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.
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
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)()
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.
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.
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)
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();
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.
Select everything, or whatever you want to re-indent and do Alt+ E+L+R. This is really quick and painless.
From sun docs:
\s A whitespace character: [ \t\n\x0B\f\r]
The simplest way is to use it with regex.
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.
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".
Try:
#your_div_id {
width: 855px;
margin:0 auto;
text-align: center;
}
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
.
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();
}
}
}
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)
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
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.
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.
Write a Boolean function that checks the regex and use apply on the column
foo[foo['b'].apply(regex_function)]
As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:
compilerOptions
in your tsconfig.json
file:"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
import myData from '../assets/data/my-data.json';
And that's it. You can now use myData
in your components/services.
Google recommend that you don't use any of them, source.
There is no need to use entity references like
&mdash
,&rdquo
, or☺
, 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 "
?
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.
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.
I had this error happen when I had 2 scripts I was running. I had:
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.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
In the run configuration you want to customize (just click on it) open the tab Arguments
and add -Xmx2048m
in the VM arguments section.
You might want to set the -Xms
as well (small heap size).
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.
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()
}
}
}
<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>
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.
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>
There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:
print(f"{1:03}")
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).
I use docker stats $(docker ps --format={{.Names}}) --no-stream
to get :
Well, you're on the right path, Benno!
There are some tips regarding VBA programming that might help you out.
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.
As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.
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
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
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);
}
}
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.
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()
{
}
}
}
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.
As said in the comments, the problem lies in your script. Actually, there are 2 problems:
None
somewhere. Maybe due to the defaultdict ?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.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 {
//...
}
Try using the solution suggested here: https://www.drupal.org/node/1129120
patch -p1 < example.patch
This helped me .
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)
Interesting question.
This would be my approach.
Hope it helps.
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
.
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 ....).
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
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)
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
Visual Studio Code, menu File → Preference → Settings → search for "trim":
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.
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
Try pasting this code in CMD:
keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
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;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
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}"
}
==
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.
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
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.
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);
}
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 { }
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.
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
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.
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.
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)
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%
Your code can simplified a lot to
$('img', resp).attr('src', function(idx, urlRelative ) {
return self.config.proxy_server + self.config.location_images + urlRelative;
});
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)
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());
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.
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.
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 :)
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;
From user @jamylak an alternative form of open("filename","w").close()
is
with open('filename.txt','w'): pass